// All brand files (logos, fonts, stickers, imagery) live in the public
// "brand-assets" Supabase Storage bucket now — plain files, downloaded
// directly, no server-side zipping or on-demand PNG rasterization (that
// needed Puppeteer on Render). See scripts/upload-brand-assets.mjs and
// supabase/migrations/20260903000005_brand_assets_bucket.sql.
const BRAND_ASSETS_BASE = "https://aufarawdznfzptcuymgs.supabase.co/storage/v1/object/public/brand-assets/assets/";
const BRAND_FONTS_BASE = "https://aufarawdznfzptcuymgs.supabase.co/storage/v1/object/public/brand-assets/fonts/";

// Real Flexxi brand imagery — system visuals & mockups
const BRAND_IMAGERY = [
  { src: "assets/brand-laptop-mockup.png", label: "Product in context — real screens, real desks", bg: "#E7E2DC", fit: "cover", position: "center" },
  { src: "assets/brand-stickers-scene.png", label: "Holographic sticker — the double-X foil at center", bg: "#050505", fit: "cover", position: "center" },
  { src: "assets/brand-xx-pattern.png", label: "Repeated-mark pattern — double-X tiled texture", bg: "#050505", fit: "cover", position: "center" },
  { src: "assets/brand-sticker-sheet.png", label: "Sticker sheet — holographic system visuals", bg: "#050505", fit: "cover", position: "center" },
];

// The sticker sheet, split into individually downloadable stickers.
// `svg` is the true-vector twin to offer alongside the PNG — null where
// none exists (the artwork only ever existed as a raster).
const STICKER_DOWNLOADS = [
  { src: "assets/sticker-flexxi.png", label: "FLEXXI wordmark", svg: "sticker-flexxi.svg" },
  { src: "assets/sticker-flexxible.png", label: "Flexxi-ble by Design", svg: "sticker-flexxible.svg" },
  { src: "assets/sticker-layers.png", label: "Designers Do It In Layers", svg: "sticker-layers.svg" },
  { src: "assets/sticker-xx.png", label: "Double-X mark", svg: "sticker-xx.svg" },
  { src: "assets/flexxi-sticker-holo.png", label: "Holographic sticker", svg: null },
  { src: "assets/brand-xx-pattern.png", label: "XX repeat pattern", svg: "xx-pattern.svg" },
];

