// ============================================================
// landing-form.jsx — Formulário de captação (lista de espera)
//
// Campos: e-mail (obrigatório) · WhatsApp opcional c/ seletor de país (bandeiras)
//         · país (dropdown) · consentimento obrigatório · honeypot anti-spam
//         · campos UTM ocultos (capturados da URL).
//
// Depende de: intl-tel-input (CDN, carregado no <head> via index.php/server.js).
// Expõe: window.LandingForm
// ============================================================

// Lista de países (código ISO-2 + nome PT/EN/ES). Usada no dropdown "País".
// Ordem: Brasil e principais hispanos/EUA no topo, depois alfabética.
const COUNTRIES = [
  { code: 'BR', pt: 'Brasil',            en: 'Brazil',          es: 'Brasil' },
  { code: 'PT', pt: 'Portugal',          en: 'Portugal',        es: 'Portugal' },
  { code: 'US', pt: 'Estados Unidos',    en: 'United States',   es: 'Estados Unidos' },
  { code: 'AR', pt: 'Argentina',         en: 'Argentina',       es: 'Argentina' },
  { code: 'MX', pt: 'México',            en: 'Mexico',          es: 'México' },
  { code: 'CL', pt: 'Chile',             en: 'Chile',           es: 'Chile' },
  { code: 'CO', pt: 'Colômbia',          en: 'Colombia',        es: 'Colombia' },
  { code: 'PE', pt: 'Peru',              en: 'Peru',            es: 'Perú' },
  { code: 'VE', pt: 'Venezuela',         en: 'Venezuela',       es: 'Venezuela' },
  { code: 'UY', pt: 'Uruguai',           en: 'Uruguay',         es: 'Uruguay' },
  { code: 'PY', pt: 'Paraguai',          en: 'Paraguay',        es: 'Paraguay' },
  { code: 'BO', pt: 'Bolívia',           en: 'Bolivia',         es: 'Bolivia' },
  { code: 'EC', pt: 'Equador',           en: 'Ecuador',         es: 'Ecuador' },
  { code: 'ES', pt: 'Espanha',           en: 'Spain',           es: 'España' },
  { code: 'CA', pt: 'Canadá',            en: 'Canada',          es: 'Canadá' },
  { code: 'GB', pt: 'Reino Unido',       en: 'United Kingdom',  es: 'Reino Unido' },
  { code: 'DE', pt: 'Alemanha',          en: 'Germany',         es: 'Alemania' },
  { code: 'FR', pt: 'França',            en: 'France',          es: 'Francia' },
  { code: 'IT', pt: 'Itália',            en: 'Italy',           es: 'Italia' },
  { code: 'OT', pt: 'Outro',             en: 'Other',           es: 'Otro' },
];

// Lê um parâmetro da query string (?utm_source=...).
function getQueryParam(name) {
  try {
    return new URLSearchParams(window.location.search).get(name) || '';
  } catch (_) {
    return '';
  }
}

// ── Marco ornamental nos cantos (mesmo visual dos outros cards) ──
const CornerMarks = () => (
  <>
    <span aria-hidden className="absolute top-1.5 left-1.5 w-3 h-3 border-l-2 border-t-2 border-gold-500/70" />
    <span aria-hidden className="absolute top-1.5 right-1.5 w-3 h-3 border-r-2 border-t-2 border-gold-500/70" />
    <span aria-hidden className="absolute bottom-1.5 left-1.5 w-3 h-3 border-l-2 border-b-2 border-gold-500/70" />
    <span aria-hidden className="absolute bottom-1.5 right-1.5 w-3 h-3 border-r-2 border-b-2 border-gold-500/70" />
  </>
);

