/* ========================================================================
   screens-brand-brain.jsx — Brand Brain builder + AI website analysis
   ====================================================================== */

const BB_KEY   = "boltkit.brandBrain.v1";
const PROJ_KEY = "boltkit.currentProject.v1";
const LIST_KEY = "boltkit.projectsList.v1";

const BB_EMPTY = {
  website_summary:    "",
  product_summary:    "",
  audience_summary:   "",
  brand_voice:        "",
  value_proposition:  "",
  content_themes:     [],
  keywords:           [],
  offers:             [],
  trust_signals:      [],
  pain_points:        [],
  instagram_angles:   [],
  // Visual identity — flows into every AI image prompt
  primary:            "",
  secondary:          "",
  accent:             "",
  typography:         "",
  imageBrief:         "",
  ai_raw:             null,
};

/* ── tiny helpers ───────────────────────────────────────────────── */

const readBrain = () => {
  try { return Object.assign({}, BB_EMPTY, JSON.parse(localStorage.getItem(BB_KEY) || "null")); }
  catch { return { ...BB_EMPTY }; }
};

const readProject = () => {
  try { return JSON.parse(localStorage.getItem(PROJ_KEY) || "{}") || {}; }
  catch { return {}; }
};

const saveBrainToStorage = (brain) => {
  try { localStorage.setItem(BB_KEY, JSON.stringify(brain)); } catch {}
};

const saveProjectToStorage = (proj) => {
  try {
    localStorage.setItem(PROJ_KEY, JSON.stringify(proj));
    const list = JSON.parse(localStorage.getItem(LIST_KEY) || "[]");
    const idx = list.findIndex(p => p.id === proj.id);
    if (idx >= 0) list[idx] = { ...list[idx], ...proj };
    else if (proj.id) list.unshift(proj);
    localStorage.setItem(LIST_KEY, JSON.stringify(list));
  } catch {}
};

const arrFromStr = (s) => (s || "").split(",").map(x => x.trim()).filter(Boolean);
const strFromArr = (a) => (Array.isArray(a) ? a : []).join(", ");

/* ── sub-components ─────────────────────────────────────────────── */

const FieldLabel = ({ children }) => (
  <div style={{
    fontFamily: "'JetBrains Mono', monospace",
    fontSize: 10,
    letterSpacing: "0.18em",
    textTransform: "uppercase",
    color: "#C8C8C5",
    fontWeight: 700,
    marginBottom: 6,
  }}>
    {children}
  </div>
);

const inputStyle = {
  width: "100%",
  background: "#1A1813",
  border: "1px solid #3A372F",
  borderRadius: 6,
  color: "#F4F4F0",
  fontSize: 13,
  padding: "9px 11px",
  fontFamily: "Inter, system-ui, sans-serif",
  outline: "none",
  boxSizing: "border-box",
  resize: "vertical",
  transition: "border-color 0.15s",
};

const BrainInput = ({ label, value, onChange, rows, placeholder }) => (
  <div style={{ marginBottom: 16 }}>
    <FieldLabel>{label}</FieldLabel>
    {rows ? (
      <textarea
        rows={rows}
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={inputStyle}
        onFocus={e => e.target.style.borderColor = "#EFFF00"}
        onBlur={e => e.target.style.borderColor = "#3A372F"}
      />
    ) : (
      <input
        type="text"
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={inputStyle}
        onFocus={e => e.target.style.borderColor = "#EFFF00"}
        onBlur={e => e.target.style.borderColor = "#3A372F"}
      />
    )}
  </div>
);

const TagList = ({ tags }) => (
  <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 6 }}>
    {tags.map((t, i) => (
      <span key={i} style={{
        background: "#26241E",
        border: "1px solid #3A372F",
        borderRadius: 4,
        padding: "3px 9px",
        fontSize: 11,
        color: "#C8C8C5",
        fontFamily: "'JetBrains Mono', monospace",
        letterSpacing: "0.06em",
      }}>{t}</span>
    ))}
  </div>
);

const SectionDivider = ({ label }) => (
  <div style={{
    display: "flex",
    alignItems: "center",
    gap: 10,
    margin: "20px 0 16px",
  }}>
    <div style={{ flex: 1, height: 1, background: "#3A372F" }} />
    <span style={{
      fontFamily: "'JetBrains Mono', monospace",
      fontSize: 9.5,
      letterSpacing: "0.22em",
      textTransform: "uppercase",
      color: "#5C5C5C",
      fontWeight: 700,
    }}>{label}</span>
    <div style={{ flex: 1, height: 1, background: "#3A372F" }} />
  </div>
);

/* ── empty state for right column ───────────────────────────────── */

const BrainEmptyState = ({ onAnalyse, analysing }) => (
  <div style={{
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    padding: "48px 24px",
    textAlign: "center",
    gap: 16,
  }}>
    <div style={{
      width: 56,
      height: 56,
      borderRadius: 16,
      background: "#26241E",
      border: "1px solid #3A372F",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
    }}>
      <Icon name="brain" size={24} stroke={1.5} />
    </div>
    <div>
      <div style={{
        fontFamily: "'Anton', Impact, sans-serif",
        fontSize: 22,
        textTransform: "uppercase",
        color: "#F4F4F0",
        lineHeight: 1.05,
        marginBottom: 8,
      }}>No Brand Brain Yet</div>
      <div style={{ color: "#5C5C5C", fontSize: 13, lineHeight: 1.55, maxWidth: 280 }}>
        Run website analysis to build your Brand Brain. AI will read your site and extract your brand, audience, offer, and content angles.
      </div>
    </div>
    <button
      className={"btn btn-primary" + (analysing ? " btn-analysing" : "")}
      data-bk-bound="true"
      onClick={onAnalyse}
      disabled={analysing}
      style={{ marginTop: 4 }}
    >
      {analysing
        ? <><span className="bolt-thinking" style={{ display: "inline-block" }}><BoltMini size={13} color="#1A1813" /></span> Analysing…</>
        : <><BoltMini size={13} color="#1A1813" /> Analyse Website</>
      }
    </button>
  </div>
);

/* ── main screen ─────────────────────────────────────────────────── */

