// Shared "Get a free audit" modal — the ONE form behind every "Get a free audit" button site-wide.
// Fields: Full name, Work email, Phone (country dial-code picker + geolocation prefill), Website.

// Autodetect visitor country once on load to pre-fill the dial code (graceful fallback to US).
(function () {
  if (window.__origoGeoInit) return;
  window.__origoGeoInit = true;
  fetch('https://ipapi.co/json/').then(r => r.ok ? r.json() : null).then(g => {
    if (!g || !window.ORIGO_COUNTRIES) return;
    let idx = window.ORIGO_COUNTRIES.findIndex(c => c.n === g.country_name);
    if (idx < 0 && g.country_calling_code) idx = window.ORIGO_COUNTRIES.findIndex(c => c.d === g.country_calling_code);
    if (idx >= 0) window.__origoGeoIdx = idx;
  }).catch(() => {});
})();

function useModalA11y(onClose) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const root = ref.current; if (!root) return;
    const prev = document.activeElement;
    const sel = 'a[href],button:not([disabled]),input,textarea,select,[tabindex]:not([tabindex="-1"])';
    const items = () => [...root.querySelectorAll(sel)].filter(el => el.offsetParent !== null);
    (items()[0] || root).focus();
    const onKey = e => {
      if (e.key === 'Escape') { e.stopPropagation(); onClose(); return; }
      if (e.key !== 'Tab') return;
      const f = items(); if (!f.length) return;
      const first = f[0], last = f[f.length - 1];
      if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
      else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
    };
    document.addEventListener('keydown', onKey, true);
    return () => { document.removeEventListener('keydown', onKey, true); if (prev && prev.focus) prev.focus(); };
  }, []);
  return ref;
}

function AuditModal({ onClose }) {
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const ref = useModalA11y(onClose);
  const countries = window.ORIGO_COUNTRIES || [{ n: 'United States', d: '+1' }];
  const [ci, setCi] = React.useState(typeof window.__origoGeoIdx === 'number' ? window.__origoGeoIdx : Math.max(0, countries.findIndex(c => c.n === 'United States')));
  const nameR = React.useRef(null), emailR = React.useRef(null), companyR = React.useRef(null), phoneR = React.useRef(null), siteR = React.useRef(null);
  const submit = async () => {
    if (busy) return;
    setErr('');
    const phoneNum = ((phoneR.current && phoneR.current.value) || '').trim();
    const payload = {
      name: ((nameR.current && nameR.current.value) || '').trim(),
      email: ((emailR.current && emailR.current.value) || '').trim(),
      company: ((companyR.current && companyR.current.value) || '').trim(),
      phone: phoneNum ? (((countries[ci] && countries[ci].d) || '') + ' ' + phoneNum) : '',
      website: ((siteR.current && siteR.current.value) || '').trim(),
    };
    if (!payload.name || !payload.company || !payload.email || !payload.website) { setErr('Please fill in all required fields.'); return; }
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(payload.email)) { setErr('Please enter a valid work email.'); return; }
    setBusy(true);
    try {
      const r = await fetch('/api/audit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
      if (!r.ok) throw new Error('failed');
      setSent(true);
    } catch (e) {
      setErr('Something went wrong. Please email admin@origolabs.ai directly.');
    } finally { setBusy(false); }
  };
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" ref={ref} tabIndex={-1} style={{ position: 'relative' }} role="dialog" aria-modal="true" aria-label="Get a free audit" onClick={e => e.stopPropagation()}>
        <button className="modal-x" onClick={onClose} aria-label="Close">×</button>
        {!sent ? (
          <React.Fragment>
            <h3>Get a free audit</h3>
            <p>Tell us where to send it. We will show you where you stand across engines.</p>
            <div className="field-row" style={{ '--d': '.06s' }}><label className="flbl">Full name<span className="req">*</span></label><input ref={nameR} className="field" placeholder="Jane Mercer" /></div>
            <div className="field-row" style={{ '--d': '.12s' }}><label className="flbl">Company<span className="req">*</span></label><input ref={companyR} className="field" placeholder="Acme Inc." /></div>
            <div className="field-row" style={{ '--d': '.18s' }}><label className="flbl">Work email<span className="req">*</span></label><input ref={emailR} type="email" className="field" placeholder="jane@company.com" /></div>
            <div className="field-row" style={{ '--d': '.24s' }}><label className="flbl">Phone<span className="opt">optional</span></label><div className="field field-pre"><select className="pre pre-sel" value={ci} onChange={e => setCi(+e.target.value)} aria-label="Country dial code">{countries.map((c, i) => <option key={c.n} value={i}>{c.d}  {c.n}</option>)}</select><input ref={phoneR} placeholder="555 0142" /></div></div>
            <div className="field-row" style={{ '--d': '.30s' }}><label className="flbl">Website<span className="req">*</span></label><div className="field field-pre"><span className="pre">https://</span><input ref={siteR} placeholder="yourbrand.com" /></div></div>
            {err && <p style={{ color: '#ff6b6b', fontSize: '13px', margin: '0 0 8px' }}>{err}</p>}
            <button className="btn btn-primary btn-md" style={{ width: '100%', marginTop: '4px', '--d': '.36s' }} onClick={submit} disabled={busy}>{busy ? 'Sending…' : 'Request free audit'}</button>
          </React.Fragment>
        ) : (
          <div className="modal-ok">
            <div className="check">Request received</div>
            <h3>We will be in touch.</h3>
            <p style={{ margin: '0 auto' }}>An engineer will reach out within one business day.</p>
            <button className="btn btn-ghost btn-md" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { useModalA11y, AuditModal });
