/* ===== Juristfri — Tweaks (color/type explorer) ===== */
const { useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakColor } = window;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "Marin",
  "type": "Serif",
  "accent": "#E07856"
}/*EDITMODE-END*/;

const THEME_MAP = { "Marin": "marin", "Skog": "skog", "Plommon": "plommon" };
const TYPE_MAP  = { "Serif": "serif", "Kontrast": "contrast", "Sans": "sans" };

// theme -> its native accent (so switching theme resets accent unless overridden)
const THEME_ACCENT = { marin: "#E07856", skog: "#D98A3D", plommon: "#C9667E" };

function tint(hex){
  // light tint of accent for --accent-soft
  const h = hex.replace('#',''); const r=parseInt(h.slice(0,2),16),g=parseInt(h.slice(2,4),16),b=parseInt(h.slice(4,6),16);
  const m=(c)=>Math.round(c+(255-c)*0.82);
  return `rgb(${m(r)}, ${m(g)}, ${m(b)})`;
}

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

  React.useEffect(() => {
    const theme = THEME_MAP[t.theme] || "marin";
    root.setAttribute('data-theme', theme);
    root.setAttribute('data-type', TYPE_MAP[t.type] || "serif");
    // accent: use override if it differs from the (previous) default behaviour
    const acc = t.accent || THEME_ACCENT[theme];
    root.style.setProperty('--accent', acc);
    root.style.setProperty('--accent-soft', tint(acc));
    if(window.refreshIcons) window.refreshIcons();
  }, [t.theme, t.type, t.accent]);

  // when theme changes, snap accent to that theme's native accent
  const onTheme = (v) => {
    setTweak({ theme: v, accent: THEME_ACCENT[THEME_MAP[v]] });
  };

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Färgtema" />
      <TweakRadio label="Tema" value={t.theme}
        options={["Marin", "Skog", "Plommon"]}
        onChange={onTheme} />
      <TweakColor label="Accentfärg" value={t.accent}
        options={["#E07856", "#D98A3D", "#C9667E", "#2F7DA8", "#7B8A3A"]}
        onChange={(v) => setTweak('accent', v)} />
      <TweakSection label="Typografi" />
      <TweakRadio label="Typsnitt" value={t.type}
        options={["Serif", "Kontrast", "Sans"]}
        onChange={(v) => setTweak('type', v)} />
    </TweaksPanel>
  );
}

const mount = document.createElement('div');
mount.id = 'tweaks-root';
document.body.appendChild(mount);
ReactDOM.createRoot(mount).render(<App />);
