/* ============== App orchestrator — مكتبة نور ==============
   Bridges the Three.js scene with the React overlay, owns app state,
   and implements the "click a book → the boy walks over → it opens" flow.
   ========================================================================= */
const { useState: uS, useEffect: uE, useRef: uR } = React;

const ASSETS = {
  logo:  'assets/images/logo-mark.png',
  hero:  'assets/images/welcome-hero.png',
  rug:   'assets/images/arabesque-tile.png',
};

const THEMES = {
  amber:   { accent:'#e0a838', deep:'#b9791b', soft:'#ffeccb', glow:'#ffd98a', bg:'#241a12' },
  emerald: { accent:'#3f9d6d', deep:'#2e7d52', soft:'#d8f0e2', glow:'#a7e3bd', bg:'#15231b' },
  night:   { accent:'#6f8cf0', deep:'#4257b8', soft:'#dde4ff', glow:'#a9bcff', bg:'#141a2a' },
};
const FONTS = {
  rounded: "'Baloo Bhaijaan 2', system-ui, sans-serif",
  clean:   "'Tajawal', system-ui, sans-serif",
  elegant: "'Aref Ruqaa', serif",
};
/* قارئ ناشئ → بطل المكتبة */
const LEVELS = ['بذرة قارئ','بذرة قارئ','قارئ ناشئ','قارئ ناشئ','عاشق الكُتب','نجم القصص','بطل المكتبة'];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "amber",
  "font": "rounded"
}/*EDITMODE-END*/;