const BrandBrainScreen = () => {
  const [project,   setProject]   = React.useState(() => {
    const p = readProject();
    return {
      id: p.id || "",
      name: p.name || "",
      url: p.url || p.website || "",
      product: p.product || p.description || "",
      audience: p.audience || p.targetAudience || "",
      selling_points: p.selling_points || "",
      tone_of_voice: p.tone_of_voice || p.brand_voice || "",
      avoid: p.avoid || "",
      competitors: p.competitors || "",
      instagram: p.instagram || "",
      content_goals: p.content_goals || "",
      ...p,
    };
  });

  const [brain,        setBrain]       = React.useState(readBrain);
  const [analysing,    setAnalysing]   = React.useState(false);
  const [saving,       setSaving]      = React.useState(false);
  const [brainSaved,   setBrainSaved]  = React.useState(false);
  const [drawingPhotos, setDrawingPhotos] = React.useState(false);
  const [drawnPhotos,   setDrawnPhotos]   = React.useState([]);
  const [brandAssets,   setBrandAssets]   = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("boltkit.brandAssets.v1") || "[]"); } catch { return []; }
  });
  const [assetInfluence, setAssetInfluence] = React.useState(() => {
    return localStorage.getItem("boltkit.brandInfluence.v1") || "medium";
  });
  const [brandPack, setBrandPack] = React.useState(null); // parsed Claude Design brand pack
  const [appScreenshots, setAppScreenshots] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("boltkit.appScreenshots.v1") || "[]"); } catch { return []; }
  });

  const hasBrain = Boolean(brain.website_summary || brain.product_summary || brain.value_proposition || brain.primary || brain.imageBrief || brain.typography);

  const updateProject = (key, val) => setProject(p => ({ ...p, [key]: val }));

  const saveProject = () => {
    setSaving(true);
    const updated = {
      ...readProject(),
      ...project,
      url: project.url,
      name: project.name,
      tone_of_voice: project.tone_of_voice,
    };
    saveProjectToStorage(updated);
    window.BoltKitToast?.({ msg: "Project details saved.", type: "success" });
    setTimeout(() => setSaving(false), 800);
  };

  const runAnalysis = async () => {
    if (analysing) return;
    const url = (project.url || "").trim();
    if (!url) {
      window.BoltKitToast?.({ msg: "Add a website URL first.", type: "error" });
      return;
    }

    setAnalysing(true);
    window.BoltKitToast?.({ msg: "Scanning website…", type: "loading" });

    try {
      /* Step 1 — inspect website */
      const inspectRes = await fetch("/api/inspect-website", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url, deepScan: true }),
      });
      const inspectData = await inspectRes.json();

      window.BoltKitToast?.({ msg: "Building Brand Brain…", type: "loading" });

      /* Step 2 — generate brand brain */
      const brainRes = await fetch("/api/generate-brand-brain", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          website: inspectData.extracted || inspectData,
          intake: {
            product: project.product,
            audience: project.audience,
            selling_points: project.selling_points,
            tone_of_voice: project.tone_of_voice,
            avoid: project.avoid,
            competitors: project.competitors,
            instagram: project.instagram,
            content_goals: project.content_goals,
          },
          project,
        }),
      });
      const brainData = await brainRes.json();

      const merged = Object.assign({}, BB_EMPTY, brainData.brain || brainData, { ai_raw: brainData });
      setBrain(merged);
      saveBrainToStorage(merged);
      setBrainSaved(false);
      window.BoltKitToast?.({ msg: "Brand Brain built.", type: "success" });
    } catch (err) {
      console.error("Brand Brain analysis failed", err);
      window.BoltKitToast?.({ msg: "Analysis failed — check console.", type: "error" });
    } finally {
      setAnalysing(false);
    }
  };

  const saveBrain = () => {
    saveBrainToStorage(brain);
    setBrainSaved(true);
    window.BoltKitToast?.({ msg: "Brand Brain saved.", type: "success" });
  };

  const drawPhotos = async () => {
    const url = (project.url || "").trim();
    if (!url) { window.BoltKitToast?.({ msg: "Add a website URL first.", type: "error" }); return; }
    setDrawingPhotos(true);
    setDrawnPhotos([]);
    window.BoltKitToast?.({ msg: "Drawing photos from website…", type: "loading" });
    try {
      const res = await fetch("/api/inspect-website", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url, deepScan: true }),
      });
      const data = await res.json();
      const extracted = data.extracted || data;
      const imgs = (extracted.image_urls || extracted.imageUrls || []).filter(Boolean).slice(0, 24);
      setDrawnPhotos(imgs);
      if (imgs.length) window.BoltKitToast?.({ msg: `${imgs.length} photo${imgs.length !== 1 ? "s" : ""} found.`, type: "success" });
      else window.BoltKitToast?.({ msg: "No photos found on that page.", type: "error" });
    } catch {
      window.BoltKitToast?.({ msg: "Failed to reach website.", type: "error" });
    } finally {
      setDrawingPhotos(false);
    }
  };

  const updateBrain = (key, val) => {
    setBrain(b => ({ ...b, [key]: val }));
    setBrainSaved(false);
  };

  const updateBrainArr = (key, val) => updateBrain(key, arrFromStr(val));

  const saveBrandAssets = (assets) => {
    setBrandAssets(assets);
    try { localStorage.setItem("boltkit.brandAssets.v1", JSON.stringify(assets)); } catch {}
  };

  const saveInfluence = (val) => {
    setAssetInfluence(val);
    localStorage.setItem("boltkit.brandInfluence.v1", val);
  };

  const handleAssetUpload = (e) => {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    const MAX_ASSETS = 6;
    files.slice(0, MAX_ASSETS - brandAssets.length).forEach(file => {
      if (!file.type.startsWith("image/")) return;
      const reader = new FileReader();
      reader.onload = (ev) => {
        const dataUrl = ev.target.result;
        const asset = { id: `asset-${Date.now()}-${Math.random().toString(36).slice(2)}`, name: file.name, dataUrl, addedAt: new Date().toISOString() };
        setBrandAssets(prev => {
          const updated = [...prev, asset].slice(0, MAX_ASSETS);
          try { localStorage.setItem("boltkit.brandAssets.v1", JSON.stringify(updated)); } catch {}
          return updated;
        });
      };
      reader.readAsDataURL(file);
    });
    e.target.value = "";
  };

  const removeAsset = (id) => saveBrandAssets(brandAssets.filter(a => a.id !== id));

  const saveAppScreenshots = (shots) => {
    setAppScreenshots(shots);
    try { localStorage.setItem("boltkit.appScreenshots.v1", JSON.stringify(shots)); } catch {}
  };

  const handleScreenshotUpload = (e) => {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    const MAX_SHOTS = 8;
    files.slice(0, MAX_SHOTS - appScreenshots.length).forEach(file => {
      if (!file.type.startsWith("image/")) return;
      const reader = new FileReader();
      reader.onload = (ev) => {
        const dataUrl = ev.target.result;
        const shot = { id: `shot-${Date.now()}-${Math.random().toString(36).slice(2)}`, name: file.name, dataUrl, addedAt: new Date().toISOString() };
        setAppScreenshots(prev => {
          const updated = [...prev, shot].slice(0, MAX_SHOTS);
          try { localStorage.setItem("boltkit.appScreenshots.v1", JSON.stringify(updated)); } catch {}
          return updated;
        });
      };
      reader.readAsDataURL(file);
    });
    e.target.value = "";
  };

  const removeScreenshot = (id) => saveAppScreenshots(appScreenshots.filter(s => s.id !== id));

  /* ── Brand Pack parser (Claude Design HTML export) ─────────────── */
  const parseBrandPack = (htmlString) => {
    const parser = new DOMParser();
    const doc    = parser.parseFromString(htmlString, "text/html");

    // 1. CSS custom properties from <style> tags
    const cssVars = {};
    doc.querySelectorAll("style").forEach(el => {
      const matches = [...(el.textContent || "").matchAll(/--([a-zA-Z0-9_-]+)\s*:\s*([^;}\n]+)/g)];
      matches.forEach(m => { cssVars[m[1].trim()] = m[2].trim(); });
    });

    // 2. All hex colours in the file
    const allHex = [...new Set(
      [...htmlString.matchAll(/#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})\b/g)]
        .map(m => m[0].toLowerCase())
        .filter(c => !["#ffffff","#fff","#000000","#000","#111","#222","#333","#eee","#f0f0f0","#fafafa"].includes(c))
    )];

    // 3. Font families
    const fontMatches = [...htmlString.matchAll(/font-family\s*:\s*['"]?([^'";\n,{}()]+)/gi)];
    const fonts = [...new Set(
      fontMatches.map(m => m[1].trim().replace(/['"]/g, ""))
        .filter(f => f.length > 2 && !f.toLowerCase().includes("system") && !f.toLowerCase().includes("sans-serif") && !f.toLowerCase().includes("inherit") && !f.toLowerCase().includes("var("))
    )].slice(0, 4);

    // 4. Google Fonts links (so we can load them)
    const gFontLinks = [...doc.querySelectorAll('link[href*="fonts.googleapis"]')].map(l => l.getAttribute("href")).filter(Boolean);

    // 5. SVG logos / icons — sanitize before storing (strip scripts + event handlers)
    const sanitizeSvg = (html) => html
      .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")
      .replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*)/gi, "")
      .replace(/\s+href\s*=\s*(?:"javascript:[^"]*"|'javascript:[^']*')/gi, "");
    const svgs = [...doc.querySelectorAll("svg")].map(s => {
      const clone = s.cloneNode(true);
      clone.removeAttribute("width"); clone.removeAttribute("height");
      clone.setAttribute("viewBox", clone.getAttribute("viewBox") || "0 0 100 100");
      return sanitizeSvg(clone.outerHTML);
    }).filter(s => s.length > 50).slice(0, 4);

    // 6. Smart primary/secondary/accent detection from CSS vars
    const pickVar = (...keys) => {
      for (const k of keys) {
        for (const [vk, vv] of Object.entries(cssVars)) {
          if (vk.toLowerCase().includes(k) && /^#|^rgb/.test(vv.trim())) return vv.trim();
        }
      }
      return null;
    };

    // 7. Brand name
    const brandName = (doc.querySelector("title")?.textContent || doc.querySelector("h1")?.textContent || "").trim();

    // 8. Tagline / description
    const tagline = (doc.querySelector("p")?.textContent || "").trim().slice(0, 160);

    // 9. Voice copy and tags
    const voiceText = (doc.querySelector(".voice-card p")?.textContent || "").trim().slice(0, 300);
    const voiceTags = [...doc.querySelectorAll(".vtag")].map(el => el.textContent.trim()).filter(Boolean);

    // 10. Hero subtitle / brand description
    const heroSub = (doc.querySelector(".hero .sub, .sub")?.textContent || "").trim().slice(0, 200);

    // 11. All named colour vars (non-utility)
    const namedColours = Object.entries(cssVars)
      .filter(([k, v]) => /^#[0-9A-Fa-f]{3,6}$/.test(v.trim()) && !["line","tx","surface"].some(skip => k.includes(skip)))
      .map(([k, v]) => `${k}: ${v.trim()}`)
      .slice(0, 8);

    const suggestedPrimary   = pickVar("primary", "brand", "lime", "green", "accent", "main");
    const suggestedSecondary = pickVar("secondary", "ink", "dark", "bg", "background");
    const suggestedAccent    = pickVar("accent", "hot", "highlight", "cta", "cyan");

    return {
      brandName,
      tagline,
      heroSub,
      voiceText,
      voiceTags,
      namedColours,
      cssVars,
      colours:          allHex,
      fonts,
      gFontLinks,
      svgs,
      suggestedPrimary,
      suggestedSecondary,
      suggestedAccent,
      suggestedTypography: fonts.join(", "),
    };
  };

  const handleBrandPackUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const pack = parseBrandPack(ev.target.result);
        setBrandPack(pack);
        window.BoltKitToast?.({ msg: `Brand pack loaded — ${pack.colours.length} colours, ${pack.fonts.length} fonts, ${pack.svgs.length} logo${pack.svgs.length !== 1 ? "s" : ""} found.`, type: "success" });
      } catch (err) {
        window.BoltKitToast?.({ msg: "Couldn't parse brand pack — try a different file.", type: "error" });
      }
    };
    reader.readAsText(file);
    e.target.value = "";
  };

  const applyBrandPackToBrain = () => {
    if (!brandPack) return;

    // Build a rich, Ideogram-optimised image brief from all extracted pack data
    const briefParts = [];
    if (brandPack.brandName) briefParts.push(`Brand: ${brandPack.brandName}.`);
    if (brandPack.heroSub) briefParts.push(brandPack.heroSub + ".");

    // Colour section
    const colourLines = [];
    if (brandPack.suggestedSecondary) colourLines.push(`background always ${brandPack.suggestedSecondary}`);
    if (brandPack.suggestedPrimary)   colourLines.push(`primary accent ${brandPack.suggestedPrimary}`);
    if (brandPack.namedColours && brandPack.namedColours.length > 2) {
      const extras = brandPack.namedColours
        .filter(nc => !nc.includes(brandPack.suggestedPrimary) && !nc.includes(brandPack.suggestedSecondary))
        .slice(0, 4).join(", ");
      if (extras) colourLines.push(`signal colours — ${extras}`);
    }
    if (colourLines.length) briefParts.push("Colours: " + colourLines.join("; ") + ".");

    if (brandPack.suggestedTypography) briefParts.push(`Typography: ${brandPack.suggestedTypography}.`);
    if (brandPack.voiceText) briefParts.push(brandPack.voiceText);
    else if (brandPack.voiceTags.length) briefParts.push(`Voice: ${brandPack.voiceTags.join(", ")}.`);

    const generatedBrief = briefParts.filter(Boolean).join(" ");

    setBrain(b => ({
      ...b,
      primary:    brandPack.suggestedPrimary   || b.primary,
      secondary:  brandPack.suggestedSecondary || b.secondary,
      accent:     brandPack.suggestedAccent    || b.accent,
      typography: brandPack.suggestedTypography || b.typography,
      imageBrief: generatedBrief || b.imageBrief,
      brand_voice: b.brand_voice || brandPack.voiceTags.join(", "),
      value_proposition: b.value_proposition || brandPack.heroSub,
    }));
    setBrainSaved(false);
    // Add SVG logos to brand assets
    if (brandPack.svgs.length > 0) {
      const svgAssets = brandPack.svgs.map((svg, i) => ({
        id: `pack-svg-${Date.now()}-${i}`,
        name: `${brandPack.brandName || "Brand"} Logo ${i + 1}.svg`,
        dataUrl: `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svg)))}`,
        addedAt: new Date().toISOString(),
      }));
      const merged = [...svgAssets, ...brandAssets].slice(0, 6);
      saveBrandAssets(merged);
    }
    window.BoltKitToast?.({ msg: "Brand pack applied to Brand Brain.", type: "success" });
  };

  /* ── shared column card style ───────────────────────────────────── */
  const colCard = {
    background: "#201E18",
    border: "1px solid #3A372F",
    borderRadius: 12,
    overflow: "hidden",
    display: "flex",
    flexDirection: "column",
  };

  const colHead = {
    padding: "16px 20px",
    borderBottom: "1px solid #3A372F",
    display: "flex",
    alignItems: "center",
    gap: 10,
  };

  const colBody = {
    padding: "20px",
    flex: 1,
    overflowY: "auto",
  };

  return (
    <div style={{ height: "100%", display: "flex", background: "#1A1813" }}>
      <SidebarNav active="brand-brain" />

      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <TopBar />

        {/* ── page header ── */}
        <div style={{ padding: "20px 28px 0", flexShrink: 0 }}>
          <div style={{
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 10.5,
            letterSpacing: "0.22em",
            color: "#EFFF00",
            fontWeight: 800,
            textTransform: "uppercase",
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            marginBottom: 6,
          }}>
            <span style={{ width: 18, height: 1, background: "#EFFF00" }} />
            BRAND BRAIN · AI ANALYSIS
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 10, marginBottom: 18 }}>
            <h1 style={{
              fontFamily: "'Anton', Impact, sans-serif",
              fontSize: 42,
              lineHeight: 1,
              textTransform: "uppercase",
              margin: 0,
              color: "#F4F4F0",
            }}>Brand Brain</h1>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              {hasBrain && (
                <div style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 6,
                  background: "#26241E",
                  border: "1px solid #3A372F",
                  borderRadius: 6,
                  padding: "5px 12px",
                  fontSize: 11,
                  fontFamily: "'JetBrains Mono', monospace",
                  color: "#4ADE80",
                  letterSpacing: "0.12em",
                  textTransform: "uppercase",
                  fontWeight: 700,
                }}>
                  <Icon name="check" size={11} stroke={2.6} />
                  Brand Brain Active
                </div>
              )}
              <button
                className={"btn btn-primary" + (analysing ? " btn-analysing" : "")}
                data-bk-bound="true"
                onClick={runAnalysis}
                disabled={analysing}
              >
                {analysing
                  ? <><span className="bolt-thinking" style={{ display: "inline-block" }}><BoltMini size={13} color="#1A1813" /></span> Analysing…</>
                  : <><BoltMini size={13} color="#1A1813" /> Analyse Website</>
                }
              </button>
            </div>
          </div>
        </div>

        {/* ── scrollable body ── */}
        <div style={{ flex: 1, overflowY: "auto", padding: "0 28px 24px", display: "flex", flexDirection: "column", gap: 16 }}>

        {/* ── two-column body ── */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "1fr 1.15fr",
          gap: 16,
          minHeight: 600,
        }}>

          {/* ═══ LEFT — Project info form ═══════════════════════════ */}
          <div style={{ ...colCard, overflow: "hidden" }}>
            <div style={colHead}>
              <Icon name="edit" size={14} stroke={2} />
              <span style={{
                fontFamily: "'JetBrains Mono', monospace",
                fontSize: 10.5,
                letterSpacing: "0.18em",
                textTransform: "uppercase",
                color: "#F4F4F0",
                fontWeight: 700,
              }}>Project Details</span>
            </div>

            <div style={{ ...colBody }}>
              <BrainInput
                label="Project Name"
                value={project.name}
                onChange={v => updateProject("name", v)}
                placeholder="e.g. Renoo · Notes for builders"
              />

              <div style={{ marginBottom: 16 }}>
                <FieldLabel>Website URL</FieldLabel>
                <div style={{ position: "relative" }}>
                  <div style={{
                    position: "absolute",
                    left: 10,
                    top: "50%",
                    transform: "translateY(-50%)",
                    color: "#5C5C5C",
                    pointerEvents: "none",
                  }}>
                    <Icon name="link" size={14} stroke={2} />
                  </div>
                  <input
                    type="text"
                    value={project.url}
                    onChange={e => updateProject("url", e.target.value)}
                    placeholder="https://yoursite.com"
                    style={{ ...inputStyle, paddingLeft: 34 }}
                    onFocus={e => e.target.style.borderColor = "#EFFF00"}
                    onBlur={e => e.target.style.borderColor = "#3A372F"}
                  />
                </div>
              </div>

              {/* Draw the data button */}
              <div style={{ marginBottom: 16, marginTop: -4 }}>
                <button
                  className="btn btn-secondary"
                  data-bk-bound="true"
                  onClick={drawPhotos}
                  disabled={drawingPhotos}
                  style={{ width: "100%", justifyContent: "center" }}
                >
                  {drawingPhotos
                    ? <><span className="bolt-thinking" style={{ display: "inline-block" }}><BoltMini size={12} color="#EFFF00" /></span> Drawing…</>
                    : <><Icon name="image" size={13} stroke={2} /> Draw the data</>
                  }
                </button>

                {drawnPhotos.length > 0 && (
                  <div style={{ marginTop: 10 }}>
                    <div style={{
                      fontFamily: "'JetBrains Mono', monospace",
                      fontSize: 9,
                      letterSpacing: "0.18em",
                      textTransform: "uppercase",
                      color: "#5C5C5C",
                      fontWeight: 700,
                      marginBottom: 8,
                    }}>{drawnPhotos.length} photos from website</div>
                    <div style={{
                      display: "grid",
                      gridTemplateColumns: "repeat(4, 1fr)",
                      gap: 6,
                    }}>
                      {drawnPhotos.map((src, i) => (
                        <a
                          key={i}
                          href={src}
                          target="_blank"
                          rel="noreferrer"
                          data-bk-bound="true"
                          style={{ display: "block", aspectRatio: "1/1", borderRadius: 6, overflow: "hidden", border: "1px solid #3A372F" }}
                          title={src}
                        >
                          <img
                            src={src}
                            alt={`Site photo ${i + 1}`}
                            style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
                            onError={e => { e.target.parentElement.style.display = "none"; }}
                          />
                        </a>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <SectionDivider label="Business Context" />

              <BrainInput
                label="What is your product / service?"
                value={project.product}
                onChange={v => updateProject("product", v)}
                placeholder="e.g. Daily note-taking app for indie builders"
              />

              <BrainInput
                label="Who is your target audience?"
                value={project.audience}
                onChange={v => updateProject("audience", v)}
                placeholder="e.g. Solo founders, indie hackers, 25–40"
              />

              <BrainInput
                label="Main selling points"
                value={project.selling_points}
                onChange={v => updateProject("selling_points", v)}
                rows={3}
                placeholder="List your strongest value props, one per line or comma-separated"
              />

              <BrainInput
                label="Brand tone / voice"
                value={project.tone_of_voice}
                onChange={v => updateProject("tone_of_voice", v)}
                placeholder="e.g. Bold, direct, slightly irreverent"
              />

              <SectionDivider label="Content Strategy" />

              <BrainInput
                label="Things to avoid in content"
                value={project.avoid}
                onChange={v => updateProject("avoid", v)}
                rows={2}
                placeholder="e.g. Corporate jargon, overpromising, stock-photo vibes"
              />

              <BrainInput
                label="Competitors (comma-separated)"
                value={project.competitors}
                onChange={v => updateProject("competitors", v)}
                placeholder="e.g. Notion, Roam Research, Obsidian"
              />

              <BrainInput
                label="Instagram handle"
                value={project.instagram}
                onChange={v => updateProject("instagram", v)}
                placeholder="@yourhandle"
              />

              <BrainInput
                label="Content goals"
                value={project.content_goals}
                onChange={v => updateProject("content_goals", v)}
                rows={3}
                placeholder="e.g. Drive signups, build brand awareness, grow to 10k followers by Q4"
              />

              <SectionDivider label="Import Brand Pack" />

              <div style={{ marginBottom: 16 }}>
                <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: "#C8C8C5", letterSpacing: "0.1em", marginBottom: 6 }}>
                  CLAUDE DESIGN · HTML EXPORT
                </div>
                <label
                  data-bk-bound="true"
                  style={{
                    display: "flex", alignItems: "center", gap: 10,
                    padding: "12px 14px",
                    background: brandPack ? "rgba(74,222,128,0.05)" : "#1A1813",
                    border: `1.5px dashed ${brandPack ? "#4ADE80" : "#3A372F"}`, borderRadius: 8,
                    cursor: "pointer", transition: "border-color 0.15s",
                  }}
                  onMouseEnter={e => e.currentTarget.style.borderColor = "#EFFF00"}
                  onMouseLeave={e => e.currentTarget.style.borderColor = brandPack ? "#4ADE80" : "#3A372F"}
                >
                  <input type="file" accept=".html,.htm" onChange={handleBrandPackUpload} style={{ display: "none" }} data-bk-bound="true" />
                  <Icon name={brandPack ? "check" : "upload"} size={16} stroke={1.8} color={brandPack ? "#4ADE80" : "#5C5C5C"} />
                  <div>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", color: brandPack ? "#4ADE80" : "#C8C8C5" }}>
                      {brandPack ? `✓ ${brandPack.brandName || "Brand pack"} loaded` : "UPLOAD BRAND PACK (.HTML)"}
                    </div>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", marginTop: 2, letterSpacing: "0.06em" }}>
                      {brandPack ? `${brandPack.colours.length} colours · ${brandPack.fonts.length} fonts · ${brandPack.svgs.length} logos — click Apply below` : "Export from Claude Design, drop it here"}
                    </div>
                  </div>
                </label>

                {brandPack && (
                  <button
                    className="btn btn-primary"
                    data-bk-bound="true"
                    onClick={applyBrandPackToBrain}
                    style={{ width: "100%", justifyContent: "center", marginTop: 8 }}
                  >
                    <Icon name="sparkle" size={12} stroke={2} color="#1A1813" /> Apply brand pack to Brain
                  </button>
                )}
              </div>

              <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                <button
                  className={"btn btn-primary" + (analysing ? " btn-analysing" : "")}
                  data-bk-bound="true"
                  onClick={runAnalysis}
                  disabled={analysing}
                >
                  {analysing
                    ? <><span className="bolt-thinking" style={{ display: "inline-block" }}><BoltMini size={13} color="#1A1813" /></span> Analysing…</>
                    : <><BoltMini size={13} color="#1A1813" /> Analyse Website</>
                  }
                </button>
                <button
                  className="btn btn-secondary"
                  data-bk-bound="true"
                  onClick={saveProject}
                  disabled={saving}
                >
                  {saving ? <><Icon name="refresh" size={12} stroke={2} /> Saving…</> : <><Icon name="save" size={12} stroke={2} /> Save project details</>}
                </button>
              </div>
            </div>
          </div>

          {/* ═══ RIGHT — Brand Brain output ═════════════════════════ */}
          <div style={{ ...colCard, overflow: "hidden" }}>
            <div style={colHead}>
              <span style={{
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                width: 20,
                height: 20,
                borderRadius: 5,
                background: hasBrain ? "#EFFF00" : "#26241E",
                transition: "background 0.2s",
              }}>
                <Icon name="brain" size={12} stroke={2} color={hasBrain ? "#1A1813" : "#5C5C5C"} />
              </span>
              <span style={{
                fontFamily: "'JetBrains Mono', monospace",
                fontSize: 10.5,
                letterSpacing: "0.18em",
                textTransform: "uppercase",
                color: "#F4F4F0",
                fontWeight: 700,
              }}>Brand Brain</span>
              {analysing && (
                <span style={{
                  marginLeft: "auto",
                  fontFamily: "'JetBrains Mono', monospace",
                  fontSize: 10,
                  color: "#EFFF00",
                  letterSpacing: "0.14em",
                  textTransform: "uppercase",
                  display: "flex",
                  alignItems: "center",
                  gap: 6,
                }}>
                  <span className="bolt-thinking" style={{ display: "inline-block" }}>
                    <BoltMini size={11} color="#EFFF00" />
                  </span>
                  Scanning…
                </span>
              )}
            </div>

            <div style={{ ...colBody }}>
              {!hasBrain ? (
                <BrainEmptyState onAnalyse={runAnalysis} analysing={analysing} />
              ) : (
                <>
                  <SectionDivider label="Summaries" />

                  <BrainInput
                    label="Website Summary"
                    value={brain.website_summary}
                    onChange={v => updateBrain("website_summary", v)}
                    rows={3}
                    placeholder="What the website communicates at a glance"
                  />

                  <BrainInput
                    label="Product Summary"
                    value={brain.product_summary}
                    onChange={v => updateBrain("product_summary", v)}
                    rows={3}
                    placeholder="Core product/service description"
                  />

                  <BrainInput
                    label="Audience Summary"
                    value={brain.audience_summary}
                    onChange={v => updateBrain("audience_summary", v)}
                    rows={2}
                    placeholder="Who this is for and what they care about"
                  />

                  <SectionDivider label="Brand" />

                  <BrainInput
                    label="Brand Voice"
                    value={brain.brand_voice}
                    onChange={v => updateBrain("brand_voice", v)}
                    placeholder="e.g. Direct, bold, human, never corporate"
                  />

                  <BrainInput
                    label="Value Proposition"
                    value={brain.value_proposition}
                    onChange={v => updateBrain("value_proposition", v)}
                    rows={2}
                    placeholder="The core promise — why choose this over alternatives"
                  />

                  <SectionDivider label="Content Engine" />

                  <div style={{ marginBottom: 16 }}>
                    <FieldLabel>Content Themes (comma-separated)</FieldLabel>
                    <textarea
                      rows={2}
                      value={strFromArr(brain.content_themes)}
                      onChange={e => updateBrainArr("content_themes", e.target.value)}
                      placeholder="e.g. Productivity, indie building, focus, shipping fast"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = "#EFFF00"}
                      onBlur={e => e.target.style.borderColor = "#3A372F"}
                    />
                    {brain.content_themes.length > 0 && <TagList tags={brain.content_themes} />}
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <FieldLabel>Keywords (comma-separated)</FieldLabel>
                    <textarea
                      rows={2}
                      value={strFromArr(brain.keywords)}
                      onChange={e => updateBrainArr("keywords", e.target.value)}
                      placeholder="e.g. note-taking, second brain, async work"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = "#EFFF00"}
                      onBlur={e => e.target.style.borderColor = "#3A372F"}
                    />
                    {brain.keywords.length > 0 && <TagList tags={brain.keywords} />}
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <FieldLabel>Offers (comma-separated)</FieldLabel>
                    <textarea
                      rows={2}
                      value={strFromArr(brain.offers)}
                      onChange={e => updateBrainArr("offers", e.target.value)}
                      placeholder="e.g. Free tier, Pro plan, Team plan"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = "#EFFF00"}
                      onBlur={e => e.target.style.borderColor = "#3A372F"}
                    />
                    {brain.offers.length > 0 && <TagList tags={brain.offers} />}
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <FieldLabel>Trust Signals (comma-separated)</FieldLabel>
                    <textarea
                      rows={2}
                      value={strFromArr(brain.trust_signals)}
                      onChange={e => updateBrainArr("trust_signals", e.target.value)}
                      placeholder="e.g. 2,000 users, press mentions, money-back guarantee"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = "#EFFF00"}
                      onBlur={e => e.target.style.borderColor = "#3A372F"}
                    />
                    {brain.trust_signals.length > 0 && <TagList tags={brain.trust_signals} />}
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <FieldLabel>Pain Points (comma-separated)</FieldLabel>
                    <textarea
                      rows={2}
                      value={strFromArr(brain.pain_points)}
                      onChange={e => updateBrainArr("pain_points", e.target.value)}
                      placeholder="e.g. Context switching, losing ideas, scattered notes"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = "#EFFF00"}
                      onBlur={e => e.target.style.borderColor = "#3A372F"}
                    />
                    {brain.pain_points.length > 0 && <TagList tags={brain.pain_points} />}
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <FieldLabel>Instagram Angles (comma-separated)</FieldLabel>
                    <textarea
                      rows={3}
                      value={strFromArr(brain.instagram_angles)}
                      onChange={e => updateBrainArr("instagram_angles", e.target.value)}
                      placeholder="e.g. Before/after productivity, day-in-the-life founder, tool teardown"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = "#EFFF00"}
                      onBlur={e => e.target.style.borderColor = "#3A372F"}
                    />
                    {brain.instagram_angles.length > 0 && <TagList tags={brain.instagram_angles} />}
                  </div>

                  <SectionDivider label="Visual Identity · AI Images" />

                  {/* Colour row */}
                  <div style={{ marginBottom: 16 }}>
                    <FieldLabel>Brand Colours</FieldLabel>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
                      {[
                        { key: "primary",   label: "Primary"   },
                        { key: "secondary", label: "Secondary" },
                        { key: "accent",    label: "Accent"    },
                      ].map(({ key, label }) => (
                        <div key={key}>
                          <div style={{
                            fontFamily: "'JetBrains Mono', monospace",
                            fontSize: 9,
                            letterSpacing: "0.14em",
                            textTransform: "uppercase",
                            color: "#5C5C5C",
                            marginBottom: 4,
                          }}>{label}</div>
                          <div style={{ position: "relative" }}>
                            {brain[key] && (
                              <div style={{
                                position: "absolute", left: 8, top: "50%",
                                transform: "translateY(-50%)",
                                width: 14, height: 14, borderRadius: 3,
                                background: brain[key],
                                border: "1px solid rgba(255,255,255,0.15)",
                                pointerEvents: "none",
                              }} />
                            )}
                            <input
                              type="text"
                              value={brain[key]}
                              onChange={e => updateBrain(key, e.target.value)}
                              placeholder="#000000"
                              style={{
                                ...inputStyle,
                                paddingLeft: brain[key] ? 30 : 11,
                                fontSize: 12,
                              }}
                              onFocus={e => e.target.style.borderColor = "#EFFF00"}
                              onBlur={e => e.target.style.borderColor = "#3A372F"}
                            />
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* ── Brand Assets ── */}
                  <div style={{ marginBottom: 20 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                      <FieldLabel>Brand Assets · Style Reference</FieldLabel>
                      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", letterSpacing: "0.1em" }}>
                        {brandAssets.length}/6 UPLOADED
                      </span>
                    </div>

                    {/* Upload zone */}
                    <label
                      data-bk-bound="true"
                      style={{
                        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
                        gap: 8, padding: "16px 12px",
                        background: "#1A1813", border: "1.5px dashed #3A372F", borderRadius: 8,
                        cursor: "pointer", marginBottom: 10, transition: "border-color 0.15s",
                      }}
                      onMouseEnter={e => e.currentTarget.style.borderColor = "#EFFF00"}
                      onMouseLeave={e => e.currentTarget.style.borderColor = "#3A372F"}
                    >
                      <input
                        type="file"
                        accept="image/*"
                        multiple
                        onChange={handleAssetUpload}
                        style={{ display: "none" }}
                        data-bk-bound="true"
                      />
                      <Icon name="image" size={20} stroke={1.5} color="#5C5C5C" />
                      <div style={{ textAlign: "center" }}>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: "#C8C8C5", fontWeight: 700, letterSpacing: "0.1em" }}>
                          UPLOAD LOGO · BRAND IMAGES · APP SCREENSHOTS
                        </div>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", marginTop: 3, letterSpacing: "0.06em" }}>
                          Up to 6 images · PNG, JPG, SVG · Max 2MB each
                        </div>
                      </div>
                    </label>

                    {/* Uploaded assets grid */}
                    {brandAssets.length > 0 && (
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6, marginBottom: 12 }}>
                        {brandAssets.map(asset => (
                          <div key={asset.id} style={{ position: "relative", borderRadius: 6, overflow: "hidden", border: "1px solid #3A372F", aspectRatio: "1/1", background: "#26241E" }}>
                            <img src={asset.dataUrl} alt={asset.name} style={{ width: "100%", height: "100%", objectFit: "contain", display: "block", padding: 4 }} />
                            <button
                              data-bk-bound="true"
                              onClick={() => removeAsset(asset.id)}
                              style={{
                                position: "absolute", top: 4, right: 4,
                                width: 20, height: 20, borderRadius: 4,
                                background: "rgba(0,0,0,0.8)", border: "none",
                                color: "#FF4D5E", cursor: "pointer", display: "flex",
                                alignItems: "center", justifyContent: "center",
                              }}
                            >
                              <Icon name="trash" size={9} stroke={2} />
                            </button>
                            <div style={{
                              position: "absolute", bottom: 0, left: 0, right: 0,
                              background: "rgba(0,0,0,0.7)", padding: "2px 5px",
                              fontFamily: "'JetBrains Mono', monospace", fontSize: 8,
                              color: "#C8C8C5", letterSpacing: "0.04em",
                              whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                            }}>{asset.name}</div>
                          </div>
                        ))}
                      </div>
                    )}

                    {/* Influence slider */}
                    {brandAssets.length > 0 && (
                      <div>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", letterSpacing: "0.12em", marginBottom: 6 }}>
                          BRAND INFLUENCE ON IMAGES
                        </div>
                        <div style={{ display: "flex", gap: 6 }}>
                          {["subtle", "medium", "strong"].map(level => (
                            <button
                              key={level}
                              data-bk-bound="true"
                              onClick={() => saveInfluence(level)}
                              style={{
                                flex: 1, padding: "6px", borderRadius: 5, cursor: "pointer",
                                fontFamily: "'JetBrains Mono', monospace", fontSize: 9, fontWeight: 700,
                                letterSpacing: "0.1em", textTransform: "uppercase",
                                background: assetInfluence === level ? "#EFFF00" : "#26241E",
                                color: assetInfluence === level ? "#1A1813" : "#5C5C5C",
                                border: `1px solid ${assetInfluence === level ? "#EFFF00" : "#3A372F"}`,
                                transition: "all 0.15s",
                              }}
                            >{level}</button>
                          ))}
                        </div>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", marginTop: 5, letterSpacing: "0.06em" }}>
                          {assetInfluence === "subtle" ? "Light style guidance — more creative freedom" : assetInfluence === "strong" ? "Heavy brand enforcement — very close to reference" : "Balanced — recommended starting point"}
                        </div>
                      </div>
                    )}
                  </div>

                  {/* ── App Screenshots & Mockups ── */}
                  <div style={{ marginBottom: 20 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
                      <FieldLabel>App Screenshots · Mockup Reference</FieldLabel>
                      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", letterSpacing: "0.1em" }}>
                        {appScreenshots.length}/8 UPLOADED
                      </span>
                    </div>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", letterSpacing: "0.06em", marginBottom: 8, lineHeight: 1.5 }}>
                      Screenshots of your app or product — used as Ideogram visual references when generating posts
                    </div>

                    <label
                      data-bk-bound="true"
                      style={{
                        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
                        gap: 8, padding: "16px 12px",
                        background: "#1A1813", border: "1.5px dashed #3A372F", borderRadius: 8,
                        cursor: "pointer", marginBottom: 10, transition: "border-color 0.15s",
                      }}
                      onMouseEnter={e => e.currentTarget.style.borderColor = "#EFFF00"}
                      onMouseLeave={e => e.currentTarget.style.borderColor = "#3A372F"}
                    >
                      <input
                        type="file"
                        accept="image/png,image/jpeg,image/webp"
                        multiple
                        onChange={handleScreenshotUpload}
                        style={{ display: "none" }}
                        data-bk-bound="true"
                      />
                      <Icon name="monitor" size={20} stroke={1.5} color="#5C5C5C" />
                      <div style={{ textAlign: "center" }}>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: "#C8C8C5", fontWeight: 700, letterSpacing: "0.1em" }}>
                          UPLOAD APP SCREENSHOTS · MOCKUPS
                        </div>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", marginTop: 3, letterSpacing: "0.06em" }}>
                          Up to 8 images · PNG, JPG — Ideogram style references
                        </div>
                      </div>
                    </label>

                    {appScreenshots.length > 0 && (
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
                        {appScreenshots.map(shot => (
                          <div key={shot.id} style={{ position: "relative", borderRadius: 6, overflow: "hidden", border: "1px solid #3A372F", aspectRatio: "9/16", background: "#26241E" }}>
                            <img src={shot.dataUrl} alt={shot.name} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
                            <button
                              data-bk-bound="true"
                              onClick={() => removeScreenshot(shot.id)}
                              style={{
                                position: "absolute", top: 4, right: 4,
                                width: 20, height: 20, borderRadius: 4,
                                background: "rgba(0,0,0,0.8)", border: "none",
                                color: "#FF4D5E", cursor: "pointer", display: "flex",
                                alignItems: "center", justifyContent: "center",
                              }}
                            >
                              <Icon name="trash" size={9} stroke={2} />
                            </button>
                            <div style={{
                              position: "absolute", bottom: 0, left: 0, right: 0,
                              background: "rgba(0,0,0,0.7)", padding: "2px 5px",
                              fontFamily: "'JetBrains Mono', monospace", fontSize: 8,
                              color: "#C8C8C5", letterSpacing: "0.04em",
                              whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                            }}>{shot.name}</div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>

                  <BrainInput
                    label="Typography Style"
                    value={brain.typography}
                    onChange={v => updateBrain("typography", v)}
                    placeholder="e.g. Bold condensed headings (Saira Condensed), clean geometric sans body (Space Grotesk)"
                  />

                  <div style={{ marginBottom: 16 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
                      <FieldLabel>Image Visual Brief</FieldLabel>
                      <span style={{
                        fontFamily: "'JetBrains Mono', monospace",
                        fontSize: 9,
                        color: "#5C5C5C",
                        letterSpacing: "0.1em",
                      }}>INJECTED INTO EVERY IMAGE PROMPT</span>
                    </div>
                    <textarea
                      rows={4}
                      value={brain.imageBrief}
                      onChange={e => updateBrain("imageBrief", e.target.value)}
                      placeholder="Describe your brand's visual style for AI image generation. Include colours, mood, aesthetic, and anything the AI must always follow. e.g. Dark near-black background, electric lime green accents, bold condensed motorsport typography, high-performance premium aesthetic."
                      style={{ ...inputStyle, lineHeight: 1.55 }}
                      onFocus={e => e.target.style.borderColor = "#EFFF00"}
                      onBlur={e => e.target.style.borderColor = "#3A372F"}
                    />
                    <div style={{
                      marginTop: 6,
                      fontFamily: "'JetBrains Mono', monospace",
                      fontSize: 9,
                      color: "#5C5C5C",
                      letterSpacing: "0.08em",
                      lineHeight: 1.5,
                    }}>
                      This is the most powerful brand control. Write it like you're briefing a designer: colours, typography style, mood, what to always include, what to never do.
                    </div>
                  </div>

                  {/* ── save + next action ── */}
                  <div style={{
                    marginTop: 24,
                    paddingTop: 20,
                    borderTop: "1px solid #3A372F",
                    display: "flex",
                    gap: 8,
                    flexWrap: "wrap",
                    alignItems: "center",
                  }}>
                    <button
                      className="btn btn-primary"
                      data-bk-bound="true"
                      onClick={saveBrain}
                    >
                      <Icon name="save" size={12} stroke={2} color="#1A1813" /> Save Brand Brain
                    </button>

                    <button
                      className="btn btn-secondary"
                      data-bk-bound="true"
                      onClick={runAnalysis}
                      disabled={analysing}
                    >
                      <Icon name="refresh" size={12} stroke={2} /> Re-analyse
                    </button>

                    {brainSaved && (
                      <button
                        className="btn btn-secondary"
                        onClick={() => window.BoltKitGo?.("strategy")}
                        style={{
                          marginLeft: "auto",
                          borderColor: "#EFFF00",
                          color: "#EFFF00",
                          display: "flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                        Brand Brain ready — Generate Strategy
                        <Icon name="arrow_right" size={12} stroke={2} />
                      </button>
                    )}
                  </div>

                  {brainSaved && (
                    <div style={{
                      marginTop: 12,
                      padding: "10px 14px",
                      background: "#1A2A1A",
                      border: "1px solid #2A3A2A",
                      borderRadius: 8,
                      display: "flex",
                      alignItems: "center",
                      gap: 8,
                      fontSize: 12,
                      color: "#4ADE80",
                      fontFamily: "'JetBrains Mono', monospace",
                      letterSpacing: "0.08em",
                    }}>
                      <Icon name="check" size={12} stroke={2.6} />
                      Saved — AI will use this Brand Brain for all content generation.
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
        {/* ═══ BRAND PACK PREVIEW — full width below columns ═══════ */}
        {brandPack && (
          <div style={{
            margin: "0 0 24px",
            background: "#201E18",
            border: "1px solid #3A372F",
            borderRadius: 12,
            overflow: "hidden",
          }}>
            {/* Header */}
            <div style={{
              padding: "14px 20px",
              borderBottom: "1px solid #3A372F",
              display: "flex", alignItems: "center", justifyContent: "space-between",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 8, height: 8, borderRadius: "50%", background: "#4ADE80" }} />
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "#F4F4F0", fontWeight: 700 }}>
                  Brand Pack · {brandPack.brandName || "Imported"}
                </span>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <button className="btn btn-primary btn-sm" data-bk-bound="true" onClick={applyBrandPackToBrain}>
                  <Icon name="sparkle" size={11} stroke={2} color="#1A1813" /> Apply to Brain
                </button>
                <button className="btn btn-secondary btn-sm" data-bk-bound="true" onClick={() => setBrandPack(null)}>
                  <Icon name="trash" size={11} stroke={2} /> Dismiss
                </button>
              </div>
            </div>

            <div style={{ padding: "20px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24 }}>

              {/* Colours */}
              <div>
                <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "#5C5C5C", fontWeight: 700, marginBottom: 10 }}>
                  Colours · {brandPack.colours.length} extracted
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {brandPack.colours.slice(0, 20).map((c, i) => {
                    const isSuggested = [brandPack.suggestedPrimary, brandPack.suggestedSecondary, brandPack.suggestedAccent].includes(c);
                    return (
                      <div key={i} style={{ textAlign: "center" }}>
                        <div style={{
                          width: 36, height: 36, borderRadius: 6, background: c,
                          border: isSuggested ? "2px solid #EFFF00" : "1px solid rgba(255,255,255,0.08)",
                          cursor: "pointer", transition: "transform 0.1s",
                        }}
                          title={c}
                          onClick={() => { navigator.clipboard?.writeText(c); window.BoltKitToast?.({ msg: `Copied ${c}`, type: "success" }); }}
                        />
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 7.5, color: "#5C5C5C", marginTop: 3, letterSpacing: "0.04em" }}>
                          {c.toUpperCase()}
                        </div>
                        {isSuggested && <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 7, color: "#EFFF00", marginTop: 1 }}>KEY</div>}
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Typography */}
              <div>
                <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "#5C5C5C", fontWeight: 700, marginBottom: 10 }}>
                  Typography · {brandPack.fonts.length} found
                </div>
                {brandPack.gFontLinks.length > 0 && brandPack.gFontLinks.map((href, i) => (
                  <link key={i} rel="stylesheet" href={href} />
                ))}
                {brandPack.fonts.length > 0 ? brandPack.fonts.map((font, i) => (
                  <div key={i} style={{ marginBottom: 12 }}>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", marginBottom: 4, letterSpacing: "0.08em" }}>{font}</div>
                    <div style={{ fontFamily: `'${font}', serif`, fontSize: 22, color: "#F4F4F0", lineHeight: 1.1 }}>Aa Bb Cc 123</div>
                    <div style={{ fontFamily: `'${font}', serif`, fontSize: 13, color: "#C8C8C5", marginTop: 3, lineHeight: 1.4 }}>The quick brown fox jumps over the lazy dog.</div>
                  </div>
                )) : (
                  <div style={{ fontSize: 12, color: "#5C5C5C" }}>No web fonts detected</div>
                )}
              </div>

              {/* Logos + Key CSS vars */}
              <div>
                {brandPack.svgs.length > 0 && (
                  <>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "#5C5C5C", fontWeight: 700, marginBottom: 10 }}>
                      Logos · {brandPack.svgs.length} found
                    </div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 16 }}>
                      {brandPack.svgs.map((svg, i) => (
                        <div key={i} style={{
                          width: 90, height: 60, background: "#26241E",
                          borderRadius: 8, border: "1px solid #3A372F",
                          display: "flex", alignItems: "center", justifyContent: "center",
                          padding: 8, overflow: "hidden",
                        }}
                          dangerouslySetInnerHTML={{ __html: svg }}
                        />
                      ))}
                    </div>
                  </>
                )}

                {Object.keys(brandPack.cssVars).length > 0 && (
                  <>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "#5C5C5C", fontWeight: 700, marginBottom: 8 }}>
                      CSS Variables
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 4, maxHeight: 160, overflowY: "auto" }}>
                      {Object.entries(brandPack.cssVars).slice(0, 20).map(([k, v]) => (
                        <div key={k} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                          {/^#[0-9A-Fa-f]{3,6}$/.test(v.trim()) && (
                            <span style={{ width: 10, height: 10, borderRadius: 2, background: v.trim(), border: "1px solid rgba(255,255,255,0.1)", flexShrink: 0 }} />
                          )}
                          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, color: "#5C5C5C", letterSpacing: "0.04em" }}>--{k}:</span>
                          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, color: "#C8C8C5", letterSpacing: "0.04em" }}>{v.trim()}</span>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        )}

        </div>
      </div>
    </div>
  );
};

Object.assign(window, { BrandBrainScreen });
