/* Color section — hero swatches, full tonal palettes, MD3 semantic mapping */

const TONAL_STOPS = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 92, 94, 95, 96, 99, 100];

function hueToColorName(hex) {
  if (!hex || hex.length < 7 || !window.hexToHsl) return "Custom";
  const [h, s, l] = window.hexToHsl(hex);
  if (l < 8)  return "Onyx";
  if (l > 93) return "Ivory";
  if (s < 8)  return l < 45 ? "Graphite" : "Pearl";
  if (h < 15 || h >= 345) return l < 45 ? "Crimson"  : "Blush";
  if (h < 30)              return l < 45 ? "Sienna"   : "Peach";
  if (h < 50)              return l < 45 ? "Amber"    : "Gold";
  if (h < 70)              return l < 45 ? "Olive"    : "Cream";
  if (h < 100)             return l < 45 ? "Fern"     : "Sage";
  if (h < 145)             return l < 45 ? "Emerald"  : "Mint";
  if (h < 175)             return l < 45 ? "Jade"     : "Seafoam";
  if (h < 210)             return l < 45 ? "Teal"     : "Aqua";
  if (h < 240)             return l < 45 ? "Azure"    : "Sky";
  if (h < 265)             return l < 45 ? "Sapphire" : "Periwinkle";
  if (h < 290)             return l < 45 ? "Indigo"   : "Lavender";
  if (h < 320)             return l < 45 ? "Violet"   : "Lilac";
  return                          l < 45 ? "Rose"     : "Blush";
}

function hexToRgb(hex) {
  const r = parseInt(hex.slice(1,3),16);
  const g = parseInt(hex.slice(3,5),16);
  const b = parseInt(hex.slice(5,7),16);
  return `${r}, ${g}, ${b}`;
}

function hexToCmyk(hex) {
  const r = parseInt(hex.slice(1,3),16)/255;
  const g = parseInt(hex.slice(3,5),16)/255;
  const b = parseInt(hex.slice(5,7),16)/255;
  const k = 1 - Math.max(r,g,b);
  if (k >= 1) return "0, 0, 0, 100";
  const c = Math.round((1-r-k)/(1-k)*100);
  const m = Math.round((1-g-k)/(1-k)*100);
  const y = Math.round((1-b-k)/(1-k)*100);
  return `${c}, ${m}, ${y}, ${Math.round(k*100)}`;
}

function isDarkHex(hex) {
  const r = parseInt(hex.slice(1,3),16), g = parseInt(hex.slice(3,5),16), b = parseInt(hex.slice(5,7),16);
  return (0.299*r + 0.587*g + 0.114*b) / 255 < 0.55;
}

/* ── Build functions accept precomputed scheme + palettes ── */

function buildHeroColors(scheme, effSec, effBg) {
  const entries = [
    { name: hueToColorName(scheme.primary),  hex: scheme.primary, role: "Primary · P-40",   note: "Buttons, FABs" },
    { name: hueToColorName(effSec),          hex: effSec,         role: "Secondary · P-40", note: "Celebration CTAs" },
    { name: hueToColorName(scheme.tertiary), hex: scheme.tertiary,role: "Tertiary · P-80",  note: "Editorial flourish" },
    { name: hueToColorName(scheme.neutral),  hex: scheme.neutral, role: "Neutral · N-95",   note: "Container base" },
    { name: hueToColorName(effBg),           hex: effBg,          role: "Surface · N-99",   note: "App canvas" },
  ];
  return entries.map(e => ({
    ...e,
    rgb:  hexToRgb(e.hex),
    cmyk: hexToCmyk(e.hex),
    text: isDarkHex(e.hex) ? "#FFFFFF" : "#1B1814",
  }));
}

function buildTonalPalettes(palettes) {
  if (!palettes) return null;
  return [
    { name: "Primary",   base: 40, pal: palettes.sap   },
    { name: "Secondary", base: 40, pal: palettes.rose  },
    { name: "Tertiary",  base: 80, pal: palettes.champ },
    { name: "Neutral",   base: 95, pal: palettes.neu   },
  ].map(({ name, base, pal }) => ({
    name,
    base,
    stops: TONAL_STOPS.map(tone => ({ tone, hex: pal[tone] || "#ffffff" })),
  }));
}

