// site.jsx — wires up Calendly + Beehiiv + contact form + Tweaks
//
// Everything reads from window.SITE_CONFIG (defined in the head of the HTML).
// Calendly mounts only if a real URL is provided; otherwise we render a labeled
// placeholder so the page still looks intentional in dev.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#368FD3",
  "headline": "Where can AI actually pay off in your business?",
  "headlineEm": "actually",
  "showSecondaryCTA": true,
  "calendlyHeight": 720,
  "compactHero": false
}/*EDITMODE-END*/;

// ── Calendly ────────────────────────────────────────────────────────────────
function mountCalendly() {
  const cfg = window.SITE_CONFIG || {};
  const mount = document.getElementById('calendly-mount');
  if (!mount) return;

  const url = cfg.calendlyUrl || '';
  const isPlaceholder = !url || /your-handle|REPLACE/i.test(url);

  // Clear any previous render (re-mount on tweak change).
  mount.innerHTML = '';

  if (isPlaceholder) {
    const ph = document.createElement('div');
    ph.className = 'cal-placeholder';
    ph.innerHTML = `
      <div>
        <b>Calendly widget mounts here</b>
        Set <code style="font-family:var(--mono);color:var(--accent)">SITE_CONFIG.calendlyUrl</code><br/>
        in the &lt;head&gt; of this file to go live.
      </div>`;
    mount.appendChild(ph);
    return;
  }

  // Wait for the Calendly script to load.
  const tryInit = () => {
    if (window.Calendly && typeof window.Calendly.initInlineWidget === 'function') {
      window.Calendly.initInlineWidget({
        url: url + (url.includes('?') ? '&' : '?') +
             'hide_event_type_details=0&hide_gdpr_banner=1&background_color=faf9f7&text_color=29261b&primary_color=368FD3',
        parentElement: mount,
      });
    } else {
      setTimeout(tryInit, 120);
    }
  };
  tryInit();
}

// ── Beehiiv newsletter ──────────────────────────────────────────────────────
// Beehiiv embed forms are plain HTML POST forms. We submit via fetch with
// `mode: 'no-cors'` (we can't read the response cross-origin, but the POST
// still lands on Beehiiv's side and the subscriber gets the confirmation
// email). If the action URL hasn't been configured, we fail loud-but-soft.
function wireNewsletter() {
  const form = document.getElementById('newsletter-form');
  const input = document.getElementById('newsletter-email');
  const status = document.getElementById('newsletter-status');
  if (!form) return;

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const email = (input.value || '').trim();
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      status.textContent = '— please enter a valid email';
      return;
    }
    status.textContent = '— subscribing…';

    const action = (window.SITE_CONFIG || {}).beehiivFormAction || '';
    const isPlaceholder = !action || /REPLACE/i.test(action);

    if (isPlaceholder) {
      // Dev mode: fake-success so the UX is testable.
      await new Promise((r) => setTimeout(r, 600));
      status.textContent = '— subscribed (demo) · paste your beehiiv form action to go live';
      input.value = '';
      return;
    }

    try {
      const fd = new FormData();
      fd.append('email', email);
      // Beehiiv embed forms also accept a referring_site param; include for attribution.
      fd.append('referring_site', location.host);
      await fetch(action, { method: 'POST', body: fd, mode: 'no-cors' });
      status.textContent = '— check your inbox to confirm.';
      input.value = '';
    } catch (err) {
      status.textContent = '— something went wrong. try again or email gelo@thelogiclayer.org';
    }
  });
}

// ── Contact form ────────────────────────────────────────────────────────────
function wireContact() {
  const form = document.getElementById('contact-form');
  const status = document.getElementById('contact-status');
  if (!form) return;

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(form).entries());
    if (!data.name || !data.email || !data.message) {
      status.textContent = '— name, email, and message are required';
      return;
    }
    status.textContent = '— sending…';

    const endpoint = (window.SITE_CONFIG || {}).contactEndpoint || 'mailto:gelo@thelogiclayer.org';

    if (endpoint.startsWith('mailto:')) {
      // Fall back to opening the user's mail client with a prefilled body.
      const subject = encodeURIComponent(`New note from ${data.name}`);
      const body = encodeURIComponent(
        `Name: ${data.name}\nEmail: ${data.email}\nCompany: ${data.company || '—'}\nStage: ${data.stage || '—'}\n\n${data.message}`
      );
      window.location.href = `${endpoint}?subject=${subject}&body=${body}`;
      status.textContent = '— opening your mail app…';
      return;
    }

    try {
      await fetch(endpoint, {
        method: 'POST',
        headers: { 'Accept': 'application/json' },
        body: new FormData(form),
      });
      status.textContent = '— sent. I\'ll reply within 2 business days.';
      form.reset();
    } catch (err) {
      status.textContent = '— couldn\'t send. email gelo@thelogiclayer.org directly.';
    }
  });
}

// ── Tweaks app ──────────────────────────────────────────────────────────────
function TweaksApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweak values to the live page.
  React.useEffect(() => {
    document.documentElement.style.setProperty('--accent', t.accent);
  }, [t.accent]);

  React.useEffect(() => {
    const h1 = document.querySelector('.headline');
    if (!h1) return;
    const text = t.headline || '';
    const em = (t.headlineEm || '').trim();
    if (em && text.toLowerCase().includes(em.toLowerCase())) {
      const i = text.toLowerCase().indexOf(em.toLowerCase());
      const before = text.slice(0, i);
      const match = text.slice(i, i + em.length);
      const after = text.slice(i + em.length);
      h1.innerHTML = `${before}<em>${match}</em>${after}`;
    } else {
      h1.textContent = text;
    }
  }, [t.headline, t.headlineEm]);

  React.useEffect(() => {
    const nl = document.getElementById('newsletter-form');
    if (nl) nl.style.display = t.showSecondaryCTA ? '' : 'none';
  }, [t.showSecondaryCTA]);

  React.useEffect(() => {
    const cal = document.getElementById('calendly-mount');
    if (cal) cal.style.height = `${t.calendlyHeight}px`;
  }, [t.calendlyHeight]);

  React.useEffect(() => {
    const hero = document.querySelector('.hero');
    if (hero) hero.style.paddingBottom = t.compactHero ? '40px' : '88px';
  }, [t.compactHero]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Brand" />
      <TweakColor label="Accent" value={t.accent}
                  onChange={(v) => setTweak('accent', v)} />

      <TweakSection label="Headline" />
      <TweakText label="Text" value={t.headline}
                 onChange={(v) => setTweak('headline', v)} />
      <TweakText label="Italicize word" value={t.headlineEm}
                 placeholder="e.g. under"
                 onChange={(v) => setTweak('headlineEm', v)} />
      <TweakToggle label="Compact hero" value={t.compactHero}
                   onChange={(v) => setTweak('compactHero', v)} />

      <TweakSection label="CTAs" />
      <TweakToggle label="Show newsletter" value={t.showSecondaryCTA}
                   onChange={(v) => setTweak('showSecondaryCTA', v)} />
      <TweakSlider label="Calendly height" value={t.calendlyHeight}
                   min={520} max={960} step={20} unit="px"
                   onChange={(v) => setTweak('calendlyHeight', v)} />
    </TweaksPanel>
  );
}

// ── Boot ────────────────────────────────────────────────────────────────────
mountCalendly();
wireNewsletter();
wireContact();

const root = document.createElement('div');
root.id = '__tweaks_root';
document.body.appendChild(root);
ReactDOM.createRoot(root).render(<TweaksApp />);
