/* ========================================================================
   pages-generate.jsx — Pack Generator + Output Viewer
   ====================================================================== */

/* ---------------------------------------------------------------- GENERATOR */
function GeneratePage() {
  const { runGeneration, generatedSet, currentProject } = React.useContext(AppCtx);
  const [picked, setPicked] = React.useState(PACK_TYPES[0]);
  const [platforms, setPlatforms] = React.useState(["Instagram", "TikTok", "Reels", "YouTube Shorts"]);
  const [audience, setAudience] = React.useState("App founders");
  const [tone, setTone] = React.useState("Premium + Punchy");
  const [variants, setVariants] = React.useState(3);
  const [format, setFormat] = React.useState("Markdown");

  const toggle = (p) => setPlatforms(ps => ps.includes(p) ? ps.filter(x => x !== p) : [...ps, p]);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Generate · {currentProject.name}</div>
          <h1 className="page-title">AI Marketing Pack <span className="hl">Generator</span></h1>
          <p className="page-sub">Pick a pack, dial in the options, and let AI write the asset set. Generations are reproducible — every run is saved as a version you can roll back to.</p>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "minmax(0, 1fr) 340px", gap: 20 }}>
        {/* Pack picker grid */}
        <div>
          <div className="row-between mb-12">
            <div className="fw-8 text-lg">Pack types</div>
            <div className="row gap-8 text-xs muted">
              <Pill icon="dot">{generatedSet.size} generated</Pill>
              <Pill>{PACK_TYPES.length} total</Pill>
            </div>
          </div>
          <div className="grid grid-3 gap-16">
            {PACK_TYPES.map(pk => (
              <PackCard key={pk.id} pack={pk} active={picked.id === pk.id} done={generatedSet.has(pk.id)} onPick={() => setPicked(pk)} />
            ))}
          </div>
        </div>

        {/* Options rail */}
        <div className="col gap-16" style={{ position: "sticky", top: 80, alignSelf: "flex-start" }}>
          <Card padding="lg">
            <div className="row gap-12">
              <div style={{ width: 44, height: 44, borderRadius: 11, background: "var(--yellow)", display: "grid", placeItems: "center", flex: "none" }}>
                <Icon name={picked.icon} size={20} color="var(--yellow-ink)" stroke={2.2} />
              </div>
              <div>
                <div className="fw-8" style={{ fontSize: 16, letterSpacing: "-0.015em" }}>{picked.name}</div>
                <div className="muted text-xs">{picked.time} · {picked.items}</div>
              </div>
            </div>
            <div className="muted text-sm mt-12">{picked.desc}</div>
          </Card>

          <Card title="Options" padding="lg">
            <div className="col gap-16">
              <Field label="Platforms">
                <div className="chip-row">
                  {["Instagram", "TikTok", "Reels", "YouTube Shorts", "Facebook", "LinkedIn", "X"].map(p => (
                    <button key={p} className={"chip" + (platforms.includes(p) ? " active chip-yellow" : "")} onClick={() => toggle(p)}>{p}</button>
                  ))}
                </div>
              </Field>
              <Field label="Audience segment">
                <select className="select" value={audience} onChange={e => setAudience(e.target.value)}>
                  <option>App founders</option>
                  <option>SaaS builders</option>
                  <option>No-code builders</option>
                  <option>Agencies</option>
                  <option>All audiences (default)</option>
                </select>
              </Field>
              <Field label="Tone">
                <select className="select" value={tone} onChange={e => setTone(e.target.value)}>
                  <option>Premium + Punchy</option>
                  <option>Founder / personal</option>
                  <option>Punchy launch energy</option>
                  <option>Educational</option>
                </select>
              </Field>
              <Field label="Variants per asset" sub={`Generates ${variants} versions of every output.`}>
                <div className="row gap-12">
                  <input type="range" min="1" max="5" value={variants} onChange={e => setVariants(+e.target.value)} style={{ flex: 1, accentColor: "var(--fg)" }} />
                  <span className="fw-8 text-lg" style={{ width: 24, textAlign: "center" }}>{variants}</span>
                </div>
              </Field>
              <Field label="Output format">
                <div className="row gap-6" style={{ flexWrap: "wrap" }}>
                  {["Markdown", "PDF", "CSV", "JSON", "ZIP"].map(f => (
                    <button key={f} className={"chip" + (format === f ? " active" : "")} onClick={() => setFormat(f)}>{f}</button>
                  ))}
                </div>
              </Field>
            </div>
          </Card>

          <Btn variant="primary" icon="sparkle" style={{ width: "100%", padding: "12px 14px", fontSize: 14 }} onClick={() => runGeneration(picked)}>
            Generate {picked.name}
          </Btn>
          <div className="muted text-xs center">Approx {picked.time} · cost ~£0.14 in AI credits</div>
        </div>
      </div>
    </div>
  );
}

