// tweaks.jsx — GenuineFy tweaks panel
// Page-aware: shows different controls on index.html vs saas.html
// All tweaks are reversible — toggling back to the default value
// removes any class / CSS-var override that the tweak applied.

(function () {
  'use strict';

  const isSaas = document.body.classList.contains('saas');

  const TWEAK_DEFAULTS = window.TWEAK_DEFAULTS || {
    palette: 'navy',
    headlineVariant: 'v1',
    heroLayout: isSaas ? 'compare' : 'feature',
    showCaptions: true,
    accent: 'orange',
    displayFont: 'intertight',
    density: 'cozy',
    radius: 'soft',
    showGrid: true,
    motion: true,
  };

  /* ─── Option tables ───────────────────────────────────────── */

  const PALETTES = [
    { id: 'navy',  label: 'Navy',  swatch: ['#0B1B33', '#F97316', '#3B82F6'] },
    { id: 'dark',  label: 'Dark',  swatch: ['#060D1A', '#F97316', '#60A5FA'] },
    { id: 'cream', label: 'Cream', swatch: ['#FAF6EC', '#0E1C36', '#D9612C'] },
  ];

  const ACCENTS = [
    { id: 'orange',   label: 'Orange',   c: '#F97316', c2: '#FB923C' },
    { id: 'electric', label: 'Electric', c: '#3B82F6', c2: '#60A5FA' },
    { id: 'magenta',  label: 'Magenta',  c: '#EC4899', c2: '#F472B6' },
    { id: 'emerald',  label: 'Emerald',  c: '#10B981', c2: '#34D399' },
    { id: 'violet',   label: 'Violet',   c: '#8B5CF6', c2: '#A78BFA' },
  ];

  const FONTS = [
    { id: 'intertight', label: 'Inter Tight', stack: '"Inter Tight", "Inter", system-ui, sans-serif' },
    { id: 'spacegrotesk', label: 'Space Grotesk', stack: '"Space Grotesk", system-ui, sans-serif' },
    { id: 'fraunces',   label: 'Fraunces',    stack: '"Fraunces", Georgia, serif' },
    { id: 'instrument', label: 'Instrument',  stack: '"Instrument Serif", Georgia, serif' },
    { id: 'dmserif',    label: 'DM Serif',    stack: '"DM Serif Display", Georgia, serif' },
  ];

  const DENSITIES = [
    { id: 'compact', label: 'Compact' },
    { id: 'cozy',    label: 'Cozy' },
    { id: 'roomy',   label: 'Roomy' },
  ];

  const RADII = [
    { id: 'sharp', label: 'Sharp' },
    { id: 'soft',  label: 'Soft' },
    { id: 'round', label: 'Round' },
  ];

  const HEADLINES_AGENCY = [
    { id: 'v1', label: 'Outcome' },
    { id: 'v2', label: 'Provocation' },
    { id: 'v3', label: 'Category' },
  ];
  const HEADLINES_SAAS = [
    { id: 'v1', label: 'Transform' },
    { id: 'v2', label: 'Stat' },
    { id: 'v3', label: 'Provocation' },
  ];

  const HEROS_AGENCY = [
    { id: 'feature', label: 'Feature' },
    { id: 'stack',   label: 'Stack' },
    { id: 'fan',     label: 'Fan' },
  ];
  const HEROS_SAAS = [
    { id: 'compare',   label: 'Compare' },
    { id: 'spotlight', label: 'Spotlight' },
    { id: 'pipeline',  label: 'Pipeline' },
  ];

  const HEADLINES = isSaas ? HEADLINES_SAAS : HEADLINES_AGENCY;
  const HEROS = isSaas ? HEROS_SAAS : HEROS_AGENCY;

  /* ─── Font lazy-loading ───────────────────────────────────── */

  function ensureFontStylesheet() {
    if (document.getElementById('twk-fonts')) return;
    const link = document.createElement('link');
    link.id = 'twk-fonts';
    link.rel = 'stylesheet';
    link.href = 'https://fonts.googleapis.com/css2?' +
      'family=Fraunces:opsz,wght@9..144,500;9..144,600;9..144,700' +
      '&family=Space+Grotesk:wght@500;600;700' +
      '&family=Instrument+Serif:ital@0;1' +
      '&family=DM+Serif+Display:ital@0;1' +
      '&display=swap';
    document.head.appendChild(link);
  }

  /* ─── Apply ───────────────────────────────────────────────── */

  function applyTweaks(t) {
    const body = document.body;

    // palette → body class
    body.classList.remove('theme-navy', 'theme-dark', 'theme-cream');
    body.classList.add('theme-' + (t.palette || 'navy'));

    // accent → inline CSS vars + data attr
    const accent = ACCENTS.find((a) => a.id === t.accent) || ACCENTS[0];
    if (t.accent && t.accent !== 'orange') {
      body.style.setProperty('--orange', accent.c);
      body.style.setProperty('--orange-2', accent.c2);
      body.style.setProperty('--brand-mark-bg', accent.c);
      body.setAttribute('data-accent', accent.id);
    } else {
      body.style.removeProperty('--orange');
      body.style.removeProperty('--orange-2');
      body.style.removeProperty('--brand-mark-bg');
      body.removeAttribute('data-accent');
    }

    // display font → CSS var + data attr (load stylesheet on first non-default)
    const font = FONTS.find((f) => f.id === t.displayFont) || FONTS[0];
    if (font.id !== 'intertight') {
      ensureFontStylesheet();
      body.style.setProperty('--f-display', font.stack);
      body.setAttribute('data-font', font.id);
    } else {
      body.style.removeProperty('--f-display');
      body.removeAttribute('data-font');
    }

    // density → body class
    body.classList.remove('density-compact', 'density-cozy', 'density-roomy');
    if (t.density && t.density !== 'cozy') {
      body.classList.add('density-' + t.density);
    }

    // corners → body class
    body.classList.remove('radius-sharp', 'radius-soft', 'radius-round');
    if (t.radius && t.radius !== 'soft') {
      body.classList.add('radius-' + t.radius);
    }

    // background grid → body class
    body.classList.toggle('no-grid', !t.showGrid);

    // motion → body class
    body.classList.toggle('no-motion', !t.motion);

    // Hero-specific (existing behaviour)
    if (isSaas) {
      const headlines = document.querySelectorAll('.hero-saas__h');
      headlines.forEach((h) => {
        h.hidden = h.getAttribute('data-variant') !== t.headlineVariant;
      });
      const layouts = document.querySelectorAll('.hero-layout');
      let valid = false;
      layouts.forEach((l) => {
        const match = l.getAttribute('data-layout') === t.heroLayout;
        l.hidden = !match;
        if (match) valid = true;
      });
      if (!valid && layouts.length) {
        layouts.forEach((l, i) => { l.hidden = i !== 0; });
      }
    } else {
      document.querySelectorAll('.hero__h').forEach((h) => {
        const v = h.getAttribute('data-variant');
        h.hidden = v !== t.headlineVariant;
      });
      const stage = document.getElementById('hero-stage');
      if (stage) stage.setAttribute('data-layout', t.heroLayout || 'feature');
    }

    body.setAttribute('data-headline', t.headlineVariant);
    body.setAttribute('data-hero', t.heroLayout || (isSaas ? 'compare' : 'feature'));
    body.classList.toggle('no-captions', !t.showCaptions);
  }

  /* ─── UI ──────────────────────────────────────────────────── */

  function boot() {
    const { useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakSelect } = window;
    if (!useTweaks || !TweaksPanel) return setTimeout(boot, 30);

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

      React.useEffect(() => { applyTweaks(t); }, [
        t.palette, t.headlineVariant, t.heroLayout, t.showCaptions,
        t.accent, t.displayFont, t.density, t.radius, t.showGrid, t.motion,
      ]);

      const reset = () => {
        Object.keys(TWEAK_DEFAULTS).forEach((k) => setTweak(k, TWEAK_DEFAULTS[k]));
      };

      /* — Palette swatch picker — */
      const PaletteSwatches = () => (
        <div className="twk-row">
          <div className="twk-lbl"><span>Palette</span><span className="twk-val">{t.palette}</span></div>
          <div style={{ display: 'flex', gap: 6 }}>
            {PALETTES.map((p) => {
              const active = t.palette === p.id;
              return (
                <button
                  key={p.id}
                  onClick={() => setTweak('palette', p.id)}
                  style={{
                    appearance: 'none',
                    border: active ? '2px solid #29261b' : '1px solid rgba(0,0,0,0.12)',
                    background: 'transparent',
                    padding: 5,
                    borderRadius: 8,
                    cursor: 'pointer',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: 4,
                    flex: 1,
                  }}
                  title={p.label}
                >
                  <span style={{ display: 'flex', borderRadius: 4, overflow: 'hidden', boxShadow: '0 1px 2px rgba(0,0,0,0.18)' }}>
                    {p.swatch.map((c, i) => (
                      <span key={i} style={{ width: 16, height: 24, background: c }} />
                    ))}
                  </span>
                  <span style={{ fontSize: 10, fontWeight: 500, color: 'rgba(41,38,27,0.75)' }}>{p.label}</span>
                </button>
              );
            })}
          </div>
        </div>
      );

      /* — Accent color dots — */
      const AccentSwatches = () => (
        <div className="twk-row">
          <div className="twk-lbl"><span>Accent</span><span className="twk-val">{t.accent}</span></div>
          <div style={{ display: 'flex', gap: 8 }}>
            {ACCENTS.map((a) => {
              const active = t.accent === a.id;
              return (
                <button
                  key={a.id}
                  onClick={() => setTweak('accent', a.id)}
                  aria-label={a.label}
                  title={a.label}
                  style={{
                    appearance: 'none',
                    padding: 0,
                    width: 30,
                    height: 30,
                    borderRadius: '50%',
                    background: `linear-gradient(135deg, ${a.c}, ${a.c2})`,
                    border: active ? '2px solid #29261b' : '2px solid rgba(0,0,0,0.12)',
                    boxShadow: active ? '0 0 0 2px #fff inset' : 'none',
                    cursor: 'pointer',
                    flex: 1,
                  }}
                />
              );
            })}
          </div>
        </div>
      );

      /* — Reset button — */
      const ResetRow = () => (
        <div className="twk-row" style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button
            onClick={reset}
            style={{
              appearance: 'none',
              border: '1px solid rgba(0,0,0,0.18)',
              background: 'transparent',
              padding: '5px 10px',
              borderRadius: 6,
              fontSize: 11,
              fontWeight: 500,
              letterSpacing: '0.02em',
              textTransform: 'uppercase',
              cursor: 'pointer',
              color: 'rgba(41,38,27,0.7)',
            }}
          >
            Reset all
          </button>
        </div>
      );

      return (
        <TweaksPanel title="Tweaks">
          <TweakSection label="Theme" />
          <PaletteSwatches />
          <AccentSwatches />
          <TweakSelect
            label="Display font"
            value={t.displayFont}
            options={FONTS.map((f) => ({ value: f.id, label: f.label }))}
            onChange={(v) => setTweak('displayFont', v)}
          />

          <TweakSection label="Layout" />
          <TweakRadio
            label="Density"
            value={t.density}
            options={DENSITIES.map((d) => ({ value: d.id, label: d.label }))}
            onChange={(v) => setTweak('density', v)}
          />
          <TweakRadio
            label="Corners"
            value={t.radius}
            options={RADII.map((r) => ({ value: r.id, label: r.label }))}
            onChange={(v) => setTweak('radius', v)}
          />

          <TweakSection label="Hero" />
          <TweakRadio
            label="Headline"
            value={t.headlineVariant}
            options={HEADLINES.map((h) => ({ value: h.id, label: h.label }))}
            onChange={(v) => setTweak('headlineVariant', v)}
          />
          <TweakRadio
            label="Hero layout"
            value={t.heroLayout}
            options={HEROS.map((h) => ({ value: h.id, label: h.label }))}
            onChange={(v) => setTweak('heroLayout', v)}
          />

          <TweakSection label="Detail" />
          <TweakToggle
            label="Hover captions"
            value={!!t.showCaptions}
            onChange={(v) => setTweak('showCaptions', v)}
          />
          <TweakToggle
            label="Background grid"
            value={!!t.showGrid}
            onChange={(v) => setTweak('showGrid', v)}
          />
          <TweakToggle
            label="Motion / animation"
            value={!!t.motion}
            onChange={(v) => setTweak('motion', v)}
          />

          <ResetRow />
        </TweaksPanel>
      );
    }

    const root = document.getElementById('tweaks-root');
    if (root && ReactDOM && ReactDOM.createRoot) {
      ReactDOM.createRoot(root).render(<App />);
    }
  }

  applyTweaks(TWEAK_DEFAULTS);
  boot();
})();
