/* Theme tweak panel — swaps design tokens (--paper, --cream, --line, --ink…)
   so every surface in the app shifts at once instead of just <body>. */

const { useEffect: useEffectT } = React;

const THEMES = {
  cream:    { label: "Warm cream",    bgHue: 70,  paperL: 0.97, accent: [0.55, 0.15, 33],  dark: false },
  paper:    { label: "Neutral paper", bgHue: 80,  paperL: 0.96, accent: [0.55, 0.15, 33],  dark: false },
  slate:    { label: "Cool slate",    bgHue: 240, paperL: 0.96, accent: [0.55, 0.18, 250], dark: false },
  sage:     { label: "Muted sage",    bgHue: 130, paperL: 0.96, accent: [0.50, 0.10, 145], dark: false },
  graphite: { label: "Graphite dark", bgHue: 80,  paperL: 0.16, accent: [0.70, 0.16, 33],  dark: true  },
};

// Color harmony — derives background hue from accent hue
const HARMONIES = {
  none:          { label: "No harmony (use palette bg)" },
  monochrome:    { label: "Monochrome (bg = accent)",        offset:   0 },
  analogous:     { label: "Analogous (+30°)",                offset:  30 },
  analogousNeg:  { label: "Analogous (−30°)",                offset: -30 },
  complementary: { label: "Complementary (+180°)",           offset: 180 },
  triadic:       { label: "Triadic (+120°)",                 offset: 120 },
  splitComp:     { label: "Split complementary (+150°)",     offset: 150 },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "paper",
  "harmony": "none",
  "accentHue": 35,
  "accentChroma": 0.17,
  "bgChroma": 0.005,
  "lineChroma": 0.02,
  "lineWidth": 0.5,
  "contrast": 1,
  "radius": 4
}/*EDITMODE-END*/;

const oklch = (l, c, h) => `oklch(${l.toFixed(3)} ${c.toFixed(3)} ${((h % 360) + 360) % 360})`;

function computeTokens(theme, t) {
  const dark = theme.dark;
  // Resolve background hue: harmony pulls from accent, otherwise use the theme's bgHue
  const harmony = HARMONIES[t.harmony];
  const bgH = harmony && harmony.offset != null ? t.accentHue + harmony.offset : theme.bgHue;
  const bgC = t.bgChroma;
  const contrast = t.contrast;

  const paperL = theme.paperL;
  let creamL, cream2L, lineL, line2L;

  if (!dark) {
    creamL  = paperL - 0.025 * contrast;
    cream2L = paperL - 0.045 * contrast;
    lineL   = paperL - 0.10  * contrast;
    line2L  = paperL - 0.06  * contrast;
  } else {
    creamL  = paperL + 0.04  * contrast;
    cream2L = paperL + 0.06  * contrast;
    lineL   = paperL + 0.12  * contrast;
    line2L  = paperL + 0.08  * contrast;
  }

  const inkL  = dark ? 0.96 : 0.10;
  const ink2L = dark ? 0.90 : 0.18;
  const ink3L = dark ? 0.70 : 0.36;
  const muteL = dark ? 0.55 : 0.58;

  // Line chroma is now ABSOLUTE (was bgC * lineChroma — when bgC≈0 lines never colored).
  // Default 0.02 is subtle; up to 0.15 makes borders clearly tinted.
  const lineC = t.lineChroma;

  return {
    "--paper":   oklch(paperL,  bgC,   bgH),
    "--cream":   oklch(creamL,  bgC,   bgH),
    "--cream-2": oklch(cream2L, bgC,   bgH),
    "--line":    oklch(lineL,   lineC, bgH),
    "--line-2":  oklch(line2L,  lineC, bgH),
    "--ink":     oklch(inkL,    bgC * 0.4, bgH),
    "--ink-2":   oklch(ink2L,   bgC * 0.4, bgH),
    "--ink-3":   oklch(ink3L,   bgC * 0.3, bgH),
    "--mute":    oklch(muteL,   bgC * 0.3, bgH),
    "--accent":     oklch(0.55, t.accentChroma,        t.accentHue),
    "--accent-ink": oklch(0.42, t.accentChroma * 0.85, t.accentHue),
    "--card-radius": `${t.radius}px`,
    "--line-w": `${t.lineWidth}px`,
  };
}

