/* ===========================================================================
   wizard.jsx — guided create flow (pure component; shell owns step + store)
   props: step, next, back, store, showToast, goLibrary
   =========================================================================== */
const W = window.STUDIO;

const WIZ_STEP_LABELS = ["Target", "Their playbook", "What works", "Your opening", "Your ad"];
const PROOF = W.ads.filter((a) => a.best).slice(0, 3);

const WHY = [
  { hook: "“POV: You finally found a vitamin your kid doesn't spit out.”",
    why: "It names the exact struggle — a kid who rejects everything — and hands the parent permission to stop trying. The product becomes the answer, not another thing to test.",
    meta: "Their #1 hook" },
  { hook: "“No mess, no mixing, no gagging.”",
    why: "It kills the real objection: the ritual. Next to powders and pills, the gummy feels effortless — and that single line has run for 128 days straight.",
    meta: "128 days running" },
  { hook: "“Because parenting is hard enough already.”",
    why: "It bonds with the buyer's exhaustion, so the ad reads as empathy instead of a pitch. People don't feel sold to — they feel seen.",
    meta: "Emotional anchor" },
];

const PRIMARY_ANGLE = {
  id: "comparison-vs-powder",
  title: "Powder vs. gummy comparison",
  note: "Nobody's running a side-by-side. “Powder: messy, gritty, $40 a jar. SuperMush: pop and go.” The friction angle is wide open.",
};
const GAP_MINI = [
  "A real taste test on camera — “tastes like strawberry, not dirt.” No competitor shows the product being eaten.",
  "A founder transformation — Alli's own focus, before and after. Authentic, and impossible to copy.",
];

