// Tweaks app for Methora index.html — a React island that mounts only the
// TweaksPanel and applies its values back to the static page via CSS variables,
// DOM classes, and a few targeted overrides.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showLogoStrip": false,
  "showParticles": true,
  "showMarquee": true,
  "customCursor": true,
  "headlineMode": "agents",
  "accentColor": "#C8261B",
  "bgColor": "#EFE6D2"
}/*EDITMODE-END*/;

const HEADLINES = {
  agents:   { a: "Your Agents.",      b: "Your Hardware." },
  private:  { a: "Private by",        b: "Architecture." },
  realtime: { a: "Real Time,",        b: "On Your Metal." },
  web3:     { a: "Web3 Security,",    b: "Continuously." },
};

function hexToRgb(hex){
  const m = /^#([0-9a-f]{6})$/i.exec(hex);
  if (!m) return {r:200,g:38,b:27};
  const n = parseInt(m[1],16);
  return { r:(n>>16)&255, g:(n>>8)&255, b:n&255 };
}

function applyTweaks(t){
  const root = document.documentElement;
  // accent color
  root.style.setProperty('--red', t.accentColor);
  const {r,g,b} = hexToRgb(t.accentColor);
  root.style.setProperty('--red-soft', `rgba(${r},${g},${b},0.16)`);

  // bg color (cream variants)
  root.style.setProperty('--cream', t.bgColor);
  // re-derive a sand band from the same hue, slightly darker
  const sandHex = mix(t.bgColor, '#9F8E63', 0.18);
  root.style.setProperty('--sand', sandHex);

  // particles
  const canvas = document.getElementById('particles');
  if (canvas) canvas.style.display = t.showParticles ? '' : 'none';

  // marquee
  const marquee = document.querySelector('.marquee');
  if (marquee) marquee.style.display = t.showMarquee ? '' : 'none';

  // logo strip
  const strip = document.querySelector('.logo-strip');
  if (strip) strip.style.display = t.showLogoStrip ? '' : 'none';

  // custom cursor
  const cdot = document.getElementById('cdot');
  const cring = document.getElementById('cring');
  if (cdot && cring){
    const hide = !t.customCursor;
    cdot.style.display = hide ? 'none' : '';
    cring.style.display = hide ? 'none' : '';
    document.body.style.cursor = hide ? 'auto' : 'none';
  }

  // headline copy — rewrite the two .line spans and replay the letter stagger
  const h1 = document.getElementById('heroHeadline');
  if (h1){
    const lines = h1.querySelectorAll('.line');
    const hd = HEADLINES[t.headlineMode] || HEADLINES.agents;
    if (lines[0] && lines[0].dataset.line !== hd.a){
      lines[0].dataset.line = hd.a;
      lines[1].dataset.line = hd.b;
      // rebuild letters (without animation, since this is a runtime swap)
      [lines[0], lines[1]].forEach((line) => {
        line.textContent = '';
        const text = line.dataset.line;
        text.split(' ').forEach((word, wIdx, arr) => {
          const wEl = document.createElement('span');
          wEl.className = 'word';
          word.split('').forEach((ch) => {
            const s = document.createElement('span');
            s.className = 'letter';
            s.textContent = ch;
            s.style.opacity = '1';
            s.style.transform = 'translateY(0)';
            wEl.appendChild(s);
          });
          line.appendChild(wEl);
          if (wIdx < arr.length - 1) line.appendChild(document.createTextNode(' '));
        });
      });
    }
  }
}

// Hex mix: a toward b by t
function mix(a, b, t){
  const A = hexToRgb(a), B = hexToRgb(b);
  const r = Math.round(A.r*(1-t)+B.r*t);
  const g = Math.round(A.g*(1-t)+B.g*t);
  const bl= Math.round(A.b*(1-t)+B.b*t);
  return '#' + [r,g,bl].map(n=>n.toString(16).padStart(2,'0')).join('');
}

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

  React.useEffect(() => { applyTweaks(t); }, [t]);

  return (
    <TweaksPanel>
      <TweakSection label="Content" />
      <TweakToggle label="Client logo strip" value={t.showLogoStrip}
                   onChange={(v) => setTweak('showLogoStrip', v)} />
      <TweakToggle label="Marquee strip" value={t.showMarquee}
                   onChange={(v) => setTweak('showMarquee', v)} />
      <TweakSelect label="Headline" value={t.headlineMode}
                   options={[
                     {value:'agents',  label:'Your Agents. / Your Hardware.'},
                     {value:'private', label:'Private by / Architecture.'},
                     {value:'realtime',label:'Real Time, / On Your Metal.'},
                     {value:'web3',    label:'Web3 Security, / Continuously.'},
                   ]}
                   onChange={(v) => setTweak('headlineMode', v)} />

      <TweakSection label="Motion" />
      <TweakToggle label="Particle field" value={t.showParticles}
                   onChange={(v) => setTweak('showParticles', v)} />
      <TweakToggle label="Custom cursor" value={t.customCursor}
                   onChange={(v) => setTweak('customCursor', v)} />

      <TweakSection label="Palette" />
      <TweakColor label="Accent" value={t.accentColor}
                  options={['#C8261B','#D9541E','#A41B7C','#1F6B5C','#1E3A8A']}
                  onChange={(v) => setTweak('accentColor', v)} />
      <TweakColor label="Background" value={t.bgColor}
                  options={['#EFE6D2','#F4ECDA','#E7DCC2','#E9E4D6','#F2EEE6']}
                  onChange={(v) => setTweak('bgColor', v)} />
    </TweaksPanel>
  );
}

(function mount(){
  const node = document.createElement('div');
  node.id = 'tweaks-root';
  document.body.appendChild(node);
  ReactDOM.createRoot(node).render(<TweaksApp />);
})();