function applyTokens(tokens) {
  const root = document.documentElement;
  Object.entries(tokens).forEach(([k, v]) => root.style.setProperty(k, v));
}

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

  useEffectT(() => {
    const theme = THEMES[t.theme] || THEMES.paper;
    applyTokens(computeTokens(theme, t));
    if (document.body.style.backgroundColor) document.body.style.backgroundColor = "";
  }, [t.theme, t.harmony, t.accentHue, t.accentChroma, t.bgChroma, t.lineChroma, t.lineWidth, t.contrast, t.radius]);

  const pickTheme = (key) => {
    const theme = THEMES[key];
    setTweak({
      theme: key,
      accentHue: theme.accent[2],
      accentChroma: theme.accent[1],
    });
  };

  const harmonyOpts = Object.entries(HARMONIES).map(([k, v]) => ({ value: k, label: v.label }));

  return (
    <TweaksPanel title="Theme">
      <TweakSection label="Palette" hint="Swaps every surface — sidebar, cards, table, KPIs — at once." />
      <div style={{display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap: 8, padding: '4px 0 8px'}}>
        {Object.entries(THEMES).map(([key, theme]) => {
          const active = t.theme === key;
          const swatch = [
            oklch(theme.paperL, 0.005, theme.bgHue),
            oklch(theme.paperL - 0.04, 0.005, theme.bgHue),
            oklch(theme.accent[0], theme.accent[1], theme.accent[2]),
          ];
          return (
            <button
              key={key}
              onClick={() => pickTheme(key)}
              style={{
                display:'flex', flexDirection:'column', gap: 6,
                padding: 8, borderRadius: 6,
                border: `1px solid ${active ? '#111' : '#d4d4d4'}`,
                background: active ? '#fafafa' : '#fff',
                cursor:'pointer', textAlign:'left', fontFamily:'inherit',
                outline: active ? '2px solid #111' : 'none',
                outlineOffset: -1,
              }}
            >
              <div style={{display:'flex', height: 22, borderRadius: 3, overflow:'hidden', border:'1px solid rgba(0,0,0,0.08)'}}>
                {swatch.map((c, i) => <div key={i} style={{flex: 1, background: c}}/>)}
              </div>
              <div style={{fontSize: 11, color:'#222', fontWeight: active ? 600 : 400}}>{theme.label}</div>
            </button>
          );
        })}
      </div>

      <TweakSection label="Accent" />
      <TweakSlider label="Hue" value={t.accentHue} min={0} max={360} step={1}
                   onChange={(v) => setTweak('accentHue', v)} />
      <TweakSlider label="Saturation" value={Math.round(t.accentChroma * 100)} min={0} max={30} step={1} unit="%"
                   onChange={(v) => setTweak('accentChroma', v / 100)} />

      <TweakSection label="Color harmony" hint="Derive background hue from the accent hue." />
      <TweakSelect label="Harmony" value={t.harmony} options={harmonyOpts}
                   onChange={(v) => setTweak('harmony', v)} />

      <TweakSection label="Surfaces" />
      <TweakSlider label="Background tint" value={Math.round(t.bgChroma * 1000)} min={0} max={40} step={1}
                   onChange={(v) => setTweak('bgChroma', v / 1000)} />
      <TweakSlider label="Line saturation" value={Math.round(t.lineChroma * 1000)} min={0} max={150} step={1}
                   onChange={(v) => setTweak('lineChroma', v / 1000)} />
      <TweakSlider label="Line thickness" value={t.lineWidth} min={0} max={4} step={0.5} unit="px"
                   onChange={(v) => setTweak('lineWidth', v)} />
      <TweakSlider label="Panel contrast" value={Math.round(t.contrast * 100)} min={50} max={400} step={5} unit="%"
                   onChange={(v) => setTweak('contrast', v / 100)} />
      <TweakSlider label="Corner radius" value={t.radius} min={0} max={20} unit="px"
                   onChange={(v) => setTweak('radius', v)} />
    </TweaksPanel>
  );
}

Object.assign(window, { ThemeTweaks, THEMES });
