// Contact form — Formspree integration with async submission + states
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/xgorqdwn';

const contactFormStyles = `
  .tk-form-status {
    border: 1px solid var(--line-strong);
    border-radius: 8px;
    padding: 28px 24px;
    text-align: left;
    background: var(--bg);
  }
  .tk-form-status.ok { border-color: var(--accent); background: #fff8f4; }
  .tk-form-status.err { border-color: #c8423a; background: #fff4f3; }
  .tk-form-status-l {
    font-family: 'JetBrains Mono', monospace;
    font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;
    color: var(--accent);
    margin-bottom: 10px;
    display: flex; align-items: center; gap: 10px;
  }
  .tk-form-status.err .tk-form-status-l { color: #c8423a; }
  .tk-form-status-l::before { content: ''; width: 18px; height: 1px; background: currentColor; }
  .tk-form-status-t {
    font-size: 22px; letter-spacing: -0.015em; line-height: 1.2;
    margin: 0 0 8px; font-weight: 600;
  }
  .tk-form-status-d {
    font-size: 14px; line-height: 1.5; color: var(--muted); margin: 0;
  }
  .tk-form-status-reset {
    font-family: 'JetBrains Mono', monospace;
    font-size: 11.5px; letter-spacing: 0.04em;
    color: var(--ink); background: transparent; border: none;
    padding: 0; margin-top: 14px; cursor: pointer;
    text-decoration: underline; text-underline-offset: 3px;
  }
  .tk-form-status-reset:hover { color: var(--accent); }
  .tk-form-field input:disabled,
  .tk-form-field textarea:disabled { opacity: 0.6; cursor: wait; }
  .tk-btn[disabled] { opacity: 0.6; cursor: wait; }
`;

function ContactForm({ linkedin }) {
  const [status, setStatus] = React.useState('idle'); // idle | sending | ok | err

  const onSubmit = async (e) => {
    e.preventDefault();
    const form = e.currentTarget;
    const fd = new FormData(form);

    setStatus('sending');
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        body: fd,
        headers: { Accept: 'application/json' },
      });
      if (res.ok) {
        setStatus('ok');
        form.reset();
      } else {
        setStatus('err');
      }
    } catch (_err) {
      setStatus('err');
    }
  };

  if (status === 'ok') {
    return (
      <>
        <style>{contactFormStyles}</style>
        <div className="tk-form-status ok">
          <div className="tk-form-status-l">Mensaje enviado</div>
          <h4 className="tk-form-status-t">Gracias. Te respondo en 24 — 48 h.</h4>
          <p className="tk-form-status-d">Mientras tanto, si quieres puedes escribirme también por LinkedIn.</p>
          <button className="tk-form-status-reset" onClick={() => setStatus('idle')}>← Enviar otro mensaje</button>
        </div>
      </>
    );
  }

  return (
    <>
      <style>{contactFormStyles}</style>
      <form
        className="tk-form"
        action={FORMSPREE_ENDPOINT}
        method="POST"
        onSubmit={onSubmit}
      >
        <div className="tk-form-row">
          <label className="tk-form-field">
            <span className="tk-form-l">Nombre</span>
            <input type="text" name="nombre" required autoComplete="name" placeholder="Cómo te llamas" disabled={status === 'sending'} />
          </label>
          <label className="tk-form-field">
            <span className="tk-form-l">Empresa</span>
            <input type="text" name="empresa" autoComplete="organization" placeholder="Tu marca o proyecto" disabled={status === 'sending'} />
          </label>
        </div>
        <label className="tk-form-field">
          <span className="tk-form-l">Correo electrónico</span>
          <input type="email" name="email" required autoComplete="email" placeholder="tu@email.com" disabled={status === 'sending'} />
        </label>
        <label className="tk-form-field">
          <span className="tk-form-l">Cuéntame</span>
          <textarea name="mensaje" rows="4" required placeholder="¿En qué estás trabajando? ¿Qué necesitas?" disabled={status === 'sending'}></textarea>
        </label>
        {status === 'err' && (
          <div className="tk-form-status err">
            <div className="tk-form-status-l">Error de envío</div>
            <p className="tk-form-status-d">No se pudo enviar el formulario. Inténtalo de nuevo o escríbeme por LinkedIn.</p>
          </div>
        )}
        <div className="tk-form-actions">
          <button type="submit" className="tk-btn prim" disabled={status === 'sending'}>
            {status === 'sending' ? 'Enviando…' : 'Enviar mensaje'}
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
          </button>
          <a className="tk-form-li" href={linkedin} target="_blank" rel="noopener">
            o escríbeme por LinkedIn
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M7 17L17 7M7 7h10v10" /></svg>
          </a>
        </div>
      </form>
    </>
  );
}

window.ContactForm = ContactForm;
