// contact.jsx — Y2K contact form (conectado a /api/contact.php)
const { useState: __cts, useEffect: __cte, useRef: __ctr } = React;

function Contact({ t }) {
  const [form, setForm] = __cts({
    name: '', email: '', company: '', budget: '', services: [], brief: '',
    website: '', // honeypot — debe quedar vacío
  });
  const [submitted, setSubmitted] = __cts(false);
  const [sending, setSending]     = __cts(false);
  const [errMsg, setErrMsg]       = __cts(null);
  const csrf = __ctr(null);
  const loadedAt = __ctr(Math.floor(Date.now() / 1000));

  // Pide token CSRF al montar
  __cte(() => {
    fetch('api/csrf.php', { credentials: 'same-origin' })
      .then(r => r.json())
      .then(d => { csrf.current = d.token; loadedAt.current = d.t || loadedAt.current; })
      .catch(() => {});
  }, []);

  const toggle = (s) => {
    setForm(f => ({
      ...f,
      services: f.services.includes(s) ? f.services.filter(x => x !== s) : [...f.services, s]
    }));
  };

  const submit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setErrMsg(null);
    setSending(true);
    try {
      const res = await fetch('api/contact.php', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf.current || '' },
        body: JSON.stringify({ ...form, _csrf: csrf.current, t: loadedAt.current })
      });
      const data = await res.json();
      if (data.ok) {
        setSubmitted(true);
      } else {
        setErrMsg(data.msg || 'No pudimos enviar tu mensaje. Intenta de nuevo.');
      }
    } catch (err) {
      setErrMsg('Error de conexión. Intenta de nuevo en un momento.');
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="contact" style={{ paddingTop: 120, paddingBottom: 60, position: 'relative' }}>
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 100, alignItems: 'start' }}>
          {/* Left intro */}
          <div style={{ position: 'sticky', top: 120 }}>
            <div className="kicker reveal" style={{ marginBottom: 28 }}>
              <span className="dot"></span>{t.cnt_eye}
            </div>
            <h2 className="display reveal" style={{ fontSize: 'clamp(48px, 7vw, 96px)', marginBottom: 32 }}>
              <div>{t.cnt_title_1}</div>
              <div className="irid-text" style={{ fontStyle: 'italic' }}>{t.cnt_title_2}</div>
            </h2>
            <p className="reveal" style={{ fontSize: 17, color: 'var(--ink)', lineHeight: 1.5, marginBottom: 48 }}>
              {t.cnt_sub}
            </p>

            <div style={{ borderTop: '1.5px solid var(--ink)', paddingTop: 32 }}>
              <div className="kicker" style={{ marginBottom: 14 }}>{t.cnt_or}</div>
              <a href="mailto:hola@multiplesmedios.com" className="display"
                 style={{
                   fontStyle: 'italic', fontSize: 28, color: 'var(--ink)',
                   textDecoration: 'none', display: 'block', marginBottom: 24,
                   letterSpacing: '-0.02em', fontWeight: 600
                 }}>
                hola@multiplesmedios.com
              </a>
              <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap' }}>
                {[
                  { l: 'Instagram', h: '@multiplesmedios', c: 'magenta' },
                  { l: 'WhatsApp', h: '+57 300 000 0000', c: 'lime' },
                  { l: 'LinkedIn', h: '/multiplesmedios', c: 'azure' },
                ].map(c => (
                  <div key={c.l} className="clickable" data-hover style={{
                    padding: '10px 14px',
                    border: '1.5px solid var(--ink)',
                    borderRadius: 12,
                    background: 'var(--paper)',
                    boxShadow: '3px 3px 0 var(--ink)',
                  }}>
                    <div className="kicker" style={{ marginBottom: 4, color: `var(--${c.c})` }}>{c.l}</div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{c.h}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Right form */}
          {submitted ? (
            <div className="reveal" style={{
              padding: 64, border: '1.5px solid var(--ink)', borderRadius: 24,
              background: 'var(--paper)', textAlign: 'center',
              boxShadow: '8px 8px 0 var(--ink)'
            }}>
              <div style={{
                width: 80, height: 80, borderRadius: '50%',
                background: 'var(--lime)', border: '1.5px solid var(--ink)',
                margin: '0 auto 24px', display: 'flex',
                alignItems: 'center', justifyContent: 'center',
                color: 'var(--ink)'
              }}>
                <Icon name="check" size={40} strokeWidth={3} />
              </div>
              <h3 className="display" style={{ fontSize: 48, fontStyle: 'italic', marginBottom: 16 }}>
                Gracias, {form.name || 'amigo'}.
              </h3>
              <p style={{ color: 'var(--ink-dim)', fontSize: 16 }}>Respondemos en &lt; 24 horas.</p>
            </div>
          ) : (
            <form onSubmit={submit} noValidate
              className="reveal" style={{
              padding: 48, borderRadius: 24, background: 'var(--paper)',
              border: '1.5px solid var(--ink)', boxShadow: '8px 8px 0 var(--ink)',
              display: 'flex', flexDirection: 'column', gap: 36
            }}>
              {/* Honeypot oculto (los bots la llenan, humanos no) */}
              <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', height: 0, width: 0, overflow: 'hidden' }}>
                <label>No llenar este campo
                  <input tabIndex={-1} autoComplete="off" name="website" value={form.website}
                    onChange={e => setForm({...form, website: e.target.value})} />
                </label>
              </div>

              {errMsg && (
                <div role="alert" style={{
                  padding: '12px 16px', borderRadius: 10,
                  background: 'color-mix(in oklch, var(--magenta) 14%, var(--paper))',
                  border: '1.5px solid var(--magenta)', color: 'var(--ink)', fontSize: 13
                }}>{errMsg}</div>
              )}

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
                <div>
                  <label className="kicker" style={{ display: 'block', marginBottom: 4 }}>01 / {t.cnt_name}</label>
                  <input className="field" required name="name" maxLength={120} value={form.name}
                    onChange={e => setForm({...form, name: e.target.value})} />
                </div>
                <div>
                  <label className="kicker" style={{ display: 'block', marginBottom: 4 }}>02 / {t.cnt_email}</label>
                  <input className="field" type="email" required value={form.email}
                    onChange={e => setForm({...form, email: e.target.value})} />
                </div>
              </div>

              <div>
                <label className="kicker" style={{ display: 'block', marginBottom: 4 }}>03 / {t.cnt_company}</label>
                <input className="field" value={form.company}
                  onChange={e => setForm({...form, company: e.target.value})} />
              </div>

              <div>
                <label className="kicker" style={{ display: 'block', marginBottom: 14 }}>04 / {t.cnt_services}</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {t.services_pick.map(s => (
                    <button key={s} type="button" onClick={() => toggle(s)} className="clickable"
                      style={{
                        padding: '12px 20px', borderRadius: 999,
                        border: '1.5px solid var(--ink)',
                        background: form.services.includes(s) ? 'var(--ink)' : 'transparent',
                        color: form.services.includes(s) ? 'var(--bg)' : 'var(--ink)',
                        fontSize: 14, fontFamily: 'inherit', fontWeight: 500,
                        cursor: 'none', transition: 'all 0.3s'
                      }}>{s}</button>
                  ))}
                </div>
              </div>

              <div>
                <label className="kicker" style={{ display: 'block', marginBottom: 14 }}>05 / {t.cnt_budget}</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {t.budgets.map(b => (
                    <button key={b} type="button" onClick={() => setForm({...form, budget: b})} className="clickable"
                      style={{
                        padding: '12px 20px', borderRadius: 999,
                        border: '1.5px solid var(--ink)',
                        background: form.budget === b ? 'var(--magenta)' : 'transparent',
                        color: form.budget === b ? 'white' : 'var(--ink)',
                        fontSize: 14, fontFamily: 'inherit', fontWeight: 500,
                        cursor: 'none', transition: 'all 0.3s'
                      }}>{b}</button>
                  ))}
                </div>
              </div>

              <div>
                <label className="kicker" style={{ display: 'block', marginBottom: 4 }}>06 / {t.cnt_brief}</label>
                <textarea className="field" rows={4} value={form.brief}
                  onChange={e => setForm({...form, brief: e.target.value})}
                  style={{ resize: 'vertical', minHeight: 100 }} />
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div className="kicker" style={{ fontSize: 10, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="sparkles" size={12} color="var(--magenta)" /> Respondemos en &lt; 24h hábiles
                </div>
                <button type="submit" disabled={sending} className="btn chrome-btn"
                  style={{ padding: '16px 28px', border: 'none', opacity: sending ? 0.6 : 1, cursor: sending ? 'wait' : undefined }}>
                  {sending ? 'Enviando…' : t.cnt_send} <span className="arrow">↗</span>
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Contact });