const load = (k, d) => { try { return JSON.parse(localStorage.getItem(k)) ?? d; } catch (e) { return d; } };
const save = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} };

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const canvasRef = uR(null);
  const [loaded, setLoaded] = uS(false);
  const [welcome, setWelcome] = uS(() => !load('noor.seen', false));
  const [openId, setOpenId] = uS(null);
  const [mode, setMode] = uS(null);               // detail | reader | quiz
  const [progress, setProgress] = uS(() => load('noor.progress', { completed: [], stars: 0 }));
  const [settings, setSettings] = uS(() => load('noor.settings', { sound: true, motion: true }));
  const [showParent, setShowParent] = uS(false);
  const [showSettings, setShowSettings] = uS(false);
  const [toast, setToast] = uS(null);
  const [confetti, setConfetti] = uS(false);
  const [aloudOn, setAloudOn] = uS(false);
  const aloudTimer = uR(null);
  const pendingId = uR(null);
  const toastTimer = uR(null);

  const rooms = window.ROOMS;
  const book = openId ? window.BOOKS.find(b => b.id === openId) : null;
  const roomObj = book ? rooms.find(r => r.id === book.room) : null;

  const flashToast = (msg) => { setToast(msg); clearTimeout(toastTimer.current); toastTimer.current = setTimeout(() => setToast(null), 3600); };

  /* ---- init Three.js scene once ---- */
  uE(() => {
    let cancelled = false;
    const startScene = () => {
      if (cancelled) return;
      // scene.js is an ES module — it may define window.LibraryScene slightly after Babel runs
      if (!canvasRef.current || !window.LibraryScene) { setTimeout(startScene, 60); return; }
      window.LibraryScene.init(canvasRef.current, {
      onReady: () => {
        setLoaded(true);
        const th = THEMES[t.theme];
        window.LibraryScene.setTheme({ accent: th.accent, glow: th.glow, bg: th.bg });
        window.LibraryScene.setMotion(settings.motion);
        window.LibraryScene.setRugTexture(ASSETS.rug);
        load('noor.progress', { completed: [] }).completed.forEach(id => window.LibraryScene.markRead(id));
      },
      // click a glowing book → walk the boy there (scene handles the walk),
      // tell the child to head over, then open when he arrives.
      onBookClick: (id) => {
        stopAloud();
        const b = window.BOOKS.find(x => x.id === id);
        pendingId.current = id;
        if (b) flashToast(`يمشي الصبيّ نحو «${b.title}»…`);
      },
      onArrived: (id) => {
        if (pendingId.current && pendingId.current !== id) return;
        pendingId.current = null;
        setOpenId(id); setMode('detail');
      },
      onHover: () => {},
      });
    };
    startScene();
    return () => { cancelled = true; };
  }, []);

  /* ---- reflect tweaks/state into scene + CSS ---- */
  const th = THEMES[t.theme];
  uE(() => {
    const root = document.documentElement;
    root.style.setProperty('--accent', th.accent);
    root.style.setProperty('--accent-deep', th.deep);
    root.style.setProperty('--accent-soft', th.soft);
    root.style.setProperty('--glow', th.glow);
    root.style.setProperty('--font-ui', FONTS[t.font]);
    if (loaded) window.LibraryScene.setTheme({ accent: th.accent, glow: th.glow, bg: th.bg });
  }, [t.theme, t.font, loaded]);

  uE(() => { if (loaded) window.LibraryScene.setMotion(settings.motion); }, [settings.motion, loaded]);
  uE(() => { if (loaded) window.LibraryScene.setPaused(mode === 'reader' || mode === 'quiz'); }, [mode, loaded]);
  uE(() => { save('noor.progress', progress); }, [progress]);
  uE(() => { save('noor.settings', settings); }, [settings]);

  /* stop ambient speech when the tab is hidden; Esc closes any open overlay */
  uE(() => {
    const onHide = () => { if (document.hidden) { clearTimeout(aloudTimer.current); window.Speech.stop(); setAloudOn(false); } };
    const onKey = (e) => {
      if (e.key === 'Escape') {
        setShowParent(false); setShowSettings(false); setOpenId(null); setMode(null);
        pendingId.current = null; window.Speech.stop(); setAloudOn(false);
        if (window.LibraryScene) window.LibraryScene.retractBooks();
      }
    };
    document.addEventListener('visibilitychange', onHide);
    window.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('visibilitychange', onHide); window.removeEventListener('keydown', onKey); };
  }, []);

  /* ---- read-aloud (ambient, for detail view) ---- */
  function stopAloud() { clearTimeout(aloudTimer.current); window.Speech.stop(); setAloudOn(false); }
  function toggleAloud(text) {
    if (aloudOn) { stopAloud(); return; }
    setAloudOn(true);
    window.Speech.speak(text, 0.9, settings.sound);
    const ms = Math.max(2600, text.length * 75);
    aloudTimer.current = setTimeout(() => stopAloud(), ms);   // actually stop the voice, not just the icon
  }

  /* ---- actions ---- */
  const closeBook = () => { stopAloud(); pendingId.current = null; setOpenId(null); setMode(null); if (window.LibraryScene) window.LibraryScene.retractBooks(); };
  const startReading = () => { stopAloud(); setMode('reader'); };
  const finishReading = () => setMode('quiz');

  const passQuiz = () => {
    const already = progress.completed.includes(openId);
    if (!already) {
      setProgress(p => ({ completed: [...p.completed, openId], stars: p.stars + 1 }));
      window.LibraryScene.markRead(openId);
      setConfetti(true); setTimeout(() => setConfetti(false), 2700);
      flashToast(`⭐ نجمة جديدة عن «${book.title}»!`);
    }
    setOpenId(null); setMode(null);
    if (window.LibraryScene) window.LibraryScene.retractBooks();
  };

  const giveHint = () => {
    const unread = window.BOOKS.find(b => !progress.completed.includes(b.id));
    if (!unread) { flashToast('لقد قرأتَ كلَّ الكتب — أنت بطل المكتبة! 🏆'); return; }
    window.LibraryScene.focusBook(unread.id);            // all shelves are visible — just pulse it
    flashToast(`ابحث عن الكتاب المتوهّج: «${unread.title}»`);
  };

  const aloudForBook = () => toggleAloud(book ? `${book.title}. ${book.blurb}` : '');
  const setSetting = (k, v) => setSettings(s => ({ ...s, [k]: v }));
  const stars = progress.stars;

  return (
    <div className="app">
      <div className="stage"><canvas ref={canvasRef} /></div>
      <div className="vignette" />

      {loaded && !welcome && (
        <React.Fragment>
          <HUD stars={stars} total={window.BOOKS.length} level={LEVELS[Math.min(stars, 6)]} logo={ASSETS.logo}
               onParent={() => setShowParent(true)} onSettings={() => setShowSettings(true)} />
          <Helpers onHint={giveHint} onAloud={() => toggleAloud('أهلاً بك في مكتبة نور. تجوّل بين الرفوف وانقُر كتاباً متوهّجاً لنقرأه معاً!')} aloudOn={aloudOn && !book} />
          {!openId && <div className="sr-hint">👆 انقر على الأرض ليمشي الصبيّ · لكلِّ ركنٍ رفُّه — انقر كتاباً متوهّجاً ليخرجَ وتقرأه</div>}
        </React.Fragment>
      )}

      {toast && <Toast>{toast.replace('💡 ','')}</Toast>}
      {confetti && <Confetti />}

      {book && (
        <ReadingPanel book={book} room={roomObj} mode={mode}
          done={progress.completed.includes(book.id)} alreadyDone={progress.completed.includes(book.id)}
          sound={settings.sound} motion={settings.motion}
          onClose={closeBook} onRead={startReading} onAloud={aloudForBook} aloudOn={aloudOn && !!book}
          onFinish={finishReading} onPass={passQuiz} />
      )}

      {showParent && (
        <Parent progress={progress} total={window.BOOKS.length} settings={settings}
          onSetting={setSetting} onClose={() => setShowParent(false)} />
      )}
      {showSettings && <Settings settings={settings} onSetting={setSetting} onClose={() => setShowSettings(false)} />}

      {welcome && <Welcome hero={ASSETS.hero} onStart={() => { setWelcome(false); save('noor.seen', true); }} />}

      <div className={`loader ${loaded ? 'hide' : ''}`}>
        <div className="bk">📚</div>
        <p>نفتحُ المكتبة…</p>
        <div className="bar"><i /></div>
      </div>

      <TweaksPanel>
        <TweakSection label="المظهر" />
        <TweakColor label="السمة" value={th.accent}
          options={[THEMES.amber.accent, THEMES.emerald.accent, THEMES.night.accent]}
          onChange={(v) => setTweak('theme', v === THEMES.emerald.accent ? 'emerald' : v === THEMES.night.accent ? 'night' : 'amber')} />
        <TweakRadio label="الخط" value={t.font}
          options={[{ value:'rounded', label:'مرِح' }, { value:'clean', label:'واضح' }, { value:'elegant', label:'أنيق' }]}
          onChange={(v) => setTweak('font', v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