const LandingForm = () => {
  const { t, lang } = useT();

  const [values, setValues] = React.useState({ email: '', country: '', consent: false, sugestao: '' });
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // idle | sending | success | error
  const [serverError, setServerError] = React.useState('');

  const phoneInputRef = React.useRef(null); // <input> do telefone
  const itiRef        = React.useRef(null); // instância do intl-tel-input
  const honeypotRef   = React.useRef(null); // campo isca (deve ficar vazio)

  // UTM capturados uma única vez no carregamento.
  const utm = React.useRef({
    utm_source:   getQueryParam('utm_source'),
    utm_medium:   getQueryParam('utm_medium'),
    utm_campaign: getQueryParam('utm_campaign'),
  });

  // Inicializa o intl-tel-input no <input> de telefone (bandeiras + código de país).
  React.useEffect(() => {
    if (!phoneInputRef.current || !window.intlTelInput) return;
    const iti = window.intlTelInput(phoneInputRef.current, {
      initialCountry: 'br',
      preferredCountries: ['br', 'pt', 'us', 'ar', 'mx', 'cl', 'co'],
      separateDialCode: true,
      // utilsScript não é estritamente necessário; validação leve é feita abaixo.
    });
    itiRef.current = iti;
    return () => { try { iti.destroy(); } catch (_) {} };
  }, []);

  const countryName = (c) => c[lang] || c.en;

  const validate = (v) => {
    const e = {};
    // E-mail obrigatório
    if (!v.email.trim()) e.email = t('lp_err_email_required');
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email.trim())) e.email = t('lp_err_email_invalid');
    // País obrigatório
    if (!v.country) e.country = t('lp_err_country_required');
    // Consentimento obrigatório
    if (!v.consent) e.consent = t('lp_err_consent_required');
    // Telefone é OPCIONAL — só validamos se algo foi digitado.
    // Validação leve por contagem de dígitos (NÃO depende do utils.js do
    // intl-tel-input, que não é carregado). 6–15 dígitos = faixa válida E.164.
    // O servidor (inscrever.php) revalida — esta é só uma checagem de sanidade.
    const iti = itiRef.current;
    if (iti) {
      const raw = phoneInputRef.current.value.trim();
      if (raw) {
        const digits = raw.replace(/\D/g, '');
        if (digits.length < 6 || digits.length > 15) {
          e.phone = t('lp_err_phone_invalid');
        }
      }
    }
    return e;
  };

  const onChange = (k) => (e) => {
    const val = k === 'consent' ? e.target.checked : e.target.value;
    const next = { ...values, [k]: val };
    setValues(next);
    if (Object.keys(errors).length) setErrors(validate(next));
  };

  const onSubmit = async (e) => {
    e.preventDefault();

    // Honeypot: se preenchido, é bot. Fingimos sucesso e não enviamos nada.
    if (honeypotRef.current && honeypotRef.current.value) {
      setStatus('success');
      return;
    }

    const errs = validate(values);
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    // Número internacional completo (ex: +5511999998888) — vazio se não preenchido.
    // Montado manualmente a partir do DDI do país selecionado (getSelectedCountryData
    // NÃO depende do utils.js) + dígitos digitados. Necessário porque separateDialCode:true
    // mantém o DDI fora do <input>, e getNumber() retornaria vazio sem o utils.js.
    let phone = '';
    const iti = itiRef.current;
    if (iti && phoneInputRef.current.value.trim()) {
      const data   = iti.getSelectedCountryData();
      const dial   = (data && data.dialCode) || '';
      const digits = phoneInputRef.current.value.replace(/\D/g, '');
      phone = digits ? '+' + dial + digits : '';
    }

    const payload = {
      email:        values.email.trim(),
      telefone:     phone,
      pais:         values.country,
      idioma:       lang,
      sugestao:     values.sugestao.trim().slice(0, 500),
      consentimento: values.consent ? 1 : 0,
      utm_source:   utm.current.utm_source,
      utm_medium:   utm.current.utm_medium,
      utm_campaign: utm.current.utm_campaign,
      website:      '', // honeypot (sempre vazio aqui)
    };

    setStatus('sending');
    setServerError('');

    try {
      const resp = await fetch('/api/inscrever.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await resp.json().catch(() => ({}));

      if (resp.ok && data.ok) {
        // ===== RASTREAMENTO — disparar evento "Lead" no sucesso =====
        // Descomente conforme for ativando cada pixel (IDs configurados no <head>).
        if (window.fbq)  fbq('track', 'Lead');
        // if (window.gtag) gtag('event', 'generate_lead');
        // if (window.ttq)  ttq.track('SubmitForm');
        setStatus('success');
      } else if (resp.status === 409) {
        // E-mail duplicado: tratamos como sucesso (a pessoa já está na lista).
        setStatus('success');
      } else {
        setServerError(data.erro || t('lp_err_generic'));
        setStatus('error');
      }
    } catch (_) {
      setServerError(t('lp_err_generic'));
      setStatus('error');
    }
  };

  // ── Estado de SUCESSO: "Você está na lista!" + comunidade ──
  if (status === 'success') {
    return (
      <div className="relative bg-stone-900/70 border border-gold-700/40 p-8 sm:p-10 flex flex-col items-center text-center gap-6">
        <CornerMarks />
        <div className="text-gold-400 text-5xl">⚔</div>
        <h3 className="font-display font-black uppercase tracking-tight text-3xl sm:text-4xl text-parchment leading-[0.95]">
          {t('lp_success_title_l1')}<br />
          <span className="text-gold-400">{t('lp_success_title_l2')}</span>
        </h3>
        <p className="font-body text-parchment/70 max-w-md leading-relaxed">{t('lp_success_body')}</p>
        <div className="flex flex-col sm:flex-row justify-center gap-3 w-full sm:w-auto">
          <PrimaryCTA href="https://www.instagram.com/kingdomtale" target="_blank" rel="noopener noreferrer">INSTAGRAM</PrimaryCTA>
          <GhostCTA href="https://www.facebook.com/profile.php?id=61590575913044" target="_blank" rel="noopener noreferrer">FACEBOOK</GhostCTA>

          {/* DISCORD e WHATSAPP — ocultos até termos os links reais (evita botão -> "#").
              Para reativar: descomente abaixo e troque o href="#" pelo link real, mantendo target/rel.
          <PrimaryCTA href="#" target="_blank" rel="noopener noreferrer">{t('lp_cta_discord')}</PrimaryCTA>
          <GhostCTA href="#" target="_blank" rel="noopener noreferrer">{t('lp_cta_whatsapp_group')}</GhostCTA>
          */}
        </div>
        <p className="font-body italic text-xs text-parchment/40 max-w-sm">{t('lp_success_share')}</p>
      </div>
    );
  }

  const sending = status === 'sending';

  return (
    <form onSubmit={onSubmit} noValidate className="relative bg-stone-900/60 border border-gold-700/30 p-6 sm:p-8 flex flex-col gap-5">
      <CornerMarks />

      {/* E-MAIL (obrigatório) */}
      <label className="flex flex-col gap-2">
        <span className="font-impact tracking-[0.35em] text-[10px] text-gold-500/80">{t('lp_form_email')}</span>
        <input
          type="email"
          inputMode="email"
          autoComplete="email"
          placeholder={t('lp_form_email_ph')}
          value={values.email}
          onChange={onChange('email')}
          className={`bg-stone-950 border ${errors.email ? 'border-crimson-500' : 'border-gold-700/60'} px-4 py-3 text-parchment font-body text-base outline-none transition-all duration-200
            focus:border-gold-400 focus:shadow-[0_0_24px_rgba(218,165,32,0.35)]`}
        />
        {errors.email && <span className="font-impact tracking-[0.2em] text-[10px] text-crimson-400 uppercase">{errors.email}</span>}
      </label>

      {/* WHATSAPP (opcional) — intl-tel-input adiciona o seletor de país c/ bandeira */}
      <label className="flex flex-col gap-2">
        <span className="font-impact tracking-[0.35em] text-[10px] text-gold-500/80">
          {t('lp_form_phone')} <span className="text-parchment/40 normal-case tracking-normal">{t('lp_form_phone_opt')}</span>
        </span>
        <input
          ref={phoneInputRef}
          type="tel"
          autoComplete="tel"
          className={`iti-input bg-stone-950 border ${errors.phone ? 'border-crimson-500' : 'border-gold-700/60'} px-4 py-3 text-parchment font-body text-base outline-none transition-all duration-200
            focus:border-gold-400 focus:shadow-[0_0_24px_rgba(218,165,32,0.35)]`}
        />
        {errors.phone && <span className="font-impact tracking-[0.2em] text-[10px] text-crimson-400 uppercase">{errors.phone}</span>}
      </label>

      {/* PAÍS (obrigatório) */}
      <label className="flex flex-col gap-2">
        <span className="font-impact tracking-[0.35em] text-[10px] text-gold-500/80">{t('lp_form_country')}</span>
        <select
          value={values.country}
          onChange={onChange('country')}
          className={`bg-stone-950 border ${errors.country ? 'border-crimson-500' : 'border-gold-700/60'} px-4 py-3 text-parchment font-body text-base outline-none transition-all duration-200
            focus:border-gold-400 focus:shadow-[0_0_24px_rgba(218,165,32,0.35)]`}
        >
          <option value="" disabled>{t('lp_form_country_ph')}</option>
          {COUNTRIES.map((c) => (
            <option key={c.code} value={c.code}>{countryName(c)}</option>
          ))}
        </select>
        {errors.country && <span className="font-impact tracking-[0.2em] text-[10px] text-crimson-400 uppercase">{errors.country}</span>}
      </label>

      {/* CONSENTIMENTO (obrigatório) */}
      <label className="flex items-start gap-3 cursor-pointer">
        <input
          type="checkbox"
          checked={values.consent}
          onChange={onChange('consent')}
          className="mt-1 w-4 h-4 accent-crimson-600 shrink-0"
        />
        <span className="font-body text-xs text-parchment/60 leading-relaxed">
          {t('lp_form_consent')}{' '}
          <a href="/privacidade.php" target="_blank" rel="noopener" className="text-gold-400 underline hover:text-gold-300">
            {t('lp_form_policy_link')}
          </a>.
        </span>
      </label>
      {errors.consent && <span className="font-impact tracking-[0.2em] text-[10px] text-crimson-400 uppercase -mt-2">{errors.consent}</span>}

      {/* SUGESTÃO (opcional) — feedback pré-lançamento; máx. 500 caracteres */}
      <label className="flex flex-col gap-2">
        <span className="font-impact tracking-[0.35em] text-[10px] text-gold-500/80">{t('lp_form_suggestion')}</span>
        <textarea
          value={values.sugestao}
          onChange={onChange('sugestao')}
          maxLength={500}
          rows={3}
          placeholder={t('lp_form_suggestion_ph')}
          className="bg-stone-950 border border-gold-700/60 px-4 py-3 text-parchment font-body text-base outline-none transition-all duration-200 resize-none
            focus:border-gold-400 focus:shadow-[0_0_24px_rgba(218,165,32,0.35)]"
        />
        <span className="font-body text-[10px] text-parchment/40 self-end">{values.sugestao.length}/500</span>
      </label>

      {/* HONEYPOT — campo isca escondido de humanos; bots costumam preencher */}
      <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: 'auto', height: 0, width: 0, overflow: 'hidden' }}>
        <label>Website
          <input ref={honeypotRef} type="text" name="website" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      {serverError && (
        <p className="font-impact tracking-[0.2em] text-[11px] text-crimson-400 uppercase text-center">{serverError}</p>
      )}

      <button
        type="submit"
        disabled={sending}
        className={`group relative mt-1 inline-flex items-center justify-center gap-3 font-headline uppercase tracking-[0.25em]
          px-8 py-4 text-sm sm:text-base bg-crimson-700 text-parchment border border-crimson-500
          transition-all duration-300 hover:bg-gold-700 hover:text-stone-950 hover:border-gold-500
          hover:shadow-[0_0_40px_rgba(218,165,32,0.35)] active:translate-y-[1px]
          ${sending ? 'opacity-60 cursor-wait' : ''}`}
        style={{ clipPath: 'polygon(8px 0, calc(100% - 8px) 0, 100% 8px, 100% calc(100% - 8px), calc(100% - 8px) 100%, 8px 100%, 0 calc(100% - 8px), 0 8px)' }}
      >
        {sending ? t('lp_form_sending') : t('lp_form_submit')}
      </button>
    </form>
  );
};

Object.assign(window, { LandingForm, COUNTRIES });