function buildMd3Tokens(effBg, palettes) {
  if (!palettes) return [];
  const { sap, rose, champ, neu } = palettes;
  return [
    { name: "primary",                  bg: "var(--md-primary)",                  fg: "var(--md-on-primary)",               hex: sap[40],  use: "Buttons, FABs · P-40" },
    { name: "on-primary",               bg: "var(--md-on-primary)",               fg: "var(--md-primary)",                  hex: "#FFFFFF",use: "Text on primary · P-100" },
    { name: "primary-container",        bg: "var(--md-primary-container)",         fg: "var(--md-on-primary-container)",     hex: sap[90],  use: "Tonal buttons · P-90" },
    { name: "on-primary-container",     bg: "var(--md-on-primary-container)",      fg: "var(--md-primary-container)",        hex: sap[10],  use: "Text on tonal · P-10" },
    { name: "secondary",                bg: "var(--md-secondary)",                 fg: "var(--md-on-secondary)",             hex: rose[40], use: "Celebration CTAs · P-40" },
    { name: "secondary-container",      bg: "var(--md-secondary-container)",       fg: "var(--md-on-secondary-container)",   hex: rose[90], use: "Soft accents · P-90" },
    { name: "tertiary",                 bg: "var(--md-tertiary)",                  fg: "var(--md-on-tertiary)",              hex: champ[40],use: "Editorial · P-40" },
    { name: "tertiary-container",       bg: "var(--md-tertiary-container)",        fg: "var(--md-on-tertiary-container)",    hex: champ[90],use: "Card BG · P-90" },
    { name: "surface",                  bg: "var(--md-surface)",                   fg: "var(--md-on-surface)",               hex: effBg,    use: "App canvas · N-99" },
    { name: "surface-variant",          bg: "var(--md-surface-variant)",           fg: "var(--md-on-surface-variant)",       hex: neu[90],  use: "Input fills · N-90" },
    { name: "surface-container-low",    bg: "var(--md-surface-container-low)",     fg: "var(--md-on-surface)",               hex: neu[96],  use: "Subtle BG · N-96" },
    { name: "surface-container",        bg: "var(--md-surface-container)",         fg: "var(--md-on-surface)",               hex: neu[94],  use: "Cards · N-94" },
    { name: "surface-container-high",   bg: "var(--md-surface-container-high)",    fg: "var(--md-on-surface)",               hex: neu[92],  use: "Sheets, modals · N-92" },
    { name: "surface-container-highest",bg: "var(--md-surface-container-highest)", fg: "var(--md-on-surface)",               hex: neu[90],  use: "Navigation · N-90" },
    { name: "error",                    bg: "var(--md-error)",                     fg: "var(--md-on-error)",                 hex: "#BA1A1A",use: "Destructive" },
    { name: "error-container",          bg: "var(--md-error-container)",           fg: "var(--md-on-error-container)",       hex: "#FFDAD6",use: "Error states" },
    { name: "outline",                  bg: "var(--md-outline)",                   fg: "#FFFFFF",                            hex: neu[50],  use: "Borders · N-50" },
    { name: "outline-variant",          bg: "var(--md-outline-variant)",           fg: "var(--md-on-surface)",               hex: neu[80],  use: "Dividers · N-80" },
  ];
}

