/* ========================================================================
   pages-assets.jsx — Brand Pack, Asset Library, URL Analysis
   ====================================================================== */

/* ---------------------------------------------------------------- BRAND PACK */
function BrandPackPage() {
  const { currentProject: p, showToast } = React.useContext(AppCtx);
  const palette = [
    { hex: "#EFFF00", role: "Acid",      note: "Primary CTAs, active states, hierarchy" },
    { hex: "#050505", role: "Black",     note: "App background and heavy panels" },
    { hex: "#0B0B0B", role: "Ink",       note: "Logo contrast and deep surfaces" },
    { hex: "#F4F4F0", role: "Off-white", note: "Text, cards and high-contrast copy" },
    { hex: "#ADC700", role: "Deep acid", note: "Pressed states and restrained accents" },
  ];
  const brandRules = p.brandRules || [
    "Use acid yellow as the only saturated brand colour.",
    "Keep layouts sharp, fast, practical and premium.",
    "Use diagonal panels, HUD details and broadcast-style hierarchy.",
    "Never make the logo soft, tinted, gradient-filled or generic.",
    "Prefer direct useful copy over vague SaaS filler."
  ];
  const openGuidelines = () => {
    window.open(p.brandSource || "/brand-pack/brand-pack.html", "_blank", "noopener,noreferrer");
    showToast("Opening BoltKit brand guidelines");
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Brand · {p.name}</div>
          <h1 className="page-title">Brand <span className="hl">Pack</span></h1>
          <p className="page-sub">One source of truth for how every {p.name} asset looks, sounds and behaves. AI keeps everything you generate within these guardrails.</p>
        </div>
        <div className="row gap-8">
          <Btn variant="secondary" icon="external" onClick={openGuidelines}>Open guidelines</Btn>
          <Btn variant="primary" icon="sparkle" onClick={() => showToast("Brand guidelines are loaded from the uploaded pack")}>Brand Pack Loaded</Btn>
        </div>
      </div>

      {/* Score strip */}
      <div className="grid mb-24" style={{ gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr) minmax(0,1fr)", gap: 16 }}>
        <Card padding="lg">
          <div className="row gap-16">
            <Ring value={92} size={84} thickness={8}>
              <div className="n" style={{ fontSize: 20 }}>92</div>
            </Ring>
            <div>
              <div className="text-xs uppercase muted" style={{ letterSpacing: "0.14em", fontWeight: 800 }}>Brand consistency</div>
              <div className="fw-8 mt-4" style={{ fontSize: 17 }}>Strong</div>
              <div className="muted text-xs mt-4">Last checked 2 hours ago</div>
            </div>
          </div>
        </Card>
        <Card padding="lg">
          <div className="text-xs uppercase muted" style={{ letterSpacing: "0.14em", fontWeight: 800 }}>Assets supplied</div>
          <div className="row gap-8 mt-8" style={{ alignItems: "flex-end" }}>
            <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-0.02em" }}>8<span className="muted">/10</span></div>
            <Pill variant="amber">2 missing</Pill>
          </div>
          <div className="muted text-xs mt-8">Founder demo video, App Store hero video</div>
        </Card>
        <Card padding="lg">
          <div className="text-xs uppercase muted" style={{ letterSpacing: "0.14em", fontWeight: 800 }}>Voice locked</div>
          <div className="row gap-8 mt-8" style={{ alignItems: "flex-end" }}>
            <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-0.02em" }}>v3.2</div>
            <Pill variant="green" icon="check">Active</Pill>
          </div>
          <div className="muted text-xs mt-8">5 rules enforced across generations</div>
        </Card>
      </div>

      {/* Logo + Icon */}
      <div className="grid mb-24" style={{ gridTemplateColumns: "minmax(0,2fr) minmax(0,1fr)", gap: 16 }}>
        <Card title="Logo" sub="Used in social posts, ads, press kits" padding="lg" action={<Btn size="sm" variant="ghost" icon="upload">Replace</Btn>}>
          <div className="grid grid-3 gap-16">
            <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 12, aspectRatio: "1/1", display: "grid", placeItems: "center", color: "var(--fg)", fontWeight: 800, letterSpacing: "-0.02em", fontSize: 38 }}>
              {p.name}
            </div>
            <div style={{ background: "var(--fg)", borderRadius: 12, aspectRatio: "1/1", display: "grid", placeItems: "center", color: "white", fontWeight: 800, letterSpacing: "-0.02em", fontSize: 38 }}>
              {p.name}
            </div>
            <div style={{ background: "var(--yellow)", borderRadius: 12, aspectRatio: "1/1", display: "grid", placeItems: "center", color: "var(--yellow-ink)", fontWeight: 800, letterSpacing: "-0.02em", fontSize: 38 }}>
              {p.name}
            </div>
          </div>
          <div className="row gap-8 mt-16">
            <Pill icon="dot">SVG</Pill>
            <Pill icon="dot">PNG ×3</Pill>
            <Pill icon="dot">FIG</Pill>
            <Pill variant="green" icon="check">License OK</Pill>
          </div>
        </Card>
        <Card title="App icon" sub="1024×1024 — used in App Store outputs" padding="lg" action={<Btn size="sm" variant="ghost" icon="upload">Replace</Btn>}>
          <div className="row gap-12">
            <AppIcon project={p} size={96} rounded="22%" />
            <div className="col gap-6">
              <Pill icon="check">1024×1024 PNG</Pill>
              <Pill icon="check">Adaptive (Android)</Pill>
              <Pill icon="check">macOS variant</Pill>
            </div>
          </div>
        </Card>
      </div>

      {/* Palette */}
      <div className="grid mb-24" style={{ gridTemplateColumns: "minmax(0,1.4fr) minmax(0,1fr)", gap: 16 }}>
        <Card title="Brand palette" sub="Locked. AI never invents new colours."
          padding="lg"
          action={<div className="row gap-8"><Btn size="sm" variant="ghost" icon="plus">Add colour</Btn><Btn size="sm" variant="secondary" icon="copy">Export tokens</Btn></div>}
        >
          <div className="grid" style={{ gridTemplateColumns: "repeat(5, minmax(0,1fr))", gap: 12 }}>
            {palette.map(c => (
              <div key={c.hex}>
                <div className="swatch" style={{ background: c.hex }}>
                  <span className="hex">{c.hex.toUpperCase()}</span>
                </div>
                <div className="fw-7 text-sm mt-8">{c.role}</div>
                <div className="muted text-xs">{c.note}</div>
              </div>
            ))}
          </div>
          <div className="hr mt-20 mb-16" />
          <div className="ai-surface card-pad">
            <div className="row-between" style={{ flexWrap: "wrap", gap: 12 }}>
              <div>
                <span className="ai-chip"><Icon name="sparkle" size={11} stroke={2.2} />AI-extracted from screenshots</span>
                <div className="fw-7 mt-8 text-sm">3 candidate colours found — none significantly diverge from your locked palette.</div>
              </div>
              <Btn variant="dark" icon="sparkle" onClick={() => showToast("Re-extracted palette · no drift")}>Extract Colours with AI</Btn>
            </div>
            <div className="row gap-12 mt-16">
              {["#FFE600", "#FFF3B0", "#1E1E1E"].map(h => (
                <div key={h} className="row gap-8" style={{ padding: "6px 10px", background: "white", border: "1px solid var(--border)", borderRadius: 99 }}>
                  <span style={{ width: 14, height: 14, borderRadius: 4, background: h }} />
                  <span className="mono text-xs fw-7">{h}</span>
                  <span className="text-xs muted">match</span>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card title="Typography" padding="lg">
          <Field label="Heading"><input className="input" defaultValue={p.fonts?.heading || "Anton"} /></Field>
          <div className="mt-12" style={{ fontFamily: "'Anton', Impact, sans-serif", fontWeight: 400, fontSize: 32, letterSpacing: "0", lineHeight: 1.05 }}>
            UPLOAD YOUR APP.<br />GENERATE THE PACK.
          </div>
          <div className="hr mt-16 mb-16" />
          <Field label="Body"><input className="input" defaultValue={p.fonts?.body || "Inter"} /></Field>
          <div className="mt-12 muted" style={{ fontSize: 14, lineHeight: 1.6 }}>
            {p.name} is {p.tagline || "a launch-ready app"}. Keep copy practical, specific and aligned to the brand rules.
          </div>
          <div className="hr mt-16 mb-16" />
          <Field label="Mono"><input className="input" defaultValue={p.fonts?.mono || "JetBrains Mono"} /></Field>
          <div className="mt-12 mono" style={{ fontSize: 13, color: "var(--fg-muted)" }}>PACK-READY · AI-GENERATED · ZIP-EXPORT</div>
        </Card>
      </div>

      {/* Voice + Rules */}
      <div className="grid grid-2 gap-16">
        <Card title="Brand voice" sub="Used by AI on every generation" padding="lg" action={<Btn size="sm" variant="ghost" icon="edit">Edit</Btn>}>
          <textarea className="textarea" style={{ minHeight: 180, lineHeight: 1.7 }}
            defaultValue={p.tone || "Premium, fast, practical, high-energy, motorsport-inspired and direct."} />
        </Card>
        <Card title="Brand rules" sub="Hard guardrails for the model" padding="lg" action={<Btn size="sm" variant="ghost" icon="plus">Add rule</Btn>}>
          <div className="col gap-8">
            {brandRules.map((rule, i) => (
              <div key={i} className="row-between" style={{ padding: 10, border: "1px solid var(--border)", borderRadius: 9 }}>
                <div className="row gap-10">
                  <Icon name="shield" size={14} color="var(--fg)" />
                  <span className="text-sm fw-6">{rule}</span>
                </div>
                <Pill>{i < 2 ? "Core" : "Guardrail"}</Pill>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------- ASSETS */
function AssetsPage() {
  const { showToast, currentProject } = React.useContext(AppCtx);
  const assetInputRef = React.useRef(null);
  const [filter, setFilter] = React.useState("All");
  const [selected, setSelected] = React.useState(0);
  const [assetQuery, setAssetQuery] = React.useState("");
  const [localAssets, setLocalAssets] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("boltkit.assets") || "[]"); }
    catch (e) { return []; }
  });
  const filters = ["All", "Logo", "Icon", "Screenshot", "Brand", "Video", "Other"];
  const baseAssets = [];
  const assets = [...localAssets, ...baseAssets];
  const filteredByType = filter === "All" ? assets : assets.filter(a => a.type === filter);
  const filtered = assetQuery.trim()
    ? filteredByType.filter(a => `${a.name} ${a.type} ${a.screen}`.toLowerCase().includes(assetQuery.trim().toLowerCase()))
    : filteredByType;
  const cur = filtered[selected] || filtered[0];
  const inferType = (file) => {
    const name = file.name.toLowerCase();
    if (name.includes("logo") || name.endsWith(".svg")) return "Logo";
    if (name.includes("icon")) return "Icon";
    if (file.type.startsWith("video/")) return "Video";
    if (name.includes("brand") || name.endsWith(".pdf")) return "Brand";
    if (file.type.startsWith("image/")) return "Screenshot";
    return "Other";
  };
  const addFiles = (files) => {
    const next = [...files].map(file => {
      const type = inferType(file);
      return {
        id: `${Date.now()}-${file.name}`,
        name: file.name,
        type,
        screen: type === "Screenshot" ? "Uploaded screen" : "—",
        dim: file.type.startsWith("image/") ? "Local preview" : "Local file",
        size: `${Math.max(1, Math.round(file.size / 1024))} KB`,
        suggested: type === "Screenshot" ? ["App Store", "Social", "Landing Page"] : ["All packs"],
        local: true,
        previewUrl: file.type.startsWith("image/") ? URL.createObjectURL(file) : null,
      };
    });
    setLocalAssets(prev => {
      const updated = [...next, ...prev];
      const persistable = updated.map(({ previewUrl, ...asset }) => asset);
      try { localStorage.setItem("boltkit.assets", JSON.stringify(persistable)); } catch (e) {}
      return updated;
    });
    setFilter("All");
    setSelected(0);
    showToast(`${next.length} asset${next.length === 1 ? "" : "s"} staged locally`);
  };
  const removeAsset = (asset) => {
    if (!asset.local) {
      showToast("Demo assets are locked. Uploaded assets can be removed.");
      return;
    }
    setLocalAssets(prev => {
      const updated = prev.filter(item => item.id !== asset.id);
      try { localStorage.setItem("boltkit.assets", JSON.stringify(updated.map(({ previewUrl, ...a }) => a))); } catch (e) {}
      return updated;
    });
    setSelected(0);
    showToast("Asset removed locally");
  };
  const loadTestMaterials = () => {
    const materials = [
      { id: "brand-pack-boltkit-html", name: "brand-pack.html", type: "Brand", screen: "Brand guidelines", dim: "HTML source", size: "18 KB", suggested: ["All packs"], local: true, sourceUrl: "/brand-pack/brand-pack.html", notes: "Canonical BoltKit brand pack from the uploaded ZIP: black, off-white and electric acid yellow; Anton, Bebas Neue, Inter and JetBrains Mono; sharp lightning identity; motorsport/esports/broadcast direction." },
      { id: "brand-pack-boltkit-zip", name: "boltkit-brand-pack.zip", type: "Brand", screen: "Original upload", dim: "ZIP archive", size: "Uploaded", suggested: ["Brand", "Exports"], local: true, sourcePath: "assets/brand-pack/boltkit-brand-pack.zip", notes: "Original Claude Design brand pack ZIP copied into assets/brand-pack for handoff." },
      { id: "logo-boltkit", name: "boltkit-logo.svg", type: "Logo", screen: "Wordmark", dim: "Vector", size: "2 KB", suggested: ["All packs"], local: true },
      { id: "screenshot-dashboard", name: "boltkit-dashboard-screenshot.png", type: "Screenshot", screen: "Dashboard", dim: "Local reference", size: "180 KB", suggested: ["Landing Page", "Social", "Ads"], local: true },
      { id: "url-notes", name: "website-url-and-positioning.txt", type: "Other", screen: "URL notes", dim: "Text", size: "1 KB", suggested: ["Analysis", "SEO", "Landing Page"], local: true, notes: "URL: http://localhost:5174/ Promise: Upload your app. Generate the launch pack." }
    ];
    setLocalAssets(materials);
    localStorage.setItem("boltkit.assets", JSON.stringify(materials));
    setSelected(0);
    showToast("BoltKit brand pack and test materials staged locally");
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Library · {filtered.length} of {assets.length}</div>
          <h1 className="page-title">Assets</h1>
          <p className="page-sub">Every screenshot, logo and brand file the AI has to work with. AI tags each by screen type and suggests where it's most useful.</p>
        </div>
        <div className="row gap-8">
          <Btn variant="secondary" icon="brain">Re-tag with AI</Btn>
          <Btn variant="secondary" icon="package" onClick={loadTestMaterials}>Load brand pack</Btn>
          <Btn variant="primary" icon="upload" onClick={() => assetInputRef.current?.click()}>Upload assets</Btn>
          <input ref={assetInputRef} type="file" multiple style={{ display: "none" }} onChange={event => addFiles(event.target.files || [])} />
        </div>
      </div>

      <div className="mb-16">
        <div className="drop" onDragOver={event => event.preventDefault()} onDrop={event => { event.preventDefault(); addFiles(event.dataTransfer.files || []); }}>
          <Icon name="upload" size={22} color="var(--yellow)" />
          <div>
            <div className="fw-8">Drop assets anywhere on this zone</div>
            <div className="muted text-sm">PNG, JPG, SVG, PDF, MP4 · auto-detected and tagged for {currentProject.name}</div>
          </div>
        </div>
      </div>

      <div className="row-between mb-16" style={{ flexWrap: "wrap", gap: 12 }}>
        <div className="chip-row">
          {filters.map(f => (
            <button key={f} className={"chip" + (filter === f ? " active chip-yellow" : "")} onClick={() => { setFilter(f); setSelected(0); }}>{f}</button>
          ))}
        </div>
        <div className="input-with-icon" style={{ minWidth: 240 }}>
          <Icon name="search" size={15} className="ico" />
          <input className="input" placeholder="Search assets…" value={assetQuery} onChange={event => { setAssetQuery(event.target.value); setSelected(0); }} />
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "minmax(0, 1fr) 360px", gap: 16, alignItems: "flex-start" }}>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))", gap: 12 }}>
          {filtered.length === 0 && (
            <Card padding="lg" style={{ gridColumn: "1 / -1" }} title="No assets yet" sub="Upload a logo, screenshots, app icon or brand pack to give AI more useful context.">
              <div className="muted text-sm">The workspace starts clean. Drag files into the upload zone above or use the Upload assets button.</div>
            </Card>
          )}
          {filtered.map((a, i) => (
            <button key={a.name} onClick={() => setSelected(i)} style={{ textAlign: "left", padding: 0, background: "none" }}>
              <div className={"thumb" + (i === selected ? "" : "")}
                style={{
                  borderColor: i === selected ? "var(--fg)" : "var(--border)",
                  boxShadow: i === selected ? "0 0 0 3px var(--yellow)" : "var(--shadow-sm)",
                  aspectRatio: a.type === "Logo" || a.type === "Icon" ? "1/1" : "9/19",
                  background: a.type === "Logo" ? "var(--surface-2)" : a.type === "Icon" ? "var(--surface-3)" : undefined,
                }}>
                {a.previewUrl && <img src={a.previewUrl} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />}
                {!a.previewUrl && a.type === "Logo" && <div style={{ fontWeight: 800, fontSize: 18, letterSpacing: "-0.02em", color: "var(--fg)" }}>{currentProject.name}</div>}
                {!a.previewUrl && a.type === "Icon" && <AppIcon project={currentProject} size={56} />}
                {a.type === "Screenshot" && <span className="label">{a.screen}</span>}
              </div>
              <div className="row-between mt-8 text-xs">
                <span className="fw-7" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</span>
                <span className="muted">{a.size}</span>
              </div>
            </button>
          ))}
        </div>

        {/* Detail side panel */}
        {cur ? <Card title={cur.name} sub={`${cur.type} · ${cur.dim}`} action={<IconBtn icon="trash" onClick={() => removeAsset(cur)} />} padding="lg">
          <div className="thumb" style={{ aspectRatio: cur.type === "Screenshot" ? "9/19" : "1/1", marginBottom: 16 }}>
            {cur.previewUrl && <img src={cur.previewUrl} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />}
            {!cur.previewUrl && cur.type === "Logo" && <div style={{ fontWeight: 800, fontSize: 24, letterSpacing: "-0.02em" }}>{currentProject.name}</div>}
            {!cur.previewUrl && cur.type === "Icon" && <AppIcon project={currentProject} size={80} />}
            {!cur.previewUrl && cur.type === "Screenshot" && <span className="label">{cur.screen}</span>}
          </div>
          <span className="ai-chip"><Icon name="sparkle" size={11} stroke={2.2} />AI detected</span>
          <div className="grid grid-2 gap-8 mt-12 text-sm">
            <div><div className="text-xs muted fw-7 uppercase" style={{ letterSpacing: "0.12em" }}>Screen type</div><div className="fw-7 mt-4">{cur.screen}</div></div>
            <div><div className="text-xs muted fw-7 uppercase" style={{ letterSpacing: "0.12em" }}>File type</div><div className="fw-7 mt-4">{cur.type}</div></div>
            <div><div className="text-xs muted fw-7 uppercase" style={{ letterSpacing: "0.12em" }}>Dimensions</div><div className="fw-7 mt-4 mono text-xs">{cur.dim}</div></div>
            <div><div className="text-xs muted fw-7 uppercase" style={{ letterSpacing: "0.12em" }}>Size</div><div className="fw-7 mt-4">{cur.size}</div></div>
          </div>
          <div className="hr mt-16 mb-16" />
          <div className="text-xs muted fw-7 uppercase mb-8" style={{ letterSpacing: "0.12em" }}>Features detected</div>
          <div className="chip-row mb-16">
            {cur.type === "Screenshot" ? ["Launch Command Centre", "Generate flow", "Export centre"].map(f => <span key={f} className="chip">{f}</span>)
              : <span className="chip">—</span>}
          </div>
          <div className="text-xs muted fw-7 uppercase mb-8" style={{ letterSpacing: "0.12em" }}>Suggested use</div>
          <div className="chip-row">
            {cur.suggested.map(s => <span key={s} className="chip active chip-yellow">{s}</span>)}
          </div>
          <div className="hr mt-16 mb-16" />
          {cur.sourceUrl && <Btn variant="secondary" size="sm" icon="external" onClick={() => window.open(cur.sourceUrl, "_blank", "noopener,noreferrer")}>Open source file</Btn>}
          {cur.sourceUrl && <div className="hr mt-16 mb-16" />}
          <Field label="Notes"><textarea className="textarea" placeholder="e.g. use this as the App Store hero because it shows the launch pack output clearly." /></Field>
          <div className="row gap-8 mt-16"><Btn variant="primary" size="sm" icon="sparkle" onClick={() => showToast(`${cur.name} queued for next pack`)}>Use in next pack</Btn><Btn variant="secondary" size="sm" icon="download" onClick={() => showToast(cur.local ? "Local browser uploads cannot be re-downloaded yet" : "Demo asset download placeholder")}>Download</Btn></div>
        </Card> : <Card title="Asset details" sub="Nothing selected" padding="lg"><div className="muted text-sm">Upload an asset to inspect detected type, suggested use and notes.</div></Card>}
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------- URL ANALYSIS */
function AnalysisPage() {
  const { currentProject, go, showToast } = React.useContext(AppCtx);
  const [phase, setPhase] = React.useState("idle"); // idle | running | done
  const [url, setUrl] = React.useState(currentProject.url || "https://");
  const [analysis, setAnalysis] = React.useState(null);

  const run = async () => {
    setPhase("running");
    try {
      const assets = JSON.parse(localStorage.getItem("boltkit.assets") || "[]");
      const res = await fetch("/api/analyse-project", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ project: { ...currentProject, url, assets } })
      });
      const data = await res.json();
      if (data.ok) {
        setAnalysis(data.analysis);
        showToast(`Analysis complete · ${data.mode}`);
      } else {
        showToast(data.error || "Analysis failed");
      }
    } catch (e) {
      showToast("Analysis failed");
    }
    setPhase("done");
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">AI Analysis</div>
          <h1 className="page-title">URL &amp; App <span className="hl">Analysis</span></h1>
          <p className="page-sub">Paste a URL and the AI reads the live page, your screenshots and your brand pack to build the foundation for every generated pack.</p>
        </div>
      </div>

      {/* URL input */}
      <Card padding="lg" className="mb-24">
        <div className="grid" style={{ gridTemplateColumns: "minmax(0,1fr) auto auto", gap: 8, alignItems: "stretch" }}>
          <div className="input-with-icon">
            <Icon name="globe" size={15} className="ico" />
            <input className="input" value={url} onChange={e => setUrl(e.target.value)} placeholder="https://" />
          </div>
          <Btn variant="secondary" icon="link">Add screenshots</Btn>
          <Btn variant="primary" icon="brain" onClick={run} disabled={phase === "running"}>{phase === "running" ? "Analysing…" : "Analyse"}</Btn>
        </div>
        {phase === "running" && (
          <div className="mt-16">
            <div className="row gap-8 text-sm fw-6"><div className="spinner" /> <span>Reading page · crawling 4 screenshots · cross-referencing brand pack…</span></div>
            <div className="gen-bar mt-12"><span /></div>
          </div>
        )}
        <div className="row gap-8 mt-16 text-xs muted" style={{ flexWrap: "wrap" }}>
          <Pill icon={analysis ? "check" : "dot"}>{analysis ? "Analysed this session" : "Not analysed yet"}</Pill>
          <Pill icon="dot">{(() => { try { return JSON.parse(localStorage.getItem("boltkit.assets") || "[]").length; } catch(e) { return 0; } })()} sources merged</Pill>
          <Pill icon="dot">{currentProject.features?.length || 0} features detected</Pill>
          <Pill icon="dot">{currentProject.missing || 0} missing assets</Pill>
        </div>
      </Card>

      {phase !== "running" && (
        <div className="grid" style={{ gridTemplateColumns: "minmax(0,1fr) 320px", gap: 20 }}>
          <div className="col gap-16">
            <Card padding="lg" title="Positioning" sub={`AI · how ${currentProject.name} is currently positioned`}>
              <div className="ai-surface card-pad">
                <div className="row gap-8" style={{ flexWrap: "wrap" }}>
                  <span className="ai-chip ai-chip-soft">Calm</span>
                  <span className="ai-chip ai-chip-soft">Companion</span>
                  <span className="ai-chip ai-chip-soft">Practical</span>
                  <span className="ai-chip ai-chip-soft">Mobile-first</span>
                  <span className="ai-chip ai-chip-soft">Lightly premium</span>
                  <span className="ai-chip ai-chip-soft">UK English</span>
                </div>
                <div className="mt-12 text-sm" style={{ lineHeight: 1.6 }}>
                  {analysis?.app_summary || currentProject.summary}
                </div>
              </div>
            </Card>

            <Card padding="lg" title="App summary" action={<Btn size="sm" variant="ghost" icon="copy">Copy</Btn>}>
              <div style={{ fontSize: 15, lineHeight: 1.65 }}>{analysis?.app_summary || currentProject.summary}</div>
            </Card>

            <Card padding="lg" title="Features detected" sub="From your URL, screenshots and feature notes" action={<Btn size="sm" variant="ghost" icon="refresh">Re-extract</Btn>}>
              <div className="grid grid-2 gap-10">
                {(currentProject.features || []).map(f => (
                  <div key={f} className="row gap-10" style={{ padding: 10, background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 9 }}>
                    <div style={{ width: 22, height: 22, borderRadius: 6, background: "var(--yellow)", display: "grid", placeItems: "center" }}>
                      <Icon name="bolt" size={12} color="var(--yellow-ink)" />
                    </div>
                    <span className="fw-7 text-sm" style={{ flex: 1 }}>{f}</span>
                    <Icon name="check_circle" size={14} color="var(--green)" />
                  </div>
                ))}
              </div>
            </Card>

            <div className="grid grid-2 gap-16">
              <Card title="Target users" padding="lg">
                <div className="text-sm muted">{analysis?.audience_summary || currentProject.audience}</div>
              </Card>
              <Card title="Pain points" padding="lg">
                <div className="text-sm muted">{(analysis?.pain_points || [currentProject.pain]).join(" ")}</div>
              </Card>
            </div>

            <Card title="Benefits" sub="Features turned into outcomes" padding="lg">
              <div className="grid grid-2 gap-10">
                {(analysis?.benefits || currentProject.benefits || []).map((b, i) => (
                  <div key={b.t || b || i} className="row gap-10" style={{ padding: 12, border: "1px solid var(--border)", borderRadius: 10, alignItems: "flex-start" }}>
                    <Icon name="check_circle" size={16} color="var(--green)" />
                    <div className="text-sm">{typeof b === "string" ? b : <><strong>{b.t}.</strong> <span className="muted">{b.s}</span></>}</div>
                  </div>
                ))}
              </div>
            </Card>
          </div>

          <div className="col gap-16">
            <Card padding="lg" style={{ background: "var(--fg)", color: "white", borderColor: "var(--fg)" }}>
              <div className="text-xs uppercase" style={{ color: "var(--yellow)", letterSpacing: "0.16em", fontWeight: 800 }}>Readiness</div>
              <div className="row gap-16 mt-12" style={{ alignItems: "center" }}>
                <Ring value={87} size={104} thickness={9} color="var(--yellow)" track="oklch(0.28 0.005 260)">
                  <div className="n" style={{ color: "white" }}>87<span style={{ fontSize: 13, opacity: 0.6 }}>%</span></div>
                </Ring>
                <div>
                  <div className="fw-8 text-lg">Strong</div>
                  <div className="text-xs" style={{ color: "oklch(0.78 0.008 95)" }}>Two non-blocking assets missing</div>
                </div>
              </div>
            </Card>

            <Card title="Missing marketing assets">
              <div className="col gap-8">
                {[
                  { t: "Press kit photos", v: "amber" },
                  { t: "App Store hero video", v: "amber" },
                  { t: "Twitter / X bio copy", v: "blue" },
                  { t: "Founder photo", v: "blue" },
                ].map((m, i) => (
                  <div key={i} className="row gap-10" style={{ padding: 10, border: "1px solid var(--border)", borderRadius: 9 }}>
                    <Icon name="alert" size={14} color={m.v === "amber" ? "var(--amber)" : "var(--blue)"} />
                    <span className="text-sm fw-6" style={{ flex: 1 }}>{m.t}</span>
                    <Pill variant={m.v}>{m.v === "amber" ? "Required" : "Nice to have"}</Pill>
                  </div>
                ))}
              </div>
            </Card>

            <Card title="Suggested pack next">
              <button className="row-between" onClick={() => go("generate")} style={{ width: "100%", padding: 12, border: "1px solid var(--border)", borderRadius: 10, textAlign: "left", background: "var(--yellow-soft)" }}>
                <div className="row gap-10">
                  <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--fg)", display: "grid", placeItems: "center" }}>
                    <Icon name="rocket" size={15} color="var(--yellow)" />
                  </div>
                  <div>
                    <div className="fw-8 text-sm">Full Launch Pack</div>
                    <div className="muted text-xs">~4 min · 120–160 assets</div>
                  </div>
                </div>
                <Icon name="arrow_right" size={14} stroke={2} />
              </button>
              <Btn variant="ghost" iconRight="arrow_right" onClick={() => go("generate")}>Or pick another</Btn>
            </Card>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { BrandPackPage, AssetsPage, AnalysisPage });
