/* CareNav site — Contact / call-back request modal form.
   Opens from any CTA via window.openContactForm(audience).
   Submission is local-only (no backend) — logs payload + shows success state. */

window.SiteContactForm = function SiteContactForm() {
  const [open, setOpen] = React.useState(false);
  const [audience, setAudience] = React.useState('patients');
  const [submitted, setSubmitted] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', surname: '', cell: '', email: '', consent: false });
  const [errors, setErrors] = React.useState({});
  const firstFieldRef = React.useRef(null);

  // Expose opener globally
  React.useEffect(() => {
    window.openContactForm = (aud) => {
      setAudience(aud || 'patients');
      setSubmitted(false);
      setForm({ name: '', surname: '', cell: '', email: '', consent: false });
      setErrors({});
      setOpen(true);
    };
    return () => { delete window.openContactForm; };
  }, []);

  // Lock body scroll while open + focus first field + Esc to close
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const t = setTimeout(() => firstFieldRef.current && firstFieldRef.current.focus(), 80);
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      clearTimeout(t);
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  if (!open) return null;

  const titles = {
    patients: { eyebrow: 'Request a call-back', h: 'We\'ll be in touch.', sub: 'Share your details and a CareNav navigator from a participating provider will reach out within one business day.' },
    clinicians: { eyebrow: 'Refer a patient', h: 'Tell us about your patient.', sub: 'A CareNav navigator will follow up to coordinate the referral. Submit details and we\'ll be in touch within one business day.' },
    hospitals: { eyebrow: 'Book a demo', h: 'Let\'s show you CareNav.', sub: 'A 30-minute walkthrough tailored to your service line. We\'ll be in touch within one business day.' },
    insurers: { eyebrow: 'Partner with us', h: 'Let\'s talk outcomes.', sub: 'Outcomes-aligned partnerships across SADC. We\'ll be in touch within one business day.' },
  };
  const t = titles[audience] || titles.patients;

  const set = (k) => (e) => {
    const val = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm(f => ({ ...f, [k]: val }));
    if (errors[k]) setErrors(er => ({ ...er, [k]: undefined }));
  };

  const validate = () => {
    const er = {};
    if (!form.name.trim()) er.name = 'Required';
    if (!form.surname.trim()) er.surname = 'Required';
    if (!form.cell.trim()) er.cell = 'Required';
    else if (!/^[0-9 +()-]{8,}$/.test(form.cell.trim())) er.cell = 'Enter a valid phone number';
    if (!form.email.trim()) er.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) er.email = 'Enter a valid email';
    if (!form.consent) er.consent = 'Please tick to consent';
    return er;
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const er = validate();
    setErrors(er);
    if (Object.keys(er).length) return;
    // Local-only submission — log payload. Wire to backend later.
    console.log('[CareNav contact form]', { audience, ...form, ts: new Date().toISOString() });
    setSubmitted(true);
  };

  // ----- styles -----
  const overlay = {
    position: 'fixed', inset: 0, zIndex: 100,
    background: 'rgba(11, 41, 33, 0.62)',
    backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 20, animation: 'cnFade 220ms ease-out',
  };
  const card = {
    background: 'var(--cn-cream-50)', borderRadius: 20,
    width: '100%', maxWidth: 540, maxHeight: '92vh', overflowY: 'auto',
    boxShadow: '0 30px 80px rgba(11,41,33,0.4)',
    position: 'relative',
    animation: 'cnRise 280ms cubic-bezier(0.2, 0.8, 0.2, 1)',
  };
  const labelStyle = { fontFamily: 'var(--cn-font-sans)', fontSize: 12, fontWeight: 600, color: 'var(--cn-ink-700)', letterSpacing: '0.02em', display: 'block', marginBottom: 6 };
  const fieldStyle = (hasErr) => ({
    width: '100%', padding: '12px 14px', borderRadius: 10,
    border: hasErr ? '1.5px solid var(--cn-coral-600)' : '1px solid var(--cn-ink-200)',
    background: 'white', fontFamily: 'var(--cn-font-sans)', fontSize: 15, color: 'var(--cn-ink-900)',
    boxSizing: 'border-box', outline: 'none',
    transition: 'border-color 160ms',
  });
  const errMsg = { fontFamily: 'var(--cn-font-sans)', fontSize: 11, color: 'var(--cn-coral-700)', marginTop: 4 };

  return (
    <div style={overlay} onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }} role="dialog" aria-modal="true">
      <style>{`
        @keyframes cnFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes cnRise { from { opacity: 0; transform: translateY(20px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
      `}</style>
      <div style={card}>
        {/* Close */}
        <button onClick={() => setOpen(false)} aria-label="Close" style={{
          position: 'absolute', top: 16, right: 16, width: 36, height: 36, borderRadius: 999,
          background: 'var(--cn-cream-100)', border: '1px solid var(--cn-ink-100)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--cn-ink-700)',
          fontSize: 18, lineHeight: 1,
        }}>×</button>

        <form onSubmit={(e) => e.preventDefault()} style={{ padding: '40px 36px 32px' }}>
          <div style={{ fontFamily: 'var(--cn-font-mono)', fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--cn-coral-700)', fontWeight: 600 }}>{t.eyebrow}</div>
          <h3 style={{ fontFamily: 'var(--cn-font-display)', fontSize: 32, fontWeight: 400, color: 'var(--cn-ink-900)', margin: '8px 0 10px', letterSpacing: '-0.02em' }}>{t.h}</h3>
          <p style={{ fontFamily: 'var(--cn-font-sans)', fontSize: 14, color: 'var(--cn-ink-600)', margin: '0 0 24px', lineHeight: 1.5 }}>{t.sub}</p>

          <fieldset disabled aria-hidden="true" style={{ border: 'none', padding: 0, margin: 0, opacity: 0.5, pointerEvents: 'none', filter: 'grayscale(0.4)' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <label style={labelStyle} htmlFor="cn-name">Name</label>
                <input id="cn-name" type="text" autoComplete="off" tabIndex={-1} style={fieldStyle(false)} />
              </div>
              <div>
                <label style={labelStyle} htmlFor="cn-surname">Surname</label>
                <input id="cn-surname" type="text" autoComplete="off" tabIndex={-1} style={fieldStyle(false)} />
              </div>
            </div>
            <div style={{ marginTop: 14 }}>
              <label style={labelStyle} htmlFor="cn-cell">Cellphone number</label>
              <input id="cn-cell" type="tel" autoComplete="off" tabIndex={-1} placeholder="e.g. +27 82 123 4567" style={fieldStyle(false)} />
            </div>
            <div style={{ marginTop: 14 }}>
              <label style={labelStyle} htmlFor="cn-email">Email address</label>
              <input id="cn-email" type="email" autoComplete="off" tabIndex={-1} placeholder="you@example.com" style={fieldStyle(false)} />
            </div>
            <label style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginTop: 22, padding: '14px 16px', background: 'var(--cn-cream-100)', borderRadius: 10, border: '1px solid transparent' }}>
              <input type="checkbox" tabIndex={-1} style={{ marginTop: 3, accentColor: 'var(--cn-forest-700)', width: 18, height: 18, flexShrink: 0 }} />
              <span style={{ fontFamily: 'var(--cn-font-sans)', fontSize: 13, color: 'var(--cn-ink-700)', lineHeight: 1.45 }}>
                I consent to being contacted by CareNav about my request, in line with POPIA.
              </span>
            </label>
          </fieldset>

          <div style={{
            marginTop: 26, padding: '20px 22px',
            background: 'var(--cn-forest-900)', color: 'var(--cn-cream-100)', borderRadius: 14,
            display: 'flex', gap: 16, alignItems: 'flex-start',
          }}>
            <div style={{ flexShrink: 0, width: 36, height: 36, borderRadius: 999, background: 'rgba(243,234,218,0.12)', display: 'grid', placeItems: 'center', marginTop: 2 }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--cn-coral-300)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4"/><circle cx="12" cy="16" r="0.5" fill="var(--cn-coral-300)"/></svg>
            </div>
            <div>
              <div style={{ fontFamily: 'var(--cn-font-mono)', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--cn-coral-300)', fontWeight: 700, marginBottom: 6 }}>Concept preview</div>
              <div style={{ fontFamily: 'var(--cn-font-display)', fontSize: 19, lineHeight: 1.3, color: 'var(--cn-cream-100)', letterSpacing: '-0.01em' }}>
                This is only an idea for now — but we can't wait to bring this to life for you.
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 22 }}>
            <button type="button" onClick={() => setOpen(false)} style={{
              background: 'var(--cn-forest-800)', color: 'var(--cn-cream-100)', border: 'none',
              padding: '13px 26px', borderRadius: 999, fontFamily: 'var(--cn-font-sans)',
              fontSize: 14, fontWeight: 600, cursor: 'pointer',
            }}>Close</button>
          </div>
        </form>
      </div>
    </div>
  );
};