function ColorSection({ onCopy, tweaks }) {
  const t = tweaks || window.__ZO_TWEAK_DEFAULTS || {};
  const derive   = window.deriveTonal;
  const toScheme = window.seedToScheme;

  /* Compute once — shared across all three build functions */
  const scheme  = toScheme ? toScheme(t.seed) : {
    primary: t.seed || '#1A2D6B', secondary: '#B76E79',
    tertiary: '#E8DCC4', neutral: '#F4EDE0', ivory: '#FBF8F3',
  };
  const effSec  = t.secondary || scheme.secondary;
  const effBg   = t.bg        || scheme.ivory;
  const palettes = derive ? {
    sap  : derive(scheme.primary,  40),
    rose : derive(effSec,          40),
    champ: derive(scheme.tertiary, 80),
    neu  : derive(scheme.neutral,  95, 14),
  } : null;

  const heroColors    = buildHeroColors(scheme, effSec, effBg);
  const tonalPalettes = buildTonalPalettes(palettes);
  const md3Tokens     = buildMd3Tokens(effBg, palettes);

  return (
    <section id="color" className="zo-section">
      <div className="zo-section-eyebrow">01 — Color</div>
      <h2 className="zo-section-title">A palette built for the unboxing.</h2>
      <p className="zo-section-lede">
        Sapphire holds the brand. Rose gold marks the moment of giving. Ivory and champagne carry everything else — quiet, warm, never loud.
      </p>

      <h3 className="zo-subsection-title">Hero colors</h3>
      <div className="zo-hero-swatches">
        {heroColors.map(c => (
          <div
            key={c.role}
            className="zo-swatch-hero"
            style={{ background: c.hex, color: c.text }}
            onClick={() => onCopy(c.hex)}
            title={`Copy ${c.hex}`}
          >
            <div>
              <div style={{ fontSize: 10, letterSpacing: 1.2, textTransform: "uppercase", opacity: 0.75, marginBottom: 6 }}>{c.role}</div>
              <div className="zo-swatch-hero-name">{c.name}</div>
            </div>
            <div className="zo-swatch-hero-meta">
              <div>{c.hex}</div>
              <div style={{ opacity: 0.75 }}>RGB {c.rgb}</div>
              <div style={{ opacity: 0.6, fontSize: 10, marginTop: 4 }}>CMYK {c.cmyk}</div>
            </div>
            <div className="zo-swatch-hero-copy">⌘ Copy</div>
          </div>
        ))}
      </div>

      <h3 className="zo-subsection-title">Tonal palettes</h3>
      <p style={{ color: "var(--md-on-surface-variant)", fontSize: 14, marginBottom: 24, maxWidth: "60ch" }}>
        Thirteen-stop MD3 tonal scale per family. The base tone of each is marked with a thin underline.
      </p>
      {tonalPalettes && (
        <div>
          <div className="zo-tonal-row" style={{ marginBottom: 12 }}>
            <div />
            {TONAL_STOPS.map(s => (
              <div key={s} style={{ fontSize: 10, fontFamily: "ui-monospace, monospace", color: "var(--md-on-surface-variant)", textAlign: "center", letterSpacing: 0.3 }}>{s}</div>
            ))}
          </div>
          {tonalPalettes.map(palette => (
            <div key={palette.name} className="zo-tonal-row">
              <div className="zo-tonal-label">{palette.name}</div>
              {palette.stops.map(s => (
                <div
                  key={s.tone}
                  className={`zo-tonal-step ${isDarkHex(s.hex) ? "dark" : "light"}`}
                  style={{
                    background: s.hex,
                    borderBottom: palette.base === s.tone ? "2px solid var(--md-primary)" : undefined,
                  }}
                  onClick={() => onCopy(s.hex)}
                  title={s.hex}
                >
                  {s.hex.replace("#","")}
                </div>
              ))}
            </div>
          ))}
        </div>
      )}

      <h3 className="zo-subsection-title">MD3 semantic mapping</h3>
      <p style={{ color: "var(--md-on-surface-variant)", fontSize: 14, marginBottom: 24, maxWidth: "60ch" }}>
        Every brand color resolves to a Material Design 3 token. These are what your engineers consume.
      </p>
      <div className="zo-md-grid">
        {md3Tokens.map(tk => (
          <div
            key={tk.name}
            className="zo-md-token"
            style={{ background: tk.bg, color: tk.fg }}
            onClick={() => onCopy(tk.name)}
            title={`Copy "${tk.name}"`}
          >
            <div className="zo-md-token-name">{tk.name}</div>
            <div className="zo-md-token-hex">{tk.hex}</div>
            <div className="zo-md-token-use">{tk.use}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

window.ColorSection = ColorSection;