// BRAND FOUNDATIONS page
function BrandFoundationsPage() {
  const downloadMD = () => {
    const md = generateBrandMD();
    const blob = new Blob([md], { type: "text/markdown" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "flexxi-brand-foundations.md";
    document.body.appendChild(a);
    a.click();
    setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 100);
  };

  // Download any asset by URL. Fetches to a Blob first so the browser always
  // shows a real download (plain <a download> can open SVGs inline instead).
  const downloadAsset = async (url, filename) => {
    try {
      const res = await fetch(url);
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.error || res.statusText);
      }
      const blob = await res.blob();
      const objUrl = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = objUrl;
      a.download = filename || url.split("/").pop().split("?")[0];
      document.body.appendChild(a);
      a.click();
      setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(objUrl); }, 150);
    } catch (e) {
      alert(`Download failed: ${e.message}`);
    }
  };
  // Download several files from one click — no server-side zipping, so
  // these just land as separate files in the browser's downloads folder.
  // Spaced out slightly since browsers throttle/block rapid-fire downloads.
  const downloadAll = async (files) => {
    for (const [url, filename] of files) {
      await downloadAsset(url, filename);
      await new Promise((r) => setTimeout(r, 300));
    }
  };

  const LOGO_KIT_FILES = [
    "logo-wordmark.svg", "logo-wordmark-white.svg",
    "logo-stacked.svg", "logo-stacked-white.svg",
    "logo-mark.svg", "logo-mark-white.svg",
  ].map((n) => [BRAND_ASSETS_BASE + n, n]);
  const FONT_KIT_FILES = [
    "ESRebondGrotesque-Light.otf", "ESRebondGrotesque-Regular.otf", "ESRebondGrotesque-Medium.otf",
    "ESRebondGrotesque-Semibold.otf", "ESRebondGrotesque-Bold.otf", "ESRebondGrotesque-Extrabold.otf",
  ].map((n) => [BRAND_FONTS_BASE + n, n]);
  const STICKER_KIT_FILES = STICKER_DOWNLOADS.map((s) => {
    const name = s.src.split("/").pop();
    return [BRAND_ASSETS_BASE + name, name];
  });
  // Everything (logos + fonts + stickers), downloaded as separate files.
  const downloadKit = () => downloadAll([...LOGO_KIT_FILES, ...FONT_KIT_FILES, ...STICKER_KIT_FILES]);

  return (
    <div className="fade-in">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 24 }}>
        <div>
          <div className="eyebrow">BRAND FOUNDATIONS</div>
          <h1 className="page-title">
            The kit of decisions<br />already made.
          </h1>
          <p className="page-subtitle">
            Everything below is locked in across every template, every export, every Notion import. Edit once here, ripple everywhere.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
          <button className="btn btn-ghost btn-lg" onClick={downloadMD}>
            <Icons.Download size={14} /> MD
          </button>
          <button className="btn btn-primary btn-lg" onClick={downloadKit}>
            <Icons.Download size={14} /> Download kit
          </button>
        </div>
      </div>

      {/* COLORS */}
      <section style={{ marginTop: 56 }}>
        <SectionHeader label="01" title="Colors" subtitle="Black & white do the work. Holographic foil is the one note." />
        <div className="grid-3" style={{ marginTop: 20 }}>
          <SwatchCard color={BRAND.colors.primary[0]} large />
          <SwatchCard color={BRAND.colors.primary[1]} large />
          <SwatchCard color={BRAND.colors.primary[2]} large />
        </div>
        <h3 style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, marginTop: 32, marginBottom: 12, color: "var(--ink-2)" }}>Accents</h3>
        <div className="grid-4">
          {BRAND.colors.accents.map((c) => <SwatchCard key={c.hex} color={c} />)}
          <HoloSwatchCard />
        </div>
        <h3 style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, marginTop: 32, marginBottom: 12, color: "var(--ink-2)" }}>Neutrals</h3>
        <div className="grid-4">
          {BRAND.colors.neutrals.map((c) => <SwatchCard key={c.hex} color={c} muted />)}
        </div>
      </section>

      {/* TYPOGRAPHY */}
      <section style={{ marginTop: 64 }}>
        <SectionHeader label="02" title="Typography" subtitle="Two families. Each has a job." />
        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 14 }}>
          <button className="btn btn-surface" onClick={() => downloadAll(FONT_KIT_FILES)}>
            <Icons.Download size={13} /> Download all fonts
          </button>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 20 }}>
          {BRAND.typography.families.map((f) => (
            <div key={f.name} className="card" style={{ padding: 28 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 24, marginBottom: 16 }}>
                <div>
                  <div className="eyebrow">{f.role.toUpperCase()}</div>
                  <h3 style={{ fontFamily: f.family, fontSize: 32, fontWeight: 700, margin: "6px 0 4px", letterSpacing: f.role === "Display" ? "-0.03em" : "-0.01em" }}>{f.name}</h3>
                  <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{f.usage}</div>
                </div>
                <div className="pill">{f.weights}</div>
              </div>
              <div
                style={{
                  fontFamily: f.family,
                  fontSize: 64,
                  fontWeight: f.role === "Display" ? 700 : 500,
                  letterSpacing: f.role === "Display" ? "-0.035em" : "-0.015em",
                  lineHeight: 1.0,
                  marginTop: 12,
                  textWrap: "balance",
                }}
              >
                {f.sample}
              </div>
              {f.role === "Display" && (
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 18 }}>
                  {["Light", "Regular", "Medium", "Semibold", "Bold", "Extrabold"].map((w) => (
                    <button key={w} className="btn btn-sm btn-ghost" onClick={() => downloadAsset(`${BRAND_FONTS_BASE}ESRebondGrotesque-${w}.otf`, `ESRebondGrotesque-${w}.otf`)}>
                      <Icons.Download size={11} /> {w} .otf
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Type scale */}
        <h3 style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, marginTop: 32, marginBottom: 12, color: "var(--ink-2)" }}>Type scale</h3>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          {BRAND.typography.scale.map((s, i) => (
            <div key={s.label} style={{ display: "flex", alignItems: "baseline", padding: "18px 24px", borderBottom: i === BRAND.typography.scale.length - 1 ? "0" : "1px solid var(--line)" }}>
              <div style={{ width: 110, fontSize: 11.5, color: "var(--ink-3)", fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase" }}>{s.label}</div>
              <div style={{ width: 100, fontSize: 12, color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>{s.size}px / {s.lineHeight}</div>
              <div
                style={{
                  flex: 1,
                  fontFamily: s.family,
                  fontSize: Math.min(s.size, 48),
                  fontWeight: s.weight,
                  letterSpacing: s.family === "Space Grotesk" ? "-0.035em" : "-0.01em",
                  lineHeight: 1.0,
                }}
              >
                {s.label === "Caption" ? "BUILD MODE / CAPTION" : "Sample sentence."}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* SHAPES */}
      <section style={{ marginTop: 64 }}>
        <SectionHeader label="03" title="Shapes" subtitle="Architectural and tight. A pill for every action." />
        <div className="grid-3" style={{ marginTop: 20 }}>
          {/* Radii */}
          <div className="card" style={{ padding: 24, gridColumn: "span 2" }}>
            <div className="eyebrow">CORNER RADII</div>
            <div style={{ display: "flex", gap: 16, marginTop: 18, flexWrap: "wrap" }}>
              {BRAND.shapes.radii.map((r) => (
                <div key={r.name} style={{ textAlign: "center" }}>
                  <div
                    style={{
                      width: 80,
                      height: 80,
                      background: "var(--ink)",
                      borderRadius: r.value === 999 ? 9999 : r.value,
                      marginBottom: 8,
                    }}
                  />
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{r.name}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{r.value === 999 ? "∞" : `${r.value}px`}</div>
                </div>
              ))}
            </div>
          </div>
          {/* Stickers */}
          <div className="card" style={{ padding: 24, background: "var(--bg-2)" }}>
            <div className="eyebrow">PILLS</div>
            <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 18, alignItems: "flex-start" }}>
              {/* Signature CTA — the standard site button: black pill, real
                  foil ring, inverts + reveals the arrow on hover */}
              <button className="btn btn-primary" style={{ fontSize: 12, padding: "9px 18px" }}>
                Book a call
              </button>
              {BRAND.shapes.stickers.slice(1).map((s) => (
                <div
                  key={s.label}
                  className="sticker"
                  style={{
                    transform: `rotate(${s.rotation}deg)`,
                    background: s.color === "grey" ? "var(--grey)" : "var(--ink)",
                    color: s.color === "grey" ? "var(--ink)" : "var(--surface)",
                  }}
                >
                  {s.label}
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* IMAGERY */}
      <section style={{ marginTop: 64 }}>
        <SectionHeader label="04" title="Imagery" subtitle="Bold backgrounds, real hands, generous scale." />
        <div className="grid-2" style={{ marginTop: 20 }}>
          {BRAND_IMAGERY.map((p) => (
            <div key={p.src} style={{ borderRadius: 16, overflow: "hidden", aspectRatio: "16/10", position: "relative", border: "1px solid var(--line)", background: p.bg || "var(--ink)" }}>
              <img src={p.src} alt={p.label} style={{ width: "100%", height: "100%", objectFit: p.fit || "cover", objectPosition: p.position || "center", display: "block" }} />
              <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, padding: "10px 14px", background: "linear-gradient(to top, rgba(0,0,0,0.6), transparent)", color: "white", fontSize: 12, fontWeight: 500 }}>
                {p.label}
              </div>
            </div>
          ))}
        </div>
        {/* Individually downloadable stickers (the sheet, split) */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 32, marginBottom: 12, gap: 12, flexWrap: "wrap" }}>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, color: "var(--ink-2)", margin: 0 }}>Stickers</h3>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ fontSize: 12, color: "var(--ink-3)" }}>Transparent · PNG or SVG</span>
            <button className="btn btn-sm btn-surface" onClick={() => downloadAll(STICKER_KIT_FILES)}>
              <Icons.Download size={12} /> All stickers
            </button>
          </div>
        </div>
        <div className="grid-3">
          {STICKER_DOWNLOADS.map((s) => (
            <div key={s.src} className="card" style={{ padding: 0, overflow: "hidden" }}>
              <div style={{ background: "#0B0B0B", aspectRatio: "16/10", display: "grid", placeItems: "center", padding: 18 }}>
                <img src={s.src} alt={s.label} style={{ maxWidth: "82%", maxHeight: "82%", objectFit: "contain" }} />
              </div>
              <div style={{ padding: 14, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                <div style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.label}</div>
                <div style={{ display: "flex", gap: 4, flexShrink: 0 }}>
                  <button className="btn btn-sm btn-ghost" onClick={() => downloadAsset(s.src, s.src.split("/").pop())}>
                    <Icons.Download size={12} /> PNG
                  </button>
                  {s.svg && (
                    <button className="btn btn-sm btn-ghost" onClick={() => downloadAsset(BRAND_ASSETS_BASE + s.svg, s.svg)}>
                      <Icons.Download size={12} /> SVG
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>

        <h3 style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, marginTop: 32, marginBottom: 12, color: "var(--ink-2)" }}>Principles</h3>
        <div className="grid-2">
          {BRAND.imagery.principles.map((p) => (
            <div key={p.title} className="card" style={{ padding: 22 }}>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 600, letterSpacing: "-0.015em" }}>{p.title}</div>
              <p style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5, margin: "8px 0 0" }}>{p.desc}</p>
            </div>
          ))}
        </div>
      </section>

      {/* VOICE */}
      <section style={{ marginTop: 64 }}>
        <SectionHeader label="05" title="Voice & tone" subtitle="Direct, confident, occasionally cheeky." />
        <div style={{ marginTop: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0, border: "1px solid var(--line)", borderRadius: 20, overflow: "hidden", background: "var(--surface-2)" }}>
          <div style={{ padding: 24, borderRight: "1px solid var(--line)", background: "var(--bg-2)" }}>
            <div className="eyebrow" style={{ color: "var(--ink)" }}>DO</div>
            {BRAND.voice.principles.map((p, i) => (
              <div key={i} style={{ padding: "14px 0", borderBottom: i === BRAND.voice.principles.length - 1 ? "0" : "1px solid var(--line)", fontSize: 16, fontFamily: "var(--font-display)", fontWeight: 500, letterSpacing: "-0.01em", color: "var(--ink)" }}>
                {p.do}
              </div>
            ))}
          </div>
          <div style={{ padding: 24, background: "var(--surface-2)" }}>
            <div className="eyebrow" style={{ color: "var(--ink-3)" }}>DON'T</div>
            {BRAND.voice.principles.map((p, i) => (
              <div key={i} style={{ padding: "14px 0", borderBottom: i === BRAND.voice.principles.length - 1 ? "0" : "1px solid var(--line)", fontSize: 15, color: "var(--ink-3)", textDecoration: "line-through", textDecorationColor: "var(--coral)", textDecorationThickness: "1.5px" }}>
                {p.dont}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* LOGO */}
      <section style={{ marginTop: 64 }}>
        <SectionHeader label="06" title="Logo" subtitle="Three lockups. One mark." />

        {/* Three logo versions */}
        <div className="grid-3" style={{ marginTop: 20 }}>
          {[
            { src: "assets/logo-wordmark.svg", name: "Horizontal wordmark", desc: "Primary lockup — nav bars, headers, wide formats", w: "82%", maxW: 320 },
            { src: "assets/logo-stacked.svg", name: "Stacked mark", desc: "Square format — avatars, stamps, social, app icons", w: "52%", maxW: 170 },
            { src: "assets/logo-mark.svg", name: "Double-X mark", desc: "Standalone — favicon, watermark, compact spaces", w: "48%", maxW: 150 },
          ].map((l) => (
            <div key={l.src} className="card" style={{ padding: 0, overflow: "hidden" }}>
              <div style={{ background: "#FFFFFF", aspectRatio: "4/3", display: "grid", placeItems: "center", borderBottom: "1px solid var(--line)" }}>
                <img src={l.src} alt={l.name} style={{ width: l.w, maxWidth: l.maxW, display: "block" }} />
              </div>
              <div style={{ padding: 16 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 15, letterSpacing: "-0.01em" }}>{l.name}</div>
                  <div style={{ display: "flex", gap: 4, flexShrink: 0 }}>
                    <button className="btn btn-sm btn-ghost" onClick={() => downloadAsset(l.src, l.src.split("/").pop())}>
                      <Icons.Download size={12} /> SVG
                    </button>
                  </div>
                </div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.45 }}>{l.desc}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Same three on dark */}
        <div className="grid-3" style={{ marginTop: 14 }}>
          {[
            { src: "assets/logo-wordmark-white.svg", w: "82%", maxW: 320 },
            { src: "assets/logo-stacked-white.svg", w: "52%", maxW: 170 },
            { src: "assets/logo-mark-white.svg", w: "48%", maxW: 150 },
          ].map((l) => (
            <div key={l.src} className="card" style={{ padding: 0, overflow: "hidden", background: "#070707", border: "1px solid #2A2A2A" }}>
              <div style={{ aspectRatio: "4/3", display: "grid", placeItems: "center" }}>
                <img src={l.src} alt="" style={{ width: l.w, maxWidth: l.maxW, display: "block" }} />
              </div>
              <div style={{ display: "flex", gap: 4, justifyContent: "flex-end", padding: "0 12px 12px" }}>
                <button className="btn btn-sm btn-ghost" style={{ color: "#BFBFBF", borderColor: "#333" }} onClick={() => downloadAsset(l.src, l.src.split("/").pop())}>
                  <Icons.Download size={12} /> SVG
                </button>
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 14 }}>
          <button className="btn btn-surface" onClick={() => downloadAll(LOGO_KIT_FILES)}>
            <Icons.Download size={13} /> Download all logos (SVG)
          </button>
        </div>
        <ul style={{ marginTop: 20, paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 10 }}>
          {BRAND.logo.usage.map((u, i) => (
            <li key={i} style={{ display: "flex", gap: 12, fontSize: 14, color: "var(--ink-2)" }}>
              <div style={{ width: 6, height: 6, background: "var(--ink)", borderRadius: 1, marginTop: 8, flex: "0 0 auto" }} />
              {u}
            </li>
          ))}
        </ul>
      </section>

      {/* SPACING */}
      <section style={{ marginTop: 64 }}>
        <SectionHeader label="07" title="Spacing" subtitle="Multiples of 4. Always." />
        <div className="card" style={{ padding: 24, marginTop: 20 }}>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 12 }}>
            {BRAND.spacing.map((s) => (
              <div key={s.name} style={{ textAlign: "center" }}>
                <div style={{ width: s.value, height: s.value, background: "var(--ink)", marginBottom: 8 }} />
                <div style={{ fontSize: 12, fontFamily: "var(--font-mono)", color: "var(--ink-2)" }}>{s.name}</div>
                <div style={{ fontSize: 10, color: "var(--ink-3)" }}>{s.value}px</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FOOTER */}
      <section style={{ marginTop: 80, padding: "32px 0", borderTop: "1px solid var(--line)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
          <div>
            <div className="eyebrow">EXPORT</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600, marginTop: 6 }}>
              Want this in your repo? Take it.
            </div>
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-ghost"><Icons.Copy size={13} /> Copy CSS tokens</button>
            <button className="btn btn-primary" onClick={downloadMD}>
              <Icons.Download size={13} /> Download MD
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

function SectionHeader({ label, title, subtitle }) {
  return (
    <div style={{ display: "flex", alignItems: "baseline", gap: 20, paddingBottom: 12, borderBottom: "1px solid var(--line)" }}>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 24, color: "var(--ink-4)", letterSpacing: "-0.03em" }}>{label}</div>
      <h2 className="section-title" style={{ fontSize: 28 }}>{title}</h2>
      <div style={{ flex: 1 }} />
      <div style={{ fontSize: 14, color: "var(--ink-3)" }}>{subtitle}</div>
    </div>
  );
}

function HoloSwatchCard() {
  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div
        style={{
          height: 96,
          backgroundImage: "url(assets/holo-texture.png)",
          backgroundSize: "cover",
          backgroundPosition: "center",
          borderBottom: "1px solid var(--line)",
        }}
      />
      <div style={{ padding: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 14, letterSpacing: "-0.01em" }}>Holographic foil</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)" }}>FOIL</div>
        </div>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.4 }}>
          Scanned iridescent texture. The single expressive accent — used as the CTA stroke and sticker foil, never as a flat fill.
        </div>
      </div>
    </div>
  );
}

