// App root — state, scroll-spy, global modal.
const { useState: useS, useEffect: useE, useMemo: useM, useCallback: useC, useRef: useR } = React;

const PROGRESS_KEY = 'avg.progress.v1';

function loadProgress() {
  try {
    const raw = localStorage.getItem(PROGRESS_KEY);
    return raw ? JSON.parse(raw) : {};
  } catch (e) { return {}; }
}
function saveProgress(p) {
  try { localStorage.setItem(PROGRESS_KEY, JSON.stringify(p)); } catch (e) {}
}

function App() {
  const [progress, setProgress] = useS(() => loadProgress());
  const [active, setActive] = useS(STEPS[0].id);
  const [sidebarOpen, setSidebarOpen] = useS(false);
  const [askOpen, setAskOpen] = useS(false);
  const [scrolled, setScrolled] = useS(false);

  useE(() => { saveProgress(progress); }, [progress]);

  const toggle = useC((id) => {
    setProgress(p => ({ ...p, [id]: !p[id] }));
  }, []);
  const resetProgress = useC(() => {
    if (confirm('Reset progress on all 8 scenes?')) setProgress({});
  }, []);

  // Scroll spy — track which section is closest to top
  useE(() => {
    const ALL_IDS = [
      ...PROLOGUE.map(p => p.id),
      ...STEPS.map(s => s.id),
      ...EPILOGUE.map(e => e.id),
      ...EDU_NAV.map(e => e.id),
    ];
    const els = ALL_IDS.map(id => document.getElementById(id)).filter(Boolean);
    if (!els.length) return;

    const onScroll = () => {
      const top = window.scrollY + 140;
      let cur = els[0].id;
      for (const el of els) {
        if (el.offsetTop <= top) cur = el.id;
        else break;
      }
      setActive(cur);
      setScrolled(window.scrollY > 320);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const onJump = useC((id) => {
    setSidebarOpen(false);
    const el = document.getElementById(id);
    if (el) {
      window.scrollTo({ top: el.offsetTop - 16, behavior: 'smooth' });
      setActive(id);
    }
  }, []);

  const completedCount = useM(() => Object.values(progress).filter(Boolean).length, [progress]);
  const pct = Math.round((completedCount / STEPS.length) * 100);

  // Step body map
  const BODY = { step1: Step1Body, step2: Step2Body, step3: Step3Body, step4: Step4Body,
                 step5: Step5Body, step6: Step6Body, step7: Step7Body, step8: Step8Body };
  // Context the assistant gets per step (kept short — the prose is loaded on page already, this is for grounding)
  const stepContext = (s) => `Scene ${s.n}: ${s.title}. (${s.frame}). Estimated time: ${s.time}.`;

  return (
    <>
      <div className="mobile-bar">
        <button className="menu-btn" onClick={() => setSidebarOpen(true)}>
          <Icon d={Icons.menu} size={14} stroke={2}/> Scenes
        </button>
        <div className="progress-bar"><div className="fill" style={{ width: pct + '%' }}></div></div>
        <span className="pct">{completedCount}/{STEPS.length}</span>
      </div>

      <div className="app">
        <Sidebar progress={progress} active={active} onJump={onJump}
                 open={sidebarOpen} onClose={() => setSidebarOpen(false)}
                 onReset={resetProgress} />
        <main className="main">
          <Cover />
          <div className="main-inner">
            <Intro />
            <EducatorPreface />
            <NeedSection />
            <ThreeAsterisms />
            <PrinciplesSection />
            <ThreeAsterisms />
            {STEPS.map(s => {
              const Body = BODY[s.id];
              return (
                <StepBlock key={s.id} step={s} done={!!progress[s.id]}
                           onToggle={() => toggle(s.id)}>
                  <Body />
                  <AskBox
                    context={`This is Scene ${s.n} of the guide: "${s.title}". The scene is about: ${s.frame}.`}
                    title={`Ask about Scene ${s.n}`}
                    subtitle={`Stuck on "${s.label}"? Ask a question and a tutor will explain.`}
                    suggestions={SUGGESTIONS[s.id]}
                    compact
                  />
                </StepBlock>
              );
            })}
            <ThreeAsterisms />
            <CharactersSection />
            <WatchSection />
            <ResourcesSection />
            <ReferencesSection />
            <EducatorToolkit />
            <ClosingSection completedCount={completedCount} />
          </div>
        </main>
      </div>

      <button className={`float-ask ${scrolled ? 'show' : ''}`} onClick={() => setAskOpen(true)} aria-label="Ask the guide a question">
        <span className="pulse"><Icon d={Icons.question} size={14} stroke={2}/></span>
        <span className="label">Ask the guide</span>
      </button>

      {askOpen && (
        <div className="modal-scrim" onClick={(e) => { if (e.target.classList.contains('modal-scrim')) setAskOpen(false); }}>
          <div className="modal">
            <div className="modal-head">
              <h3>Ask anything about this guide</h3>
              <button className="close" onClick={() => setAskOpen(false)}>
                <Icon d="M6 6l12 12 M18 6L6 18" size={18} stroke={1.8}/>
              </button>
            </div>
            <div className="modal-body">
              <AskBox
                context={`The user is reading "From Blog Post to Animated Video," an 8-scene guide covering: 1) finding the visual spine, 2) picking register & style, 3) writing the brief (the longest and most important step — argument statement, cast, locations, beats, consistency rules), 4) setting up Runway Agent, 5) checking the storyboard for consistency drift, 6) animating the approved storyboard, 7) adding narration with cloned voice in ElevenLabs, 8) assembling clips and audio in CapCut and exporting. Required tools: Runway, ElevenLabs, CapCut. Optional: any general AI assistant for drafting the brief. The guide emphasizes that the brief is long because length is the consistency mechanism, that drift on characters/settings is the main failure mode, and that the first attempt is for learning, not shipping a flawless asset. For character work there are in-scene tips and an "Animated characters" section after Scene 8: a character-reference sheet (Scene 3); polishing the reference image with Magnific instead of regenerating it (Scene 4); a 3–5 second test clip before animating every beat, and specialists for some shots — Runway Act-Two for performance transfer, Kling AI or Google Veo for cinematic shots, LTX Studio for connected multi-shot scenes (Scene 6); Hedra, ElevenLabs Avatars, or Descript for characters who talk on camera (Scene 7); upscaling only the kept clips and transcript editing in Descript (Scene 8); plus a workflow recommender, a low-cost workflow, and a production pipeline.`}
                title="Open-ended help"
                subtitle="Plain English. The tutor knows the whole guide and will point you back to the right scene."
                suggestions={[
                  'How long should my first video be?',
                  'My post is purely abstract — can I still animate it?',
                  'Roughly how much does Runway cost per video?',
                  'Can I use this without cloning my voice?',
                ]}
              />
            </div>
            <div className="modal-foot">Powered by an in-page assistant. Answers reflect this guide, not external sources.</div>
          </div>
        </div>
      )}
    </>
  );
}

// Per-step suggested questions
const SUGGESTIONS = {
  step1: ['What if my post has more than one possible spine?', 'My post is mostly data — can I still find a spine?'],
  step2: ['Why is off-screen easier for a first project?'],
  step3: ['How long should my brief be?', 'Do I have to use role names instead of personal names?'],
  step4: ['9:16 or 16:9 — how do I choose?'],
  step5: ['What counts as "drift" exactly?', 'How many regenerations is normal?'],
  step6: ['What\u2019s a good per-beat motion vocabulary?', 'When should I use Act-Two instead of Runway Agent?'],
  step7: ['Is voice cloning worth it on the free tier?', 'Can my character talk on camera instead?'],
  step8: ['Any free CapCut alternatives I can use?'],
};

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