// tweaks-app.jsx
// Mounts the Tweaks panel for Atrium Private Office.
// Applies tweak values to the DOM via CSS variables + targeted text rewrites.

const { useEffect } = React;

function applyTweaks(t) {
  const root = document.documentElement;

  // Accent (brass)
  if (t.accent) {
    root.style.setProperty('--brass', t.accent);
    // Derive matching variants
    root.style.setProperty('--brass-dim', t.accent + '8c');   // ~55% via hex alpha
    root.style.setProperty('--brass-soft', t.accent + '24');  // ~14%
  }

  // Fonts — swap the CSS variables, page reflows
  if (t.displayFont) root.style.setProperty('--serif', `"${t.displayFont}", Georgia, serif`);
  if (t.bodyFont)    root.style.setProperty('--sans',  `"${t.bodyFont}", -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif`);

  // Hero video — swap the <source> + reload
  const heroVid = document.querySelector('.hero-video');
  if (heroVid && t.heroVideo) {
    const wanted = `agents/${t.heroVideo}`;
    const src = heroVid.querySelector('source');
    if (src && !src.src.endsWith(wanted)) {
      src.src = wanted;
      heroVid.load();
      heroVid.play().catch(() => {});
    }
  }

  // Hero opacity
  if (heroVid && typeof t.heroOpacity === 'number') {
    heroVid.style.opacity = String(t.heroOpacity / 100);
  }

  // Brand name + mark
  document.querySelectorAll('[data-tk="brand-name"]').forEach(el => {
    el.innerHTML = renderBrandName(t.brand || 'Atrium Private Office');
  });
  document.querySelectorAll('[data-tk="brand-name-flat"]').forEach(el => {
    el.textContent = t.brand || 'Atrium Private Office';
  });
  document.querySelectorAll('[data-tk="brand-mark"]').forEach(el => {
    el.textContent = (t.brandMark || 'A').slice(0, 1);
  });

  // Hero headline (multi-line, last line in brass)
  const h1 = document.querySelector('[data-tk="hero-headline"]');
  if (h1 && t.heroHeadline) {
    const lines = String(t.heroHeadline).split('\n').filter(Boolean);
    h1.innerHTML = lines.map((line, i) =>
      i === lines.length - 1
        ? `<em>${escapeHtml(line)}</em>`
        : `${escapeHtml(line)}<br/>`
    ).join('');
  }

  // CTA text
  document.querySelectorAll('[data-tk="cta-text"]').forEach(el => {
    el.firstChild.textContent = (t.ctaText || 'Enter the Wealth Room') + ' ';
  });
}

function renderBrandName(name) {
  // Split into "First" + rest, where rest is rendered dim (matches the original markup)
  const parts = String(name).split(' ');
  if (parts.length < 2) return escapeHtml(name);
  const first = parts[0];
  const rest  = parts.slice(1).join(' ');
  return `${escapeHtml(first)} <span>${escapeHtml(rest)}</span>`;
}

function escapeHtml(s) {
  return String(s).replace(/[&<>"']/g, m => ({
    '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
  }[m]));
}

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

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

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Brand" />
      <TweakText
        label="Brand name"
        value={t.brand}
        onChange={v => setTweak('brand', v)}
      />
      <TweakText
        label="Mark"
        value={t.brandMark}
        onChange={v => setTweak('brandMark', v)}
      />

      <TweakSection label="Hero" />
      <TweakText
        label="Headline"
        value={t.heroHeadline}
        multiline
        rows={3}
        onChange={v => setTweak('heroHeadline', v)}
      />
      <TweakSelect
        label="Background video"
        value={t.heroVideo}
        options={[
          { value: 'hero.mp4',           label: 'Dusk skyline' },
          { value: 'hero-office.mp4',    label: 'Office interior' },
          { value: 'hero-office-2.mp4',  label: 'Office interior · 2' },
        ]}
        onChange={v => setTweak('heroVideo', v)}
      />
      <TweakSlider
        label="Video opacity"
        value={t.heroOpacity}
        min={20} max={100} step={5} unit="%"
        onChange={v => setTweak('heroOpacity', v)}
      />

      <TweakSection label="Type" />
      <TweakSelect
        label="Display serif"
        value={t.displayFont}
        options={['Source Serif 4', 'Newsreader', 'Spectral']}
        onChange={v => setTweak('displayFont', v)}
      />
      <TweakSelect
        label="Body sans"
        value={t.bodyFont}
        options={['Geist', 'DM Sans', 'Manrope']}
        onChange={v => setTweak('bodyFont', v)}
      />

      <TweakSection label="Color" />
      <TweakColor
        label="Brass accent"
        value={t.accent}
        options={['#C9A24E', '#B8860B', '#A88A4E', '#8C7A5B', '#9E8E6B']}
        onChange={v => setTweak('accent', v)}
      />

      <TweakSection label="Calls to action" />
      <TweakText
        label="Final CTA"
        value={t.ctaText}
        onChange={v => setTweak('ctaText', v)}
      />
    </TweaksPanel>
  );
}

ReactDOM.createRoot(document.getElementById('tweaks-root')).render(<TweaksApp />);