function PackCard({ pack, active, done, onPick }) {
  return (
    <button onClick={onPick}
      className="card"
      style={{
        padding: 0, textAlign: "left",
        borderColor: active ? "var(--fg)" : "var(--border)",
        boxShadow: active ? "0 0 0 3px var(--yellow), var(--shadow)" : "var(--shadow-sm)",
        transition: "box-shadow .14s, border-color .14s, transform .14s",
        cursor: "pointer", overflow: "hidden",
      }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.boxShadow = "var(--shadow-lg)"; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.boxShadow = "var(--shadow-sm)"; }}
    >
      <div className="card-pad-lg">
        <div className="row-between" style={{ alignItems: "flex-start" }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: pack.featured ? "var(--fg)" : "var(--yellow)", display: "grid", placeItems: "center" }}>
            <Icon name={pack.icon} size={18} color={pack.featured ? "var(--yellow)" : "var(--yellow-ink)"} stroke={2.2} />
          </div>
          {done && <Pill variant="green" icon="check">Generated</Pill>}
          {pack.featured && !done && <Pill variant="dark"><Icon name="bolt" size={11} stroke={2.2} />Most popular</Pill>}
        </div>
        <div className="fw-8 mt-12" style={{ fontSize: 15, letterSpacing: "-0.015em" }}>{pack.name}</div>
        <div className="muted text-xs mt-4" style={{ minHeight: 32 }}>{pack.desc}</div>
        <div className="hr mt-16 mb-12" />
        <div className="row-between text-xs">
          <span className="muted">{pack.time}</span>
          <span className="fw-7">{pack.items}</span>
        </div>
      </div>
    </button>
  );
}

