// Vanday DAM — Tweaks panel
// Surfaces a handful of visual + behavior knobs so the user can play
// with the design without rebuilding. Tweaks the user picks here are
// persisted via the host (__edit_mode_set_keys) and written into the
// EDITMODE-BEGIN/END block at the top of this file.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent":         "#D97757",
  "sidebarDensity": "comfy",
  "cardDensity":    "comfy",
  "thumbStyle":     "cover",
  "mono":           "Geist Mono",
  "showAITags":     true,
  "showExpiry":     true,
  "showSimilar":    true,
  "uiCorner":       10
}/*EDITMODE-END*/;

// Reasonable curated swatches. Hex so the underlying var(--accent) can
// be overridden via plain CSS variable update — the rest of the palette
// reads from this token.
const ACCENT_OPTIONS = [
  "#D97757",  // warm orange (default)
  "#2A6FDB",  // confident blue
  "#1F8A5B",  // forest green
  "#7C3AED",  // editorial purple
  "#E11D48",  // hot magenta
  "#0F172A",  // monochrome slate
];

const MONO_OPTIONS = [
  "Geist Mono",
  "JetBrains Mono",
  "IBM Plex Mono",
  "Fira Code",
];

// Convert hex → oklch params (rough — we tweak L+C from a fixed swatch and reuse hex for accent itself).
function applyTweaks(t) {
  const root = document.documentElement.style;
  root.setProperty("--accent", t.accent);
  // Re-derive accent-soft and accent-hover from the chosen accent.
  root.setProperty("--accent-soft", t.accent + "1F"); // ~12% alpha
  root.setProperty("--accent-hover", shade(t.accent, -0.08));

  // Corner radius scale
  const c = Number(t.uiCorner) || 10;
  root.setProperty("--radius", c + "px");
  root.setProperty("--radius-sm", Math.max(2, c - 4) + "px");
  root.setProperty("--radius-lg", c + 4 + "px");
  root.setProperty("--radius-xl", c + 10 + "px");

  // Mono font
  root.setProperty("--font-mono",
    `"${t.mono}", ui-monospace, "SF Mono", Menlo, Consolas, monospace`);
  ensureGoogleFont(t.mono);

  // Density classes on <body>
  document.body.classList.toggle("tw-tight",  t.cardDensity === "tight");
  document.body.classList.toggle("tw-roomy",  t.cardDensity === "roomy");
  document.body.classList.toggle("tw-sb-tight", t.sidebarDensity === "tight");
  document.body.classList.toggle("tw-sb-roomy", t.sidebarDensity === "roomy");
  document.body.classList.toggle("tw-thumb-contain", t.thumbStyle === "contain");
  document.body.classList.toggle("tw-hide-ai", !t.showAITags);
  document.body.classList.toggle("tw-hide-expiry", !t.showExpiry);
  document.body.classList.toggle("tw-hide-similar", !t.showSimilar);
}

function shade(hex, amt) {
  // amt in -1..1; negative darkens.
  const h = hex.replace("#", "");
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  const adj = (c) => Math.max(0, Math.min(255, Math.round(c + 255 * amt)));
  return "#" + [adj(r), adj(g), adj(b)].map((c) => c.toString(16).padStart(2, "0")).join("");
}

const _loadedFonts = new Set();
function ensureGoogleFont(name) {
  if (!name || _loadedFonts.has(name)) return;
  _loadedFonts.add(name);
  const id = `gf-${name.replace(/\s+/g, "-")}`;
  if (document.getElementById(id)) return;
  const link = document.createElement("link");
  link.id = id;
  link.rel = "stylesheet";
  link.href = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(name)}:wght@400;500;600;700&display=swap`;
  document.head.appendChild(link);
}

function VandayTweaks() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  React.useEffect(() => { applyTweaks(t); }, [t]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Brand">
        <TweakColor
          label="Accent color"
          options={ACCENT_OPTIONS}
          value={t.accent}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakSelect
          label="Mono typeface"
          help="Used for filenames, code, audit timestamps, etc."
          options={MONO_OPTIONS}
          value={t.mono}
          onChange={(v) => setTweak("mono", v)}
        />
        <TweakSlider
          label="UI corner radius"
          min={0} max={24} step={1}
          value={t.uiCorner}
          onChange={(v) => setTweak("uiCorner", v)}
          format={(v) => `${v}px`}
        />
      </TweakSection>

      <TweakSection title="Layout">
        <TweakRadio
          label="Sidebar density"
          options={[
            { value: "tight", label: "Tight" },
            { value: "comfy", label: "Comfy" },
            { value: "roomy", label: "Roomy" },
          ]}
          value={t.sidebarDensity}
          onChange={(v) => setTweak("sidebarDensity", v)}
        />
        <TweakRadio
          label="Card density"
          options={[
            { value: "tight", label: "Tight" },
            { value: "comfy", label: "Comfy" },
            { value: "roomy", label: "Roomy" },
          ]}
          value={t.cardDensity}
          onChange={(v) => setTweak("cardDensity", v)}
        />
        <TweakRadio
          label="Thumbnail fit"
          options={[
            { value: "cover",   label: "Fill" },
            { value: "contain", label: "Fit" },
          ]}
          value={t.thumbStyle}
          onChange={(v) => setTweak("thumbStyle", v)}
        />
      </TweakSection>

      <TweakSection title="Card chrome">
        <TweakToggle
          label="AI tag chips"
          help="Show auto-generated keywords on cards"
          value={t.showAITags}
          onChange={(v) => setTweak("showAITags", v)}
        />
        <TweakToggle
          label="Expiry badges"
          help="Yellow / red badge on assets with an expiration date"
          value={t.showExpiry}
          onChange={(v) => setTweak("showExpiry", v)}
        />
        <TweakToggle
          label="Find-similar pill"
          help="Hover-revealed 'Similar' pill on every thumb"
          value={t.showSimilar}
          onChange={(v) => setTweak("showSimilar", v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// Mount the panel into a portal node so it doesn't disturb the app tree.
function mountTweaks() {
  let host = document.getElementById("__tweaks-root");
  if (!host) {
    host = document.createElement("div");
    host.id = "__tweaks-root";
    document.body.appendChild(host);
  }
  ReactDOM.createRoot(host).render(<VandayTweaks />);
}

// Render after first frame so the app has mounted first.
window.requestAnimationFrame(mountTweaks);
