// RegisterForm.jsx — waitlist register modal + newsletter form.
// Publishes window.RegisterModal, window.openRegister, window.NewsletterForm.
// POSTs to the showcase API (same-origin in prod; base from <meta name="showcase-api-base">).

(function () {
  function apiBase() {
    const m = document.querySelector('meta[name="showcase-api-base"]');
    return (m && m.content) || '';
  }

  const listeners = new Set();
  window.openRegister = () => listeners.forEach((fn) => fn(true));
  function useRegister() {
    const [open, setOpen] = React.useState(false);
    React.useEffect(() => {
      const fn = (v) => setOpen(v);
      listeners.add(fn);
      return () => listeners.delete(fn);
    }, []);
    return [open, setOpen];
  }

  function Field({ label, children }) {
    return (
      <label className="block">
        <span className="block text-[11px] font-semibold uppercase tracking-wide text-zinc-500 mb-1">{label}</span>
        {children}
      </label>
    );
  }
  const inputCls =
    'w-full h-10 px-3 rounded-md border border-zinc-200 text-[13px] focus:outline-none focus:border-zinc-400';

  function RegisterModal() {
    const [open, setOpen] = useRegister();
    const [state, setState] = React.useState('form'); // form | sending | done | error
    const [number, setNumber] = React.useState('');
    const [errMsg, setErrMsg] = React.useState('');
    const [form, setForm] = React.useState({
      name: '', company: '', email: '', nif: '', city: '', phone: '',
      segment: '', current_erp: '', consent: false, hp: '',
    });
    if (!open) return null;
    const set = (k) => (e) => setForm({ ...form, [k]: e.target.type === 'checkbox' ? e.target.checked : e.target.value });

    async function submit(e) {
      e.preventDefault();
      setState('sending'); setErrMsg('');
      try {
        const res = await fetch(apiBase() + '/api/waitlist', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form),
        });
        if (res.status === 429) { setErrMsg('Demasiados pedidos. Tente novamente mais tarde.'); setState('error'); return; }
        if (!res.ok) { setErrMsg('Verifique os campos e o consentimento.'); setState('error'); return; }
        const data = await res.json();
        setNumber(data.number); setState('done');
      } catch (_) { setErrMsg('Falha de ligação. Tente novamente.'); setState('error'); }
    }

    return (
      <div className="fixed inset-0 z-[200] grid place-items-center p-4" style={{ background: 'rgba(0,0,0,0.5)' }}
           onClick={() => setOpen(false)}>
        <div className="w-full max-w-[520px] rounded-2xl bg-white p-6 sm:p-8 max-h-[90vh] overflow-auto"
             onClick={(e) => e.stopPropagation()}>
          {state === 'done' ? (
            <div className="text-center">
              <div className="text-[11px] uppercase tracking-wide text-zinc-500 font-semibold">Convite reservado</div>
              <h3 className="text-[22px] font-semibold tracking-tight mt-2">É o N.º {number}</h3>
              <p className="text-[13px] text-zinc-600 mt-3 leading-relaxed">
                Enviámos a sua carta de convite por email. Veja a caixa de entrada (e o spam, por garantia).
              </p>
              <button onClick={() => setOpen(false)}
                      className="mt-6 h-10 px-5 rounded-md text-white text-[13px] font-medium" style={{ background: '#18181B' }}>
                Fechar
              </button>
            </div>
          ) : (
            <form onSubmit={submit} className="space-y-3">
              <div className="flex items-center justify-between">
                <h3 className="text-[18px] font-semibold tracking-tight">Pedir convite para a beta</h3>
                <button type="button" onClick={() => setOpen(false)} className="text-zinc-400 text-[20px] leading-none">×</button>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <Field label="Nome*"><input required className={inputCls} value={form.name} onChange={set('name')} /></Field>
                <Field label="Empresa*"><input required className={inputCls} value={form.company} onChange={set('company')} /></Field>
              </div>
              <Field label="Email*"><input required type="email" className={inputCls} value={form.email} onChange={set('email')} /></Field>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <Field label="NIF / NIPC"><input className={inputCls} value={form.nif} onChange={set('nif')} /></Field>
                <Field label="Cidade"><input className={inputCls} value={form.city} onChange={set('city')} /></Field>
                <Field label="Telefone"><input className={inputCls} value={form.phone} onChange={set('phone')} /></Field>
                <Field label="ERP actual"><input className={inputCls} value={form.current_erp} onChange={set('current_erp')} /></Field>
              </div>
              <Field label="Tipo de empresa">
                <select className={inputCls} value={form.segment} onChange={set('segment')}>
                  <option value="">—</option>
                  <option value="distribuidor">Distribuidor</option>
                  <option value="retalhista">Retalhista</option>
                  <option value="fabricante">Fabricante</option>
                  <option value="empreiteiro">Empreiteiro</option>
                  <option value="outro">Outro</option>
                </select>
              </Field>
              <input tabIndex={-1} autoComplete="off" value={form.hp} onChange={set('hp')}
                     style={{ position: 'absolute', left: '-9999px' }} aria-hidden="true" />
              <label className="flex items-start gap-2 text-[12px] text-zinc-600 mt-1">
                <input type="checkbox" checked={form.consent} onChange={set('consent')} className="mt-0.5" />
                <span>Autorizo o contacto da equipa ConstructHub e o tratamento dos meus dados nos termos da política de privacidade (RGPD).</span>
              </label>
              {state === 'error' && <div className="text-[12px] text-red-600">{errMsg}</div>}
              <button type="submit" disabled={state === 'sending'}
                      className="w-full h-11 rounded-md text-white text-[14px] font-medium disabled:opacity-60" style={{ background: '#18181B' }}>
                {state === 'sending' ? 'A enviar…' : 'Pedir convite'}
              </button>
            </form>
          )}
        </div>
      </div>
    );
  }

  function NewsletterForm() {
    const [email, setEmail] = React.useState('');
    const [consent, setConsent] = React.useState(false);
    const [hp, setHp] = React.useState('');
    const [state, setState] = React.useState('idle'); // idle | sending | done | error

    async function submit(e) {
      e.preventDefault();
      setState('sending');
      try {
        const res = await fetch(apiBase() + '/api/newsletter', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, consent, hp }),
        });
        setState(res.ok ? 'done' : 'error');
      } catch (_) { setState('error'); }
    }
    if (state === 'done') return <div className="text-[12.5px] text-zinc-300">Verifique o seu email para confirmar a subscrição.</div>;
    return (
      <form onSubmit={submit} className="flex flex-col gap-2 max-w-[360px]">
        <div className="flex gap-2">
          <input required type="email" placeholder="o-seu@email.pt" value={email} onChange={(e) => setEmail(e.target.value)}
                 className="flex-1 h-10 px-3 rounded-md border border-white/20 bg-white/5 text-[13px] text-white placeholder-white/40" />
          <button type="submit" disabled={state === 'sending'}
                  className="h-10 px-4 rounded-md bg-white text-zinc-900 text-[13px] font-medium disabled:opacity-60">
            {state === 'sending' ? '…' : 'Avisar-me'}
          </button>
        </div>
        <input tabIndex={-1} autoComplete="off" value={hp} onChange={(e) => setHp(e.target.value)}
               style={{ position: 'absolute', left: '-9999px' }} aria-hidden="true" />
        <label className="flex items-start gap-2 text-[11px] text-white/50">
          <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} className="mt-0.5" />
          <span>Aceito receber novidades por email (RGPD). Pode cancelar a qualquer momento.</span>
        </label>
        {state === 'error' && <div className="text-[11px] text-red-300">Verifique o email e o consentimento.</div>}
      </form>
    );
  }

  Object.assign(window, { RegisterModal, NewsletterForm });
})();
