/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakToggle */
const TRACE_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "display": "bricolage",
  "accent": "#00cd9c",
  "grid": true,
  "motion": true,
  "compliance": true
}/*EDITMODE-END*/;

function relLuminance(hex) {
  var c = hex.replace("#", "");
  if (c.length === 3) c = c.split("").map(function (x) { return x + x; }).join("");
  var r = parseInt(c.substr(0, 2), 16) / 255,
      g = parseInt(c.substr(2, 2), 16) / 255,
      b = parseInt(c.substr(4, 2), 16) / 255;
  var f = function (v) { return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
  return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
}

function TraceTweaks() {
  const [t, setTweak] = useTweaks(TRACE_TWEAK_DEFAULTS);
  const root = document.documentElement;

  React.useEffect(() => {
    root.setAttribute("data-display", t.display);
  }, [t.display]);

  React.useEffect(() => {
    root.style.setProperty("--accent", t.accent);
    // bright accents read better with dark ink; deeper accents with light ink
    const ink = relLuminance(t.accent) > 0.45 ? "#04221a" : "#ffffff";
    root.style.setProperty("--accent-ink", ink);
  }, [t.accent]);

  React.useEffect(() => {
    root.setAttribute("data-grid", t.grid ? "on" : "off");
  }, [t.grid]);

  React.useEffect(() => {
    root.setAttribute("data-motion", t.motion ? "on" : "off");
  }, [t.motion]);

  React.useEffect(() => {
    root.setAttribute("data-compliance", t.compliance ? "on" : "off");
  }, [t.compliance]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Type" />
      <TweakRadio
        label="Display face"
        value={t.display}
        options={[
          { value: "bricolage", label: "Bricolage" },
          { value: "schibsted", label: "Schibsted" },
          { value: "general", label: "General" },
        ]}
        onChange={(v) => setTweak("display", v)}
      />
      <TweakSection label="Accent" />
      <TweakColor
        label="CTA accent"
        value={t.accent}
        options={["#00cd9c", "#11a36f", "#f4633a", "#2f6bff"]}
        onChange={(v) => setTweak("accent", v)}
      />
      <TweakSection label="Atmosphere" />
      <TweakToggle label="Grid backdrop" value={t.grid} onChange={(v) => setTweak("grid", v)} />
      <TweakToggle label="Motion" value={t.motion} onChange={(v) => setTweak("motion", v)} />
      <TweakSection label="Content test" />
      <TweakToggle label="EU AI Act beat" value={t.compliance} onChange={(v) => setTweak("compliance", v)} />
    </TweaksPanel>
  );
}

var _tweaksRoot = document.getElementById("tweaks-root");
if (_tweaksRoot) { ReactDOM.createRoot(_tweaksRoot).render(<TraceTweaks />); }