function SwatchCard({ color, large, muted }) {  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ height: large ? 160 : 96, background: color.hex, borderBottom: "1px solid var(--line)" }} />
      <div style={{ padding: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 14, letterSpacing: "-0.01em" }}>{color.name}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase" }}>{color.hex}</div>
        </div>
        {color.usage && !muted && (
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.4 }}>{color.usage}</div>
        )}
      </div>
    </div>
  );
}

// =============================================================
// Generate the brand foundations as Markdown
// =============================================================
function generateBrandMD() {
  const lines = [];
  lines.push(`# ${BRAND.name} — Brand Foundations`);
  lines.push("");
  lines.push(`> ${BRAND.tagline}`);
  lines.push("");
  lines.push(BRAND.description);
  lines.push("");
  lines.push("---");
  lines.push("");

  // Colors
  lines.push("## 01 — Colors");
  lines.push("");
  lines.push("### Primary");
  lines.push("");
  lines.push("| Name | Hex | Usage |");
  lines.push("| --- | --- | --- |");
  BRAND.colors.primary.forEach(c => lines.push(`| ${c.name} | \`${c.hex}\` | ${c.usage} |`));
  lines.push("");
  lines.push("### Accents");
  lines.push("");
  if (BRAND.colors.accents.length) {
    lines.push("| Name | Hex | Usage |");
    lines.push("| --- | --- | --- |");
    BRAND.colors.accents.forEach(c => lines.push(`| ${c.name} | \`${c.hex}\` | ${c.usage} |`));
  } else {
    lines.push("No flat color accents. Black does the work; the holographic foil (a scanned texture, not a hex) is the single expressive note — used as the CTA stroke and sticker foil, never as a fill.");
  }
  lines.push("");
  lines.push("### Neutrals");
  lines.push("");
  lines.push("| Name | Hex | Usage |");
  lines.push("| --- | --- | --- |");
  BRAND.colors.neutrals.forEach(c => lines.push(`| ${c.name} | \`${c.hex}\` | ${c.usage} |`));
  lines.push("");

  // Typography
  lines.push("## 02 — Typography");
  lines.push("");
  BRAND.typography.families.forEach(f => {
    lines.push(`### ${f.name} — ${f.role}`);
    lines.push("");
    lines.push(`- **Usage:** ${f.usage}`);
    lines.push(`- **Weights:** ${f.weights}`);
    lines.push(`- **Sample:** _${f.sample}_`);
    lines.push("");
  });
  lines.push("### Type scale");
  lines.push("");
  lines.push("| Label | Size | Line height | Weight | Family |");
  lines.push("| --- | --- | --- | --- | --- |");
  BRAND.typography.scale.forEach(s => lines.push(`| ${s.label} | ${s.size}px | ${s.lineHeight} | ${s.weight} | ${s.family} |`));
  lines.push("");

  // Shapes
  lines.push("## 03 — Shapes");
  lines.push("");
  lines.push("### Corner radii");
  lines.push("");
  lines.push("| Name | Value | Usage |");
  lines.push("| --- | --- | --- |");
  BRAND.shapes.radii.forEach(r => lines.push(`| ${r.name} | ${r.value === 999 ? "Pill (∞)" : `${r.value}px`} | ${r.usage} |`));
  lines.push("");
  lines.push("### Pills");
  lines.push("");
  lines.push("Pills are short rounded labels used as visual punctuation. Use sparingly — never more than one per composition.");
  lines.push("");

  // Imagery
  lines.push("## 04 — Imagery");
  lines.push("");
  BRAND.imagery.principles.forEach(p => {
    lines.push(`### ${p.title}`);
    lines.push("");
    lines.push(p.desc);
    lines.push("");
  });

  // Voice
  lines.push("## 05 — Voice & tone");
  lines.push("");
  lines.push("| Do | Don't |");
  lines.push("| --- | --- |");
  BRAND.voice.principles.forEach(p => lines.push(`| ${p.do} | ${p.dont} |`));
  lines.push("");

  // Logo
  lines.push("## 06 — Logo");
  lines.push("");
  lines.push(`Wordmark: **${BRAND.logo.primary}**`);
  lines.push("");
  BRAND.logo.usage.forEach(u => lines.push(`- ${u}`));
  lines.push("");

  // Spacing
  lines.push("## 07 — Spacing");
  lines.push("");
  lines.push("Spacing scale uses multiples of 4.");
  lines.push("");
  lines.push("| Name | Value |");
  lines.push("| --- | --- |");
  BRAND.spacing.forEach(s => lines.push(`| ${s.name} | ${s.value}px |`));
  lines.push("");

  // CSS tokens
  lines.push("## CSS tokens");
  lines.push("");
  lines.push("```css");
  lines.push(":root {");
  [...BRAND.colors.primary, ...BRAND.colors.accents, ...BRAND.colors.neutrals].forEach(c => {
    const slug = c.name.toLowerCase().replace(/\s+/g, "-");
    lines.push(`  --color-${slug}: ${c.hex};`);
  });
  BRAND.spacing.forEach(s => lines.push(`  --space-${s.name}: ${s.value}px;`));
  BRAND.shapes.radii.forEach(r => lines.push(`  --radius-${r.name.toLowerCase()}: ${r.value === 999 ? "9999px" : `${r.value}px`};`));
  lines.push("}");
  lines.push("```");
  lines.push("");
  lines.push("---");
  lines.push("");
  lines.push(`_Generated by Flexxi Marketing Asset Generator · ${new Date().toLocaleDateString()}_`);
  lines.push("");

  return lines.join("\n");
}

window.BrandFoundationsPage = BrandFoundationsPage;
