// LeadFormModal — opens from any CTA. Posts to /api/telegram-proxy (Cloudflare Pages Function).
// Mirrors the field set used by Aceverse: name, company, phone, email.
// Bonus: direct LinkedIn fallback link.

const LeadFormCtx = React.createContext({ open: () => {}, close: () => {} });
const useLeadForm = () => React.useContext(LeadFormCtx);

const LINKEDIN_FALLBACK = 'https://www.linkedin.com/in/roman-poliashenko/';

const LeadFormModal = ({ onClose }) => {
  const [submitting, setSubmitting] = React.useState(false);
  const [status, setStatus] = React.useState(null); // null | 'ok' | 'err'
  const [errMsg, setErrMsg] = React.useState('');
  const formRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  const submit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setStatus(null);
    const form = e.currentTarget;
    const payload = {
      name:    form.elements.user_name.value.trim(),
      company: form.elements.company_name.value.trim(),
      phone:   form.elements.user_phone.value.trim(),
      email:   form.elements.user_email.value.trim(),
      page:    window.location.href,
      source:  'inclamo-landing',
    };

    // Local dev: skip POST, show a clear note.
    const host = window.location.hostname;
    if (host === 'localhost' || host === '127.0.0.1') {
      console.log('[LeadForm] Local dev — would POST:', payload);
      setStatus('ok');
      setErrMsg('Submitted locally (dev mode — no notification sent).');
      setSubmitting(false);
      return;
    }

    try {
      const resp = await fetch('/api/telegram-proxy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!resp.ok) {
        const txt = await resp.text();
        throw new Error(`${resp.status}: ${txt.slice(0, 120)}`);
      }
      setStatus('ok');
      form.reset();
      setTimeout(onClose, 1800);
    } catch (err) {
      setStatus('err');
      setErrMsg(err.message || 'Network error');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="lf-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="lf-card" role="dialog" aria-modal="true" aria-labelledby="lf-title">
        <button className="lf-close" onClick={onClose} aria-label="Close">×</button>
        <h2 id="lf-title" className="lf-title">Talk to Inclamo</h2>
        <p className="lf-sub">
          Leave your contacts and we'll reach out within one business day. Or message us on LinkedIn.
        </p>

        <form className="lf-form" ref={formRef} onSubmit={submit}>
          <input className="lf-input" type="text"  id="user_name"    name="user_name"    placeholder="Your name *"          required autoComplete="name" />
          <input className="lf-input" type="text"  id="company_name" name="company_name" placeholder="Company (optional)"   autoComplete="organization" />
          <input className="lf-input" type="tel"   id="user_phone"   name="user_phone"   placeholder="Phone *"              required autoComplete="tel" />
          <input className="lf-input" type="email" id="user_email"   name="user_email"   placeholder="Email (optional)"     autoComplete="email" />
          <button type="submit" className="lf-submit" disabled={submitting}>
            {submitting ? 'Sending…' : 'Send request'}
          </button>
        </form>

        {status === 'ok' && (
          <div className="lf-status ok">Got it — we'll be in touch shortly.{errMsg ? ` ${errMsg}` : ''}</div>
        )}
        {status === 'err' && (
          <div className="lf-status err">Couldn't send: {errMsg}. Try LinkedIn below.</div>
        )}

        <div className="lf-divider"><span>or</span></div>

        <a className="lf-li" href={LINKEDIN_FALLBACK} target="_blank" rel="noopener noreferrer">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
            <path d="M20.45 20.45h-3.55v-5.57c0-1.33-.03-3.04-1.86-3.04-1.86 0-2.14 1.45-2.14 2.95v5.66h-3.55V9h3.41v1.56h.05c.48-.9 1.64-1.86 3.38-1.86 3.61 0 4.27 2.38 4.27 5.47v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.78C.8 0 0 .77 0 1.73v20.54C0 23.23.8 24 1.78 24h20.44c.98 0 1.78-.77 1.78-1.73V1.73C24 .77 23.2 0 22.22 0z"/>
          </svg>
          Message on LinkedIn
        </a>
      </div>
    </div>
  );
};

const LeadFormProvider = ({ children }) => {
  const [open, setOpen] = React.useState(false);
  const ctx = React.useMemo(() => ({
    open: () => setOpen(true),
    close: () => setOpen(false),
  }), []);
  // Expose globally so non-React handlers (or anchor onClick) can open the modal.
  React.useEffect(() => {
    window.openLeadForm = ctx.open;
    window.closeLeadForm = ctx.close;
  }, [ctx]);
  return (
    <LeadFormCtx.Provider value={ctx}>
      {children}
      {open && <LeadFormModal onClose={ctx.close} />}
    </LeadFormCtx.Provider>
  );
};

window.LeadFormProvider = LeadFormProvider;
window.useLeadForm = useLeadForm;
