// contact.jsx
const { useState: useStateC } = React;

const FORMSUBMIT_ENDPOINT = 'https://formsubmit.co/ajax/rafael@souzanunesecia.com.br';

const Contact = () => {
  const { t, lang } = useLang();
  const c = t.contact;
  const [status, setStatus] = useStateC('idle'); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = useStateC('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;

    const form = e.currentTarget;
    const formData = new FormData(form);

    setStatus('sending');
    setErrorMsg('');

    try {
      const res = await fetch(FORMSUBMIT_ENDPOINT, {
        method: 'POST',
        headers: { 'Accept': 'application/json' },
        body: formData
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.success !== 'false') {
        setStatus('success');
        form.reset();
      } else {
        throw new Error(data.message || 'Falha no envio');
      }
    } catch (err) {
      setStatus('error');
      setErrorMsg(lang === 'pt'
        ? 'Não foi possível enviar agora. Tente novamente em instantes.'
        : 'Could not send right now. Please try again shortly.');
    }
  };

  const sending = status === 'sending';
  const success = status === 'success';
  const error = status === 'error';

  const successText = lang === 'pt'
    ? 'Obrigado, retornamos em até 1 dia útil'
    : 'Thank you, we’ll reply within 1 business day';
  const sendingText = lang === 'pt' ? 'Enviando…' : 'Sending…';

  // SVG checkmark (replaces emoji ✓ - emoji rendering is font-dependent
  // and breaks consistency across platforms; SVG follows currentColor).
  const CheckIcon = () => (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none"
         stroke="currentColor" strokeWidth="2" strokeLinecap="round"
         strokeLinejoin="round" aria-hidden="true">
      <path d="M3 8.5 L6.5 12 L13 4.5"/>
    </svg>
  );

  // Live region announcement for screen readers (status of submission)
  const liveAnnouncement = sending
    ? sendingText
    : success
      ? successText
      : error
        ? errorMsg
        : '';

  return (
    <section className="contact" id="contact">
      <Reveal><div className="eyebrow">{c.eyebrow}</div></Reveal>
      <Reveal delay={1}><h2 className="contact-headline">{c.title}</h2></Reveal>

      {/* Live region - announces sending / success / error to screen readers */}
      <div className="visually-hidden" aria-live="polite" aria-atomic="true">
        {liveAnnouncement}
      </div>

      <div className="contact-grid">
        <form className="contact-form" onSubmit={handleSubmit} noValidate>
          {/* Formsubmit configuration */}
          <input type="hidden" name="_subject" value={lang === 'pt'
            ? 'Novo contato pelo site SN&Cia'
            : 'New website contact: SN&Cia'}/>
          <input type="hidden" name="_template" value="table"/>
          <input type="hidden" name="_captcha" value="false"/>
          {/* Honeypot - hidden anti-spam field; bots fill it, humans don't */}
          <input type="text" name="_honey" tabIndex="-1" autoComplete="off"
            style={{position:'absolute', left:'-9999px', opacity:0, pointerEvents:'none'}} aria-hidden="true"/>

          <Reveal delay={1}>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:32}}>
              <div className="field">
                <label htmlFor="contact-name">{c.name}</label>
                <input id="contact-name" name="Nome" type="text" required disabled={sending}/>
              </div>
              <div className="field">
                <label htmlFor="contact-company">{c.company}</label>
                <input id="contact-company" name="Empresa" type="text" required disabled={sending}/>
              </div>
            </div>
          </Reveal>
          <Reveal delay={2}>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:32}}>
              <div className="field">
                <label htmlFor="contact-role">{c.role}</label>
                <input id="contact-role" name="Cargo" type="text" disabled={sending}/>
              </div>
              <div className="field">
                <label htmlFor="contact-email">{c.email}</label>
                <input id="contact-email" name="email" type="email" required disabled={sending}/>
              </div>
              <div className="field">
                <label htmlFor="contact-phone">{c.phone}</label>
                <input id="contact-phone" name="Telefone" type="tel" inputMode="tel" disabled={sending}/>
              </div>
            </div>
          </Reveal>
          <Reveal delay={3}>
            <div className="field">
              <label htmlFor="contact-interest">{c.interest}</label>
              <select id="contact-interest" name="Interesse" disabled={sending} defaultValue="" required>
                {/* Placeholder option: invisible until the user opens the
                    dropdown. defaultValue="" + value="" + disabled+hidden
                    keeps the field visually empty on first render across
                    Chrome / Safari / Firefox. */}
                <option value="" disabled hidden></option>
                <option>Estratégia</option>
                <option>Finanças</option>
                <option>Valuation</option>
                <option>VBM</option>
                <option>Governança</option>
                <option>Educação</option>
                <option>{c.interestOther}</option>
              </select>
            </div>
          </Reveal>
          <Reveal delay={4}>
            <div className="field">
              <label htmlFor="contact-message">{c.message}</label>
              <textarea id="contact-message" name="Mensagem" rows="3" disabled={sending}></textarea>
            </div>
          </Reveal>
          <Reveal delay={5}>
            <div className="contact-submit-row">
              <button
                type="submit"
                className={`contact-submit ${success ? 'is-success' : ''}`}
                disabled={sending || success}
                aria-busy={sending}>
                {success && <CheckIcon/>}
                <span>
                  {success ? successText : sending ? sendingText : c.submit}
                </span>
                {!success && !sending && <ArrowIcon/>}
              </button>
              {error && (
                <span className="contact-error" role="alert">{errorMsg}</span>
              )}
            </div>
          </Reveal>
        </form>
      </div>
    </section>
  );
};

window.Contact = Contact;