/* ---------------------------------------------------------------- OUTPUT VIEWER */
function OutputViewerPage() {
  const { selectedPackForOutput, setSelectedPackForOutput, go, generatedSet, showToast, runGeneration, currentProject } = React.useContext(AppCtx);
  // Map pack id -> route id for the in-app viewers
  const route = {
    full: "social", social: "social", instagram: "social",
    video: "video",
    appstore: "appstore",
    ads: "ads",
    landing: "landing",
    seo: "seo",
    claude: "claude-prompts",
    codex: "codex-prompts",
  };

  const available = PACK_TYPES.filter(p => generatedSet.has(p.id));
  const current = PACK_TYPES.find(p => p.id === selectedPackForOutput) || available[0] || PACK_TYPES[0];
  const generatedOutput = React.useMemo(() => {
    try {
      const all = JSON.parse(localStorage.getItem("boltkit.generatedContent") || "{}");
      return all[current.id] || null;
    } catch (e) {
      return null;
    }
  }, [current.id, generatedSet]);
  const [version, setVersion] = React.useState("v3");
  const versionKey = `boltkit.versions.${current.id}`;
  const defaultVersions = [
    { v: "v3", t: "Latest · 12 min ago", note: "Tightened hooks, removed emoji", active: true },
    { v: "v2", t: "Yesterday", note: "Re-ran after new screenshots" },
    { v: "v1", t: "3 days ago", note: "First pass" },
  ];
  const [versions, setVersions] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(versionKey) || "null") || defaultVersions; }
    catch (e) { return defaultVersions; }
  });
  React.useEffect(() => {
    try { setVersions(JSON.parse(localStorage.getItem(versionKey) || "null") || defaultVersions); }
    catch (e) { setVersions(defaultVersions); }
    setVersion("v3");
  }, [current.id]);
  const contentText = React.useMemo(() => {
    if (generatedOutput?.content_markdown) return generatedOutput.content_markdown;
    if (generatedOutput?.content_json) return JSON.stringify(generatedOutput.content_json, null, 2);
    if (current.id === "video") return SAMPLE_VIDEOS.map(v => `${v.title}\nDuration: ${v.duration}\nScenes: ${v.scenes}`).join("\n\n");
    if (current.id === "ads") return SAMPLE_ADS.meta.map(ad => `${ad.head}\n${ad.body}\nCTA: ${ad.cta}`).join("\n\n");
    if (current.id === "appstore") return `${SAMPLE_APPSTORE.title}\n${SAMPLE_APPSTORE.subtitle}\n\n${SAMPLE_APPSTORE.description}`;
    if (current.id === "landing") return `${SAMPLE_LANDING.hero_h}\n${SAMPLE_LANDING.hero_sub}\n\n${SAMPLE_LANDING.vp}`;
    if (current.id === "seo") return [...SAMPLE_SEO.titles, SAMPLE_SEO.meta, ...SAMPLE_SEO.blogs].join("\n");
    if (current.id === "claude") return CLAUDE_PROMPTS.map(p => `${p.name}: ${p.purpose}`).join("\n\n");
    if (current.id === "codex") return CODEX_PROMPTS.map(p => `${p.name}: ${p.stack}`).join("\n\n");
    return SAMPLE_INSTAGRAM.map(p => `${p.hook}\n${p.body}\n${p.hashtags || ""}`).join("\n\n");
  }, [current.id, generatedOutput]);
  const copyAll = () => {
    try { navigator.clipboard.writeText(contentText); } catch (e) {}
    showToast("Copied generated content");
  };
  const improve = () => {
    const next = [{ v: `v${versions.length + 1}`, t: "Just now", note: "Improved in demo mode", active: true }, ...versions.map(v => ({ ...v, active: false }))];
    setVersions(next);
    localStorage.setItem(versionKey, JSON.stringify(next));
    setVersion(next[0].v);
    showToast("Improved output and saved a new version");
  };
  const saveVersion = () => {
    const next = [{ v: `v${versions.length + 1}`, t: "Just now", note: "Manual save", active: true }, ...versions.map(v => ({ ...v, active: false }))];
    setVersions(next);
    localStorage.setItem(versionKey, JSON.stringify(next));
    setVersion(next[0].v);
    showToast("Version saved locally");
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Outputs · {currentProject.name}</div>
          <h1 className="page-title">Output <span className="hl">Viewer</span></h1>
          <p className="page-sub">All generated packs, every version, with quality and brand-fit scores. Open any pack to read, regenerate or export.</p>
        </div>
        <div className="row gap-8">
          <Btn variant="secondary" icon="history">Version history</Btn>
          <Btn variant="secondary" icon="download" onClick={() => go("exports")}>Export selected</Btn>
        </div>
      </div>

      <div className="card mb-24" style={{ padding: 6 }}>
        <div className="row" style={{ gap: 4, overflowX: "auto" }}>
          {available.map(p => (
            <button key={p.id}
              onClick={() => setSelectedPackForOutput(p.id)}
              className="row gap-8"
              style={{
                padding: "8px 12px", borderRadius: 8, flexShrink: 0,
                background: current.id === p.id ? "var(--fg)" : "transparent",
                color: current.id === p.id ? "white" : "var(--fg)",
                fontWeight: 700, fontSize: 13,
              }}>
              <Icon name={p.icon} size={14} color={current.id === p.id ? "var(--yellow)" : "var(--fg-muted)"} />
              {p.name}
            </button>
          ))}
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "minmax(0, 1fr) 300px", gap: 20 }}>
        <div className="col gap-16">
          <Card padding="lg">
            <div className="row-between" style={{ flexWrap: "wrap", gap: 12 }}>
              <div>
                <div className="fw-8" style={{ fontSize: 18, letterSpacing: "-0.015em" }}>{current.name}</div>
                <div className="muted text-xs mt-4">{generatedOutput ? `Generated ${new Date(generatedOutput.savedAt).toLocaleString()} · ${generatedOutput.mode}` : `Ready to generate · ${current.items} · ${current.tone} tone`}</div>
              </div>
              <div className="row gap-6" style={{ flexWrap: "wrap" }}>
                <Btn size="sm" variant="ghost" icon="refresh" onClick={() => runGeneration(current)}>Regenerate</Btn>
                <Btn size="sm" variant="ghost" icon="sparkle" onClick={improve}>Improve</Btn>
                <Btn size="sm" variant="secondary" icon="copy" onClick={copyAll}>Copy all</Btn>
                <Btn size="sm" variant="primary" icon="download" onClick={() => go("exports")}>Export</Btn>
              </div>
            </div>
          </Card>

          {/* Preview body — route to the relevant in-app viewer page */}
          {generatedOutput
            ? <Card padding="lg"><div className="ai-chip"><Icon name="sparkle" size={11} stroke={2.2} />{generatedOutput.mode || "generated"}</div><div className="fw-8 mt-12" style={{ fontSize: 18 }}>{generatedOutput.title || current.name}</div><pre className="generated-preview">{contentText}</pre></Card>
            : current.id === "full" || current.id === "social" || current.id === "instagram"
            ? <SocialPreview compact />
            : current.id === "video" ? <VideoPreview compact />
            : current.id === "appstore" ? <AppStorePreview compact />
            : current.id === "ads" ? <AdsPreview compact />
            : current.id === "landing" ? <LandingPreview compact />
            : current.id === "seo" ? <SeoPreview compact />
            : current.id === "claude" ? <PromptsPreview kind="claude" compact />
            : current.id === "codex" ? <PromptsPreview kind="codex" compact />
            : <GenericPreview pack={current} />}

          <Card padding="lg">
            <div className="row-between mb-16">
              <div className="fw-8">Full content</div>
              <Btn size="sm" variant="ghost" icon="star" onClick={saveVersion}>Save version</Btn>
            </div>
            <div className="col gap-12">
              {!generatedOutput && SAMPLE_INSTAGRAM.map((p, i) => (
                <div key={i} style={{ padding: 14, border: "1px solid var(--border)", borderRadius: 10 }}>
                  <div className="row-between">
                    <div className="row gap-8"><Pill variant="dark"><Icon name="insta" size={11} stroke={2.2} />{p.kind}</Pill><span className="muted text-xs">Quality {p.score}</span></div>
                    <div className="row gap-4"><IconBtn icon="copy" /><IconBtn icon="refresh" /><IconBtn icon="star" /></div>
                  </div>
                  <div className="fw-8 mt-8" style={{ fontSize: 15 }}>{p.hook}</div>
                  <div className="mt-8 text-sm" style={{ whiteSpace: "pre-line", lineHeight: 1.55 }}>{p.body}</div>
                  <div className="muted text-xs mono mt-12">{p.hashtags}</div>
                </div>
              ))}
              {generatedOutput && (
                <div style={{ padding: 14, border: "1px solid var(--border)", borderRadius: 10 }}>
                  <div className="row-between"><Pill variant="yellow">Generated content</Pill><IconBtn icon="copy" onClick={copyAll} /></div>
                  <pre className="generated-preview">{contentText}</pre>
                </div>
              )}
            </div>
          </Card>
        </div>

        {/* Right rail */}
        <div className="col gap-16">
          <Card title="Scores">
            <div className="col gap-12 mt-4">
              <ScoreRow label="Quality" value={92} tone="green" />
              <ScoreRow label="Brand match" value={94} tone="yellow" />
              <ScoreRow label="Tone fit" value={88} tone="yellow" />
              <ScoreRow label="Hook strength" value={76} tone="blue" />
            </div>
          </Card>

          <Card title="Version history" sub={`${versions.length} versions saved`}>
            <div className="col gap-4">
              {versions.map(v => (
                <button key={v.v} onClick={() => setVersion(v.v)}
                  className="row-between"
                  style={{ padding: 10, borderRadius: 8, background: version === v.v ? "var(--surface-2)" : "transparent", width: "100%", textAlign: "left" }}>
                  <div>
                    <div className="row gap-8"><span className="mono fw-8 text-xs">{v.v}</span>{v.active && <Pill variant="yellow">Active</Pill>}</div>
                    <div className="muted text-xs mt-4">{v.t} · {v.note}</div>
                  </div>
                  <Icon name="chevron_right" size={14} stroke={2} color="var(--fg-muted)" />
                </button>
              ))}
            </div>
          </Card>

          <Card title="Open in pack viewer">
            <div className="col gap-6">
              <Btn variant="secondary" iconRight="arrow_right" onClick={() => go(route[current.id] || "social")}>
                Open {current.name} viewer
              </Btn>
              <Btn variant="ghost" icon="share">Share preview link</Btn>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function ScoreRow({ label, value, tone }) {
  return (
    <div>
      <div className="row-between text-sm">
        <span className="muted fw-6">{label}</span>
        <span className="fw-8">{value}</span>
      </div>
      <div className="meter mt-4"><span style={{ width: value + "%", background: tone === "green" ? "var(--green)" : tone === "blue" ? "var(--blue)" : "var(--yellow)" }} /></div>
    </div>
  );
}

function GenericPreview({ pack }) {
  return (
    <Card padding="lg">
      <div className="ai-surface card-pad" style={{ textAlign: "center" }}>
        <div className="ai-chip"><Icon name="sparkle" size={11} stroke={2.2} />Pack ready</div>
        <div className="fw-8 mt-12" style={{ fontSize: 18 }}>{pack.name}</div>
        <div className="muted text-sm mt-8" style={{ maxWidth: 480, margin: "8px auto 0" }}>Open the dedicated viewer for this pack to see structured content, scores and per-asset edit controls.</div>
      </div>
    </Card>
  );
}

Object.assign(window, { GeneratePage, PackCard, OutputViewerPage, ScoreRow });
