/* CONTACT — Sección final, tipo "última pieza".
   Lado izquierdo: heading enorme + datos directos (WhatsApp, teléfono, email, dirección).
   Lado derecho: formulario corto (no genérico, con campos específicos del rubro:
   tipo de proyecto, tienes plano?, cuándo lo necesitas?). */

const Contact = ({ t, lang = 'es' }) => {
  const [form, setForm] = React.useState({
    name: '', company: '', phone: '', email: '',
    project: 'counter', hasPlans: 'no', when: '4-8w', notes: '',
  });
  const [sent, setSent] = React.useState(false);

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Etiquetas legibles para el mensaje a WhatsApp (no IDs internos)
  const projectLabels = {
    counter:    { es: 'Counter / mostrador',         en: 'Counter' },
    kiosco:     { es: 'Kiosco / tótem urbano',       en: 'Kiosk / urban totem' },
    cocina:     { es: 'Cocina industrial',           en: 'Industrial kitchen' },
    gabinete:   { es: 'Gabinete telecom / outdoor',  en: 'Telecom / outdoor cabinet' },
    estructura: { es: 'Estructura / mueble inox',    en: 'Structure / stainless furniture' },
    otro:       { es: 'Otro',                         en: 'Other' },
  };
  const planLabels = {
    no:   { es: 'Solo idea, sin plano',     en: 'Just an idea, no plans' },
    foto: { es: 'Tengo foto / boceto',      en: 'Photo / sketch' },
    pdf:  { es: 'Tengo PDF',                en: 'I have a PDF' },
    cad:  { es: 'Plano CAD listo',          en: 'CAD ready' },
  };
  const whenLabels = {
    urgente:     { es: 'Urgente (≤2 sem)',  en: 'Urgent (≤2 wk)' },
    '4-8w':      { es: '4–8 semanas',        en: '4–8 weeks' },
    '2-3m':      { es: '2–3 meses',          en: '2–3 months' },
    explorando:  { es: 'Solo explorando',    en: 'Just exploring' },
  };

  const pickLabel = (map, key) => (map[key] && (map[key][lang] || map[key].es)) || key;

  const submit = (e) => {
    e.preventDefault();

    // Validación mínima — el browser ya valida required, esto es defensa adicional
    if (!form.name || !form.phone) return;

    const lines = lang === 'es'
      ? [
          'Hola Acerolab, quiero cotizar un proyecto.',
          '',
          `· Nombre: ${form.name}`,
          form.company ? `· Empresa: ${form.company}` : null,
          `· Teléfono: ${form.phone}`,
          form.email ? `· Email: ${form.email}` : null,
          `· Proyecto: ${pickLabel(projectLabels, form.project)}`,
          `· Planos: ${pickLabel(planLabels, form.hasPlans)}`,
          `· Tiempos: ${pickLabel(whenLabels, form.when)}`,
          form.notes ? '' : null,
          form.notes ? `Notas:\n${form.notes}` : null,
        ]
      : [
          'Hi Acerolab, I would like to quote a project.',
          '',
          `· Name: ${form.name}`,
          form.company ? `· Company: ${form.company}` : null,
          `· Phone: ${form.phone}`,
          form.email ? `· Email: ${form.email}` : null,
          `· Project: ${pickLabel(projectLabels, form.project)}`,
          `· Plans: ${pickLabel(planLabels, form.hasPlans)}`,
          `· Timing: ${pickLabel(whenLabels, form.when)}`,
          form.notes ? '' : null,
          form.notes ? `Notes:\n${form.notes}` : null,
        ];

    const message = lines.filter(l => l !== null).join('\n');
    const url = `https://wa.me/525578680250?text=${encodeURIComponent(message)}`;

    // Abrir WhatsApp en nueva pestaña; el form queda con el feedback de "enviado"
    window.open(url, '_blank', 'noopener');
    setSent(true);
    setTimeout(() => setSent(false), 6000);
  };

  return (
    <section id="contacto" style={{ background: '#0a0a0b', color: '#f5f5f7', borderTop: '1px solid var(--hairline)' }}>
      <div className="wrap" style={{ padding: '120px 32px' }}>
        <div className="contact-grid" style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 80 }}>

          {/* LEFT */}
          <div>
            <span className="eyebrow" style={{ color: 'rgba(255,255,255,0.5)' }}>— 08 / {t('Contacto', 'Contact')}</span>
            <h2 className="display" style={{
              fontSize: 'clamp(48px, 6vw, 96px)',
              lineHeight: 0.95,
              fontWeight: 500,
              marginTop: 24,
              marginBottom: 32,
              letterSpacing: '-0.03em',
              textWrap: 'balance',
            }}>
              {t('Cuéntanos qué', 'Tell us what')}
              <br/>
              <span style={{
                background: 'linear-gradient(180deg, #f5f5f7 0%, #888892 100%)',
                WebkitBackgroundClip: 'text',
                backgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
              }}>
                {t('necesitas fabricar.', 'you need built.')}
              </span>
            </h2>
            <p style={{ fontSize: 18, lineHeight: 1.6, color: 'rgba(255,255,255,0.7)', maxWidth: 480, marginBottom: 56 }}>
              {t(
                'Respondemos personalmente en menos de 4 horas hábiles. Cotización formal en menos de 12 horas hábiles. No bots, no formularios automáticos: una persona real con experiencia en planta lee tu mensaje. Visitas a planta bienvenidas.',
                'We reply personally in under 4 business hours. Formal quote in under 12 business hours. No bots, no auto-replies — a real person with shop-floor experience reads your message. Plant visits welcome.'
              )}
            </p>

            {/* Direct contact rows */}
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {[
                { label: 'WHATSAPP', value: '+52 55 7868 0250', href: 'https://wa.me/525578680250' },
                { label: 'EMAIL', value: 'contacto@acerolab.com.mx', href: 'mailto:contacto@acerolab.com.mx' },
                { label: t('PLANTA', 'PLANT'), value: 'Tlalnepantla de Baz, Estado de México', href: 'https://maps.google.com/?q=Tlalnepantla+de+Baz' },
              ].map((row, i) => (
                <a key={i} href={row.href} target="_blank" rel="noopener" style={{
                  display: 'grid',
                  gridTemplateColumns: '110px 1fr auto',
                  gap: 24,
                  padding: '20px 0',
                  borderTop: '1px solid rgba(255,255,255,0.1)',
                  borderBottom: i === 3 ? '1px solid rgba(255,255,255,0.1)' : 'none',
                  alignItems: 'center',
                  color: '#fff',
                  textDecoration: 'none',
                  transition: 'padding-left 200ms ease',
                }}
                onMouseEnter={e => e.currentTarget.style.paddingLeft = '8px'}
                onMouseLeave={e => e.currentTarget.style.paddingLeft = '0'}
                >
                  <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.12em' }}>{row.label}</span>
                  <span style={{ fontSize: 16 }}>{row.value}</span>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ opacity: 0.5 }}><path d="M5 12h14M13 5l7 7-7 7"/></svg>
                </a>
              ))}
            </div>

            <div style={{ marginTop: 40, display: 'flex', gap: 32, fontSize: 12, color: 'rgba(255,255,255,0.5)', flexWrap: 'wrap' }} className="mono">
              <span>{t('LUN–SÁB · 9:00–18:00', 'MON–SAT · 9:00–18:00')}</span>
              <span>·</span>
              <span>{t('GARANTÍA 3 AÑOS', '3-YEAR WARRANTY')}</span>
            </div>
          </div>

          {/* RIGHT — form */}
          <form onSubmit={submit} style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.1)', padding: 'clamp(28px, 3vw, 40px)' }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'rgba(255,255,255,0.5)', marginBottom: 24, display: 'flex', justifyContent: 'space-between' }}>
              <span>{t('FORMULARIO RÁPIDO', 'QUICK FORM')}</span>
              <span>{t('SE ENVÍA POR WHATSAPP', 'SENDS VIA WHATSAPP')}</span>
            </div>

            <div style={{ display: 'grid', gap: 20 }}>
              <Field label={t('Nombre', 'Name')}>
                <input required value={form.name} onChange={e => update('name', e.target.value)} placeholder={t('Tu nombre', 'Your name')} />
              </Field>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                <Field label={t('Empresa', 'Company')}>
                  <input value={form.company} onChange={e => update('company', e.target.value)} placeholder={t('Opcional', 'Optional')}/>
                </Field>
                <Field label={t('WhatsApp / teléfono', 'WhatsApp / phone')}>
                  <input required value={form.phone} onChange={e => update('phone', e.target.value)} placeholder="+52 ..."/>
                </Field>
              </div>
              <Field label="Email">
                <input type="email" value={form.email} onChange={e => update('email', e.target.value)} placeholder="tu@empresa.com"/>
              </Field>

              <Field label={t('¿Qué necesitas?', 'What do you need?')}>
                <select value={form.project} onChange={e => update('project', e.target.value)}>
                  <option value="counter">{t('Counter / mostrador', 'Counter')}</option>
                  <option value="kiosco">{t('Kiosco / tótem urbano', 'Kiosk / urban totem')}</option>
                  <option value="cocina">{t('Cocina industrial', 'Industrial kitchen')}</option>
                  <option value="gabinete">{t('Gabinete telecom / outdoor', 'Telecom / outdoor cabinet')}</option>
                  <option value="estructura">{t('Estructura / mueble inox', 'Structure / inox furniture')}</option>
                  <option value="otro">{t('Otro — te explico', 'Other — let me explain')}</option>
                </select>
              </Field>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                <Field label={t('¿Tienes plano?', 'Do you have plans?')}>
                  <select value={form.hasPlans} onChange={e => update('hasPlans', e.target.value)}>
                    <option value="no">{t('No, solo idea', 'No, just an idea')}</option>
                    <option value="foto">{t('Tengo foto / boceto', 'Photo / sketch')}</option>
                    <option value="pdf">{t('Tengo PDF', 'I have a PDF')}</option>
                    <option value="cad">{t('Plano CAD listo', 'CAD ready')}</option>
                  </select>
                </Field>
                <Field label={t('¿Cuándo?', 'When?')}>
                  <select value={form.when} onChange={e => update('when', e.target.value)}>
                    <option value="urgente">{t('Urgente (≤2 sem)', 'Urgent (≤2 wk)')}</option>
                    <option value="4-8w">{t('4–8 semanas', '4–8 weeks')}</option>
                    <option value="2-3m">{t('2–3 meses', '2–3 months')}</option>
                    <option value="explorando">{t('Solo explorando', 'Just exploring')}</option>
                  </select>
                </Field>
              </div>

              <Field label={t('Cuéntanos un poco', 'Tell us a bit')}>
                <textarea rows={3} value={form.notes} onChange={e => update('notes', e.target.value)} placeholder={t('Dimensiones, contexto, lo que sepas. No te preocupes por ser preciso.', 'Dimensions, context, anything you know. No need to be precise.')}/>
              </Field>

              <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', padding: '16px 24px' }}>
                {sent
                  ? t('✓ Abriendo WhatsApp — envíalo y te contestamos', '✓ Opening WhatsApp — send it and we reply')
                  : t('Enviar por WhatsApp', 'Send via WhatsApp')}
                {!sent && (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.002-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                )}
              </button>
              <p className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.4)', textAlign: 'center', marginTop: 4 }}>
                {t('AL ENVIAR ABRIMOS WHATSAPP CON TUS DATOS PRE-LLENADOS. NO COMPARTIMOS TU INFORMACIÓN.', 'SUBMITTING OPENS WHATSAPP WITH YOUR DATA PRE-FILLED. WE DO NOT SHARE YOUR INFO.')}
              </p>
            </div>
          </form>
        </div>
      </div>

      <style>{`
        #contacto input, #contacto select, #contacto textarea {
          width: 100%;
          background: rgba(255,255,255,0.03);
          border: 1px solid rgba(255,255,255,0.15);
          color: #fff;
          padding: 12px 14px;
          font-family: inherit;
          font-size: 14px;
          outline: none;
          transition: border-color 150ms;
        }
        #contacto input::placeholder, #contacto textarea::placeholder { color: rgba(255,255,255,0.3); }
        #contacto input:focus, #contacto select:focus, #contacto textarea:focus { border-color: rgba(255,255,255,0.6); }
        @media (max-width: 900px) {
          .contact-grid { grid-template-columns: 1fr !important; gap: 56px !important; }
        }
      `}</style>
    </section>
  );
};

const Field = ({ label, children }) => (
  <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.1em' }}>{label}</span>
    {children}
  </label>
);

window.Contact = Contact;