function Wizard({ step, next, back, store }) {
  const { useState } = React;
  const [target, setTarget] = useState("gruns");
  const [analyzing, setAnalyzing] = useState(false);
  const genScripts = W.scripts.filter((s) => s.generated);
  const [genIdx, setGenIdx] = useState(0);

  const comp = W.competitors.find((c) => c.id === target);
  const script = genScripts[genIdx];
  const angleSaved = store.angles.some((a) => a.id === PRIMARY_ANGLE.id);
  const inShotList = store.shot.some((s) => s.id === script.id);

  const body = () => {
    switch (step) {
      case 0: return (
        <div className="wiz-anim">
          <div className="eyebrow"><Icon name="spy" size={13}/> SuperMush Ad Studio</div>
          <h1 className="wiz-title">Who should we study?</h1>
          <p className="wiz-sub">Pick a competitor. We'll break down what's working in their ads and hand you a creative you can film today — no guesswork.</p>
          <div className="wiz-body">
            {W.competitors.slice(0, 4).map((c) => {
              const ready = c.id === "gruns";
              const sel = target === c.id;
              return (
                <div key={c.id} className={`opt ${sel ? "sel" : ""} ${ready ? "" : "locked"}`} onClick={() => ready && setTarget(c.id)}>
                  <div className="comp-logo" style={{ background: c.swatch, width: 38, height: 38, flex: "0 0 38px", fontSize: 16, borderRadius: 9 }}>{c.name[0]}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 15 }}>{c.name}</div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>{c.category}</div>
                  </div>
                  <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 12 }}>
                    {ready ? <Chip tone="olive" dot="#3f9d6b">Analyzed</Chip> : <Chip tone="ghost">Queued</Chip>}
                    <div className="opt-check">{sel && <Icon name="check" size={13} stroke={3}/>}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      );
      case 1: return (
        <div className="wiz-anim">
          <div className="eyebrow"><Icon name="spy" size={13}/> What we found · {comp.name}</div>
          <h1 className="wiz-title">Grüns sells calm<br/>to exhausted parents.</h1>
          <p className="wiz-sub">Their whole library leans on one feeling: <i>parenting is hard — this is one less thing to worry about.</i> They wrap it in relatable humor, influencer trust, and tidy benefit lists. The adult line has run the same static ad for 128 days.</p>
          <div className="wiz-body">
            <div className="section-label"><Icon name="trophy" size={13}/> Their longest-running ads</div>
            <div className="proof-grid">
              {PROOF.map((a) => (
                <div className="proof" key={a.id}>
                  <AdThumb ad={a}/>
                  <div className="proof-cap"><span className="pc-adv">{a.advertiser}</span><span className="pc-days">{a.days}d</span></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      );
      case 2: return (
        <div className="wiz-anim">
          <div className="eyebrow"><Icon name="hook" size={13}/> Why it converts</div>
          <h1 className="wiz-title">Three hooks doing<br/>all the work.</h1>
          <p className="wiz-sub">Strip away the production and every winning ad runs on one of these. This is the part worth stealing — the angle, not the asset.</p>
          <div className="wiz-body">
            {WHY.map((w, i) => (
              <div className="why-row" key={i}>
                <div className="why-hook">{w.hook}</div>
                <div className="why-text">{w.why}</div>
                <div className="why-meta"><Chip tone="orange"><Icon name="bolt" size={11}/> {w.meta}</Chip></div>
              </div>
            ))}
          </div>
        </div>
      );
      case 3: return (
        <div className="wiz-anim">
          <div className="eyebrow"><Icon name="gap" size={13}/> Your opening</div>
          <h1 className="wiz-title">The angle nobody's running.</h1>
          <p className="wiz-sub">Grüns wins on parent-empathy and influencer trust. But across the whole category, these plays are wide open — and they fit a founder-led mushroom brand perfectly.</p>
          <div className="wiz-body">
            <div className="gap-primary">
              <div className="gp-tag">Biggest opportunity</div>
              <div className="gp-text">{PRIMARY_ANGLE.note}</div>
              <div style={{ marginTop: 15 }}>
                {angleSaved
                  ? <button className="btn gold sm" disabled style={{ opacity: 0.95 }}><Icon name="check" size={14} stroke={3}/> Angle approved</button>
                  : <button className="btn primary sm" onClick={() => { store.saveAngle(PRIMARY_ANGLE); store.toast("Angle approved", { label: "View angles", fn: () => store.goLibrary("angles") }); }}><Icon name="check" size={14}/> Approve this angle</button>}
              </div>
            </div>
            <div style={{ marginTop: 18 }}>
              {GAP_MINI.map((g, i) => (
                <div className="gap-mini" key={i}>
                  <span className="gm-ico"><Icon name="arrow" size={16}/></span>
                  <span className="gm-text">{g}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      );
      case 4: return (
        <div className="wiz-anim">
          <div className="eyebrow"><Icon name="sparkle" size={13}/> Made for you · Higgsfield + AI</div>
          <h1 className="wiz-title">Here's your ad.</h1>
          <p className="wiz-sub">We took Grüns' best hook, flipped it for mushrooms, and generated a frame to match. Hand it to Alli and shoot.</p>
          <div className="wiz-body">
            <div className="make-grid">
              <div>
                <GenFrame script={script} ratio="4/5"/>
                <div style={{ marginTop: 10, fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-faint)", textAlign: "center" }}>{script.format} · {script.length}</div>
              </div>
              <div className="make-script">
                <div className="ai-note" style={{ marginBottom: 18 }}>
                  <div className="ai-tag"><Icon name="hook" size={12}/> Inspired by</div>{script.inspired}
                </div>
                <div className="make-beat"><div className="mb-label">Hook · 0–3s</div><div className="mb-hook">“{script.hook}”</div></div>
                <div className="make-beat"><div className="mb-label">Body</div><div className="mb-body">{script.body}</div></div>
                <div className="make-beat"><div className="mb-label">CTA</div><div className="mb-body" style={{ marginBottom: 7 }}>{script.cta}</div><span className="make-overlay">Overlay: “{script.ctaOverlay}”</span></div>
              </div>
            </div>
          </div>
        </div>
      );
      default: return null;
    }
  };

  const footer = () => {
    if (step === 0) return (
      <>
        <span className="grow"/>
        <button className="btn primary" disabled={analyzing} onClick={() => { setAnalyzing(true); setTimeout(() => { setAnalyzing(false); next(); }, 700); }}>
          {analyzing ? <><Icon name="sparkle" size={15}/> Analyzing…</> : <>Study {comp.name} <Icon name="arrow" size={15}/></>}
        </button>
      </>
    );
    if (step === 4) return (
      <>
        <button className="btn ghost" onClick={back}><Icon name="arrowLeft" size={15}/> Back</button>
        <span className="grow"/>
        <button className="btn" onClick={() => { setGenIdx((i) => (i + 1) % genScripts.length); window.scrollTo(0, 0); }}><Icon name="wand" size={15}/> Generate another angle</button>
        {inShotList
          ? <button className="btn primary" onClick={() => store.goLibrary("shot")}><Icon name="check" size={15} stroke={3}/> In shot list — view</button>
          : <button className="btn primary" onClick={() => { store.addShot(script.id); store.toast("Sent to Alli's shot list", { label: "View shot list", fn: () => store.goLibrary("shot") }); }}><Icon name="video" size={15}/> Send to Alli</button>}
      </>
    );
    return (
      <>
        <button className="btn ghost" onClick={back}><Icon name="arrowLeft" size={15}/> Back</button>
        <span className="grow"/>
        <button className="btn primary" onClick={next}>Continue <Icon name="arrow" size={15}/></button>
      </>
    );
  };

  return (
    <>
      <div className="wiz-stage"><div className="wiz-col" key={step}>{body()}</div></div>
      <div className="wiz-foot"><div className="wiz-foot-inner">{footer()}</div></div>
    </>
  );
}

Object.assign(window, { Wizard, WIZ_STEP_LABELS });
