// 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 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')));
  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</label><input className="field" placeholder="Jane Mercer" /></div>
            <div className="field-row" style={{ '--d': '.12s' }}><label className="flbl">Work email</label><input className="field" placeholder="jane@company.com" /></div>
            <div className="field-row" style={{ '--d': '.18s' }}><label className="flbl">Phone</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 placeholder="555 0142" /></div></div>
            <div className="field-row" style={{ '--d': '.24s' }}><label className="flbl">Website</label><div className="field field-pre"><span className="pre">https://</span><input placeholder="yourbrand.com" /></div></div>
            <button className="btn btn-primary btn-md" style={{ width: '100%', marginTop: '4px', '--d': '.3s' }} onClick={() => setSent(true)}>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 });
