// Main UI components.
const { useState, useEffect, useRef, useCallback, useMemo } = React;

/* ============================================================
   STEP META — used by sidebar & step rendering
   ============================================================ */
const STEPS = [
  { id: 'step1', n: 1, kicker: 'Scene One',   label: 'Find the spine',     title: 'Read your post and find the visual spine', time: '15 min', frame: 'Pre-production · A blank page, a finished post', objective: 'Identify one recurring image, place, or object that can carry the post\u2019s argument across beats.' },
  { id: 'step2', n: 2, kicker: 'Scene Two',   label: 'Register & style',   title: 'Pick your register and style',             time: '10 min', frame: 'Pre-production · Choosing the aesthetic', objective: 'Decide on-screen vs. off-screen narrator and lock an aesthetic anchored to an existing visual reference.' },
  { id: 'step3', n: 3, kicker: 'Scene Three', label: 'Write the brief',    title: 'Write the brief',                          time: '30\u201360 min', frame: 'The longest scene \u2014 and the most important', objective: 'Translate the post into a four-part brief: argument, cast, locations, beats \u2014 with explicit consistency rules.' },
  { id: 'step4', n: 4, kicker: 'Scene Four',  label: 'Setup Runway',       title: 'Set up Runway Agent',                      time: '10 min', frame: 'Open the studio · Load the brief', objective: 'Configure a Runway Agent session with the right reference image, aspect ratio, duration, and audio setting.' },
  { id: 'step5', n: 5, kicker: 'Scene Five',  label: 'Consistency check',  title: 'Review the storyboard for consistency',    time: '20 min', frame: 'Compare frames · catch the drift', objective: 'Evaluate character, setting, and aesthetic consistency; direct targeted regenerations to fix drift.' },
  { id: 'step6', n: 6, kicker: 'Scene Six',   label: 'Animate',            title: 'Tell the agent to animate',                time: '20 min', frame: 'The frames begin to move', objective: 'Specify per-beat motion (character vs. camera) that matches the argument\u2019s pacing.' },
  { id: 'step7', n: 7, kicker: 'Scene Seven', label: 'Narration',          title: 'Add narration in ElevenLabs',              time: '15 min', frame: 'The voice over the visual', objective: 'Select two or three landing lines from the post; clone or pick a voice; direct the read.' },
  { id: 'step8', n: 8, kicker: 'Scene Eight', label: 'Assemble',           title: 'Assemble in CapCut',                       time: '15 min', frame: 'Cut · sync · export', objective: 'Sequence clips, place narration where visuals can\u2019t carry the meaning alone, and export at target resolution.' },
];

const PROLOGUE = [
  { id: 'educators', label: 'For educators',   title: 'Two ways to use this guide' },
  { id: 'need',       label: 'Tools you\u2019ll need',   title: 'Tools & materials' },
  { id: 'principles', label: 'Two things first',         title: 'Before you start' },
];

const EPILOGUE = [
  { id: 'characters',  label: 'Animated characters',      title: 'Animated characters: picking tools by job' },
  { id: 'watch',      label: 'Where it goes sideways',   title: 'Where it tends to go sideways' },
  { id: 'resources',   label: 'All resources',            title: 'All resources, in one place' },
  { id: 'references',  label: 'References',               title: 'References & further reading' },
];

const EDU_NAV = [
  { id: 'edu-toolkit',    label: 'Educator\u2019s toolkit' },
  { id: 'edu-rubric',     label: 'Rubric' },
  { id: 'edu-class',      label: 'Class structures' },
  { id: 'edu-policy',     label: 'AI-use policy' },
  { id: 'edu-a11y',       label: 'Accessibility' },
  { id: 'edu-hardware',   label: 'Hardware & access' },
  { id: 'edu-pitfalls',   label: 'Student pitfalls' },
  { id: 'edu-discussion', label: 'Discussion prompts' },
];

/* ============================================================
   COVER
   ============================================================ */
function Cover() {
  return (
    <header className="cover">
      <span className="cover-shape shape-rule" aria-hidden="true"></span>
      <span className="cover-shape shape-corner-tl" aria-hidden="true"></span>
      <span className="cover-shape shape-corner-br" aria-hidden="true"></span>
      <div className="ornament-row">
        <span className="line"></span>
        <Asterism color="var(--gold)" />
        <span className="line"></span>
      </div>
      <p className="kicker">An Interactive Workshop · For Artists Who Write</p>
      <h1>
        From Blog Post to <em>Animated&nbsp;Video</em>
      </h1>
      <p className="subtitle">
        A beginner-friendly walk-through for turning a piece of writing into a short
        animated video, without losing the argument or your mind.
      </p>
      <div className="meta-row">
        <span className="meta-chip"><Icon d={Icons.clock} size={14}/> 2&ndash;3 hrs first time</span>
        <span className="meta-chip"><Icon d={Icons.film} size={14}/> 8 scenes</span>
        <span className="meta-chip"><Icon d={Icons.brush} size={14}/> AI-assisted, hand-edited</span>
      </div>
    </header>
  );
}

/* ============================================================
   SIDEBAR
   ============================================================ */
