// Live palette switcher. Updates document.documentElement.dataset.palette,
// persists in localStorage, broadcasts 'bits-palette-change' so SVG sections
// (Timeline) can re-read computed CSS vars.
window.BITSPalettes = [
  {
    id: "canvas",
    name: "Ivory Canvas",
    sub: "v1 · cream + navy + gold",
    note: "Current. Reads Anthropic-ish.",
    swatches: ["#FBF8F1", "#002855", "#C8A95B"],
  },
  {
    id: "paper",
    name: "Clean Paper",
    sub: "white · navy · gold",
    note: "Strip the cream, keep the accents.",
    swatches: ["#FFFFFF", "#002855", "#C8A95B"],
  },
  {
    id: "cool",
    name: "Institution Cool",
    sub: "pale blue · navy · gold",
    note: "Corporate, institutional, calm.",
    swatches: ["#F2F6FB", "#002855", "#C8A95B"],
  },
  {
    id: "saffron",
    name: "Saffron Sprint",
    sub: "white · Ashoka blue · saffron",
    note: "Indian, energetic, warm.",
    swatches: ["#FFFFFF", "#0B3D91", "#F97316"],
  },
  {
    id: "forest",
    name: "Forest Academy",
    sub: "bone · forest green · amber",
    note: "Collegiate, Ivy-adjacent.",
    swatches: ["#F9F7EF", "#0F3D2E", "#D97706"],
  },
  {
    id: "graphite",
    name: "Editorial Graphite",
    sub: "off-white · graphite · marigold",
    note: "Bold, publication-grade.",
    swatches: ["#F7F5F0", "#1A1A1A", "#D4A017"],
  },
];

window.BITSPaletteHook = () => {
  const [version, setVersion] = React.useState(0);
  React.useEffect(() => {
    const h = () => setVersion((v) => v + 1);
    window.addEventListener("bits-palette-change", h);
    return () => window.removeEventListener("bits-palette-change", h);
  }, []);
  return version;
};

window.BITSApplyPalette = (id) => {
  document.documentElement.dataset.palette = id;
  try {
    localStorage.setItem("bits-palette", id);
  } catch (e) {}
  window.dispatchEvent(new CustomEvent("bits-palette-change", { detail: id }));
};

window.PalettePicker = () => {
  const [open, setOpen] = React.useState(false);
  const [current, setCurrent] = React.useState(() => {
    try {
      return localStorage.getItem("bits-palette") || "canvas";
    } catch (e) {
      return "canvas";
    }
  });

  React.useEffect(() => {
    window.BITSApplyPalette(current);
  }, [current]);

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (!e.target.closest?.("[data-palette-picker]")) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  const active =
    window.BITSPalettes.find((p) => p.id === current) || window.BITSPalettes[0];

  return (
    <div className="relative" data-palette-picker>
      <button
        onClick={() => setOpen((v) => !v)}
        className="inline-flex items-center gap-2 px-2.5 py-1.5 rounded-full border border-bits-line bg-white/80 hover:border-bits-deep/40 transition-colors"
        aria-label="Change palette"
      >
        <span className="flex -space-x-1">
          {active.swatches.map((c, i) => (
            <span
              key={i}
              className="w-3.5 h-3.5 rounded-full ring-1 ring-black/10"
              style={{ background: c }}
            />
          ))}
        </span>
        <span className="text-[11.5px] font-semibold text-bits-ink">
          {active.name}
        </span>
        <svg
          width="12"
          height="12"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          className="text-bits-steel"
        >
          <path d="M6 9l6 6 6-6" />
        </svg>
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-80 z-50 rounded-2xl border border-bits-line bg-white shadow-glass p-2 fade-in">
          <div className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-bits-goldDeep">
            Choose a palette — previews live
          </div>
          <div className="grid grid-cols-1 gap-1">
            {window.BITSPalettes.map((p) => {
              const isActive = current === p.id;
              return (
                <button
                  key={p.id}
                  onClick={() => {
                    setCurrent(p.id);
                    setOpen(false);
                  }}
                  className={`w-full text-left px-2.5 py-2 rounded-lg flex items-center gap-3 transition-colors ${
                    isActive
                      ? "bg-bits-cream border border-bits-gold/50"
                      : "hover:bg-bits-mist/60 border border-transparent"
                  }`}
                >
                  <span className="flex -space-x-1 shrink-0">
                    {p.swatches.map((c, i) => (
                      <span
                        key={i}
                        className="w-5 h-5 rounded-full ring-1 ring-black/10"
                        style={{ background: c }}
                      />
                    ))}
                  </span>
                  <span className="flex-1 min-w-0">
                    <span className="flex items-center gap-2">
                      <span className="text-[13px] font-semibold text-bits-ink">
                        {p.name}
                      </span>
                      {isActive && (
                        <span className="text-[9px] font-bold uppercase tracking-wider text-bits-goldDeep">
                          · Active
                        </span>
                      )}
                    </span>
                    <span className="block text-[11px] text-bits-steel">
                      {p.note}
                    </span>
                  </span>
                </button>
              );
            })}
          </div>
          <div className="px-3 py-2 text-[10.5px] text-bits-steel border-t border-bits-line mt-1">
            Pick the one that feels like BITS. We'll lock it for the real asset
            set.
          </div>
        </div>
      )}
    </div>
  );
};
