// rs-tweaks.jsx — ROBSEEK Tweaks panel
// Shared across all pages. Loads tweak defaults from an EDITMODE block,
// wires theme / type pairing / hero style / accent intensity into DOM.

(function initRSTweaks() {
  // Read EDITMODE defaults from the host page; fall back to sensible defaults.
  // Any page that wants custom defaults sets window.RS_TWEAK_DEFAULTS before
  // this file loads (via an inline EDITMODE block + assignment).
  const DEFAULTS = window.RS_TWEAK_DEFAULTS || {
    theme: 'dark',         // 'dark' | 'light'
    typePair: 'grotesk',   // 'grotesk' (Space Grotesk + Inter) | 'sora' (Sora + Manrope)
    heroStyle: 'atmospheric', // 'atmospheric' (striped placeholder) | 'coded' (pure grid + no image)
    accentIntensity: 100,  // 60-140 (%)
    motionLevel: 'moderate', // 'off' | 'subtle' | 'moderate'
  };

  // One-time Google font preload for secondary pairing
  const fontsLink = document.createElement('link');
  fontsLink.rel = 'stylesheet';
  fontsLink.href = 'https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;600;700&family=Sora:wght@400;500;600;700&display=swap';
  document.head.appendChild(fontsLink);

  function applyTweaks(t) {
    const html = document.documentElement;
    // theme
    html.setAttribute('data-theme', t.theme);
    try { localStorage.setItem('rs-theme', t.theme); } catch (e) {}
    // type pairing via CSS vars
    if (t.typePair === 'sora') {
      html.style.setProperty('--rs-display', "'Sora', sans-serif");
      html.style.setProperty('--rs-sans', "'Manrope', sans-serif");
    } else {
      html.style.removeProperty('--rs-display');
      html.style.removeProperty('--rs-sans');
    }
    // accent intensity → modulates red channel via a filter-less approach:
    // we override --rs-red with a mixed value.
    const k = Math.max(60, Math.min(140, t.accentIntensity | 0));
    // Base red #EA0700 (234, 7, 0). Intensity scales saturation/luminance
    // by blending toward black (<100) or white (>100).
    const base = { r: 234, g: 7, b: 0 };
    let r, g, b;
    if (k === 100) { r = base.r; g = base.g; b = base.b; }
    else if (k < 100) {
      const m = k / 100;
      r = Math.round(base.r * m); g = Math.round(base.g * m); b = Math.round(base.b * m);
    } else {
      const m = (k - 100) / 40; // 0..1
      r = Math.round(base.r + (255 - base.r) * m * 0.4);
      g = Math.round(base.g + (255 - base.g) * m * 0.6);
      b = Math.round(base.b + (255 - base.b) * m * 0.6);
    }
    html.style.setProperty('--rs-red', `rgb(${r},${g},${b})`);

    // hero style
    html.setAttribute('data-hero-style', t.heroStyle);
    // motion
    html.setAttribute('data-motion', t.motionLevel);
  }

  // Apply tweaks immediately (before React mount) using whatever's stored.
  // The header ThemeToggle (in components.jsx) only writes to the simple
  // 'rs-theme' key; if its value is more recent than what's inside the
  // 'rs-tweaks' JSON, prefer it so the header toggle isn't silently
  // overridden on the next page load.
  const stored = (() => {
    try {
      const tweaks = JSON.parse(localStorage.getItem('rs-tweaks') || 'null') || { ...DEFAULTS };
      const theme = localStorage.getItem('rs-theme');
      if (theme === 'light' || theme === 'dark') tweaks.theme = theme;
      return tweaks;
    } catch (e) { return { ...DEFAULTS }; }
  })();
  applyTweaks(stored);

  // Wait for React + tweaks-panel starter to load, then mount UI
  function mount() {
    if (!window.React || !window.TweaksPanel) { setTimeout(mount, 50); return; }
    const { useState } = window.React;

    function RSTweaks() {
      const [t, setT] = useState(stored);
      const setK = (k, v) => {
        const next = { ...t, [k]: v };
        setT(next);
        applyTweaks(next);
        try { localStorage.setItem('rs-tweaks', JSON.stringify(next)); } catch (e) {}
        // Also persist to host's EDITMODE block if present
        window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
      };
      const reset = () => {
        setT(DEFAULTS);
        applyTweaks(DEFAULTS);
        try { localStorage.setItem('rs-tweaks', JSON.stringify(DEFAULTS)); } catch (e) {}
      };
      return (
        <TweaksPanel title="Tweaks">
          <TweakSection label="Theme">
            <TweakRadio
              label="Mode"
              value={t.theme}
              options={[
                { value: 'dark',  label: 'Dark' },
                { value: 'light', label: 'Light' },
              ]}
              onChange={(v) => setK('theme', v)}
            />
          </TweakSection>

          <TweakSection label="Typography">
            <TweakRadio
              label="Pairing"
              value={t.typePair}
              options={[
                { value: 'grotesk', label: 'Space Grotesk · Inter' },
                { value: 'sora',    label: 'Sora · Manrope' },
              ]}
              onChange={(v) => setK('typePair', v)}
            />
          </TweakSection>

          <TweakSection label="Accent">
            <TweakSlider
              label="Intensity"
              value={t.accentIntensity}
              min={60} max={140} step={5} unit="%"
              onChange={(v) => setK('accentIntensity', v)}
            />
          </TweakSection>

          <TweakSection label="Hero visual">
            <TweakRadio
              label="Style"
              value={t.heroStyle}
              options={[
                { value: 'atmospheric', label: 'Atmospheric placeholder' },
                { value: 'coded',       label: 'Pure coded' },
              ]}
              onChange={(v) => setK('heroStyle', v)}
            />
          </TweakSection>

          <TweakSection label="Motion">
            <TweakRadio
              label="Level"
              value={t.motionLevel}
              options={[
                { value: 'off',      label: 'Off' },
                { value: 'subtle',   label: 'Subtle' },
                { value: 'moderate', label: 'Moderate' },
              ]}
              onChange={(v) => setK('motionLevel', v)}
            />
          </TweakSection>

          <TweakSection label="">
            <TweakButton label="Reset to defaults" secondary onClick={reset}/>
          </TweakSection>
        </TweaksPanel>
      );
    }

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