function Sidebar({ progress, active, onJump, open, onClose, onReset }) {
  const completedCount = Object.values(progress).filter(Boolean).length;
  const pct = Math.round((completedCount / STEPS.length) * 100);

  return (
    <>
      <div className={`sidebar-backdrop ${open ? 'open' : ''}`} onClick={onClose}></div>
      <aside className={`sidebar ${open ? 'open' : ''}`}>
        <div className="brand">
          <div className="brand-mark">
            <Icon d={Icons.film} size={18} stroke={1.8} />
          </div>
          <div className="brand-text">
            Studio Notes
            <small>The Workshop</small>
          </div>
        </div>

        <div className="progress-summary">
          <div className="label">Your progress</div>
          <div className="count"><em>{completedCount}</em>&thinsp;/&thinsp;{STEPS.length} scenes</div>
          <div className="progress-bar"><div className="fill" style={{ width: pct + '%' }}></div></div>
        </div>

        <div className="nav-section-label">Before you begin</div>
        <div className="nav-list">
          {PROLOGUE.map(item => (
            <a key={item.id} className={`nav-item ${active === item.id ? 'active' : ''}`}
               href={`#${item.id}`} onClick={(e) => { onJump(item.id); }}>
              <span className="nav-num">·</span>
              <span className="nav-label">{item.label}</span>
              <span></span>
            </a>
          ))}
        </div>

        <div className="nav-section-label">The eight scenes</div>
        <div className="nav-list">
          {STEPS.map(s => (
            <a key={s.id} className={`nav-item ${active === s.id ? 'active' : ''} ${progress[s.id] ? 'done' : ''}`}
               href={`#${s.id}`} onClick={() => onJump(s.id)}>
              <span className="nav-num">{String(s.n).padStart(2, '0')}</span>
              <span className="nav-label">{s.label}</span>
              <span className="nav-check">
                {progress[s.id] && <Icon d={Icons.check} size={9} stroke={2.5}/>}
              </span>
            </a>
          ))}
        </div>

        <div className="nav-section-label">After you ship</div>
        <div className="nav-list">
          {EPILOGUE.map(item => (
            <a key={item.id} className={`nav-item ${active === item.id ? 'active' : ''}`}
               href={`#${item.id}`} onClick={() => onJump(item.id)}>
              <span className="nav-num">·</span>
              <span className="nav-label">{item.label}</span>
              <span></span>
            </a>
          ))}
        </div>

        <div className="nav-section-label nav-section-edu">For educators</div>
        <div className="nav-list">
          {EDU_NAV.map(item => (
            <a key={item.id} className={`nav-item nav-item-edu ${active === item.id ? 'active' : ''}`}
               href={`#${item.id}`} onClick={() => onJump(item.id)}>
              <span className="nav-num">{item.id === 'edu-toolkit' ? '\u2756' : '\u00b7'}</span>
              <span className="nav-label">{item.label}</span>
              <span></span>
            </a>
          ))}
        </div>

        <div className="sidebar-footer">
          <button className="reset-btn" onClick={onReset}>↺ Reset progress</button>
        </div>
      </aside>
    </>
  );
}

/* ============================================================
   STEP HEADER
   ============================================================ */
function StepHeader({ step, done, onToggleDone }) {
  return (
    <div className="step-header">
      <div className="step-numeral">{String(step.n).padStart(2, '0')}</div>
      <div className="step-text">
        <div className="step-kicker">
          {step.kicker} <span className="est">· {step.time}</span>
        </div>
        <h2>{step.title}</h2>
        {step.objective && (
          <div className="step-objective">
            <span className="step-objective-label">Learning objective</span>
            <span className="step-objective-text">{step.objective}</span>
          </div>
        )}
      </div>
      <button className="complete-btn" onClick={onToggleDone}
              aria-pressed={done}>
        <span className="dot">{done && <Icon d={Icons.check} size={8} stroke={2.5}/>}</span>
        {done ? 'Completed' : 'Mark complete'}
      </button>
    </div>
  );
}

/* ============================================================
   COLLAPSIBLE PROMPT BLOCK (with copy button)
   ============================================================ */
function PromptBlock({ label, code, defaultExpanded = false }) {
  const [expanded, setExpanded] = useState(defaultExpanded);
  const [copied, setCopied] = useState(false);
  const onCopy = useCallback(() => {
    navigator.clipboard?.writeText(code).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    }).catch(() => {});
  }, [code]);

  return (
    <div className="prompt-block">
      <div className="prompt-label">
        <span>{label}</span>
        <button className={`copy-btn ${copied ? 'copied' : ''}`} onClick={onCopy}>
          {copied ? <><Icon d={Icons.check} size={11} stroke={2.5}/> Copied</> :
                    <><Icon d={Icons.copy} size={11}/> Copy</>}
        </button>
      </div>
      <div className={`prompt-content ${expanded ? 'expanded' : ''}`}>{code}</div>
      <button className="prompt-expand" onClick={() => setExpanded(e => !e)}>
        {expanded ? 'Collapse ▴' : 'Expand to read fully ▾'}
      </button>
    </div>
  );
}

/* ============================================================
   CHECK YOUR UNDERSTANDING
   ============================================================ */
function Checkup({ question, answer }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="checkup">
      <div className="checkup-label">
        <Icon d={Icons.bulb} size={12}/> Check your understanding
      </div>
      <p className="checkup-q">{question}</p>
      {!open && (
        <button className="checkup-reveal" onClick={() => setOpen(true)}>
          Reveal the answer <Icon d={Icons.arrowRight} size={12}/>
        </button>
      )}
      {open && <div className="checkup-a">{answer}</div>}
    </div>
  );
}

Object.assign(window, { STEPS, PROLOGUE, EPILOGUE, Cover, Sidebar, StepHeader, PromptBlock, Checkup });
