/* global React, Icon, Button, Eyebrow */
/* Shared ContactModal — accessible, stateful, reusable across all pages */

function ContactModal({ onClose }) {
  const [form, setForm] = React.useState({ name: '', email: '', company: '', interest: '' });
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const firstInputRef = React.useRef(null);
  const prevFocusRef = React.useRef(null);

  React.useEffect(() => {
    prevFocusRef.current = document.activeElement;
    firstInputRef.current && firstInputRef.current.focus();
    const handleKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handleKey);
    return () => {
      document.removeEventListener('keydown', handleKey);
      prevFocusRef.current && prevFocusRef.current.focus();
    };
  }, []);

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!form.name || !form.email) return;
    setSending(true);
    setTimeout(() => { setSending(false); setSent(true); }, 1200);
  };

  const labelStyle = { display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--fg2)', marginBottom: 5 };

  return (
    <div id="modal-backdrop" onClick={onClose}
      style={{ position:'fixed',inset:0,zIndex:60,background:'rgba(15,22,24,0.55)',backdropFilter:'blur(6px)',display:'grid',placeItems:'center',animation:'fadeIn 240ms var(--ease-out)' }}>
      <div role="dialog" aria-modal="true" aria-labelledby="modal-title"
        className="modal" onClick={e => e.stopPropagation()}>
        <button type="button" className="modal-close" onClick={onClose} aria-label="Cerrar diálogo">
          <Icon name="arrow-right" size={14} style={{ transform: 'rotate(45deg)' }} />
        </button>
        {sent ? (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ width:56,height:56,borderRadius:999,background:'var(--teal-50)',color:'var(--brand)',display:'grid',placeItems:'center',margin:'0 auto 18px' }}>
              <Icon name="check" size={28} />
            </div>
            <h3 id="modal-title" style={{ fontFamily:'var(--font-heading)',fontSize:26,fontWeight:700,letterSpacing:'-0.025em',margin:'0 0 10px',lineHeight:1.15 }}>¡Listo, te contactamos!</h3>
            <p style={{ color:'var(--fg2)',fontSize:15,lineHeight:1.55,margin:'0 0 24px' }}>Un estratega te escribirá en menos de 24 horas.</p>
            <Button variant="ghost" size="md" onClick={onClose}>Cerrar</Button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} noValidate>
            <Eyebrow>HABLA CON UN ESTRATEGA</Eyebrow>
            <h3 id="modal-title" style={{ fontFamily:'var(--font-heading)',fontSize:28,fontWeight:700,letterSpacing:'-0.025em',margin:'14px 0 10px',lineHeight:1.15 }}>30 minutos. Sin pitch.</h3>
            <p style={{ color:'var(--fg2)',fontSize:15,lineHeight:1.55,margin:'0 0 24px' }}>
              Cuéntanos dónde estás. Te decimos qué solución FRSKO tiene más sentido — trabajemos juntos o no.
            </p>
            <div style={{ marginBottom:12 }}>
              <label htmlFor="modal-name" style={labelStyle}>Nombre *</label>
              <input id="modal-name" ref={firstInputRef} className="modal-input" placeholder="Tu nombre" value={form.name} onChange={set('name')} required aria-required="true" />
            </div>
            <div style={{ marginBottom:12 }}>
              <label htmlFor="modal-email" style={labelStyle}>Email de trabajo *</label>
              <input id="modal-email" className="modal-input" placeholder="tu@empresa.com" type="email" value={form.email} onChange={set('email')} required aria-required="true" />
            </div>
            <div style={{ marginBottom:12 }}>
              <label htmlFor="modal-company" style={labelStyle}>Empresa</label>
              <input id="modal-company" className="modal-input" placeholder="Nombre de tu empresa" value={form.company} onChange={set('company')} />
            </div>
            <div style={{ marginBottom:12 }}>
              <label htmlFor="modal-interest" style={labelStyle}>¿Qué te interesa explorar?</label>
              <select id="modal-interest" className="modal-input" value={form.interest} onChange={set('interest')}>
                <option value="">Selecciona una opción</option>
                <option>Lead Engine AI (B2B leads)</option>
                <option>NeuroCopy Lab (creatividades)</option>
                <option>Content Studio AI (contenido)</option>
                <option>Smart Ads AI (paid)</option>
                <option>SEO Pulse (SEO + IA)</option>
                <option>Bootcamps &amp; Workshops</option>
                <option>Aún no estoy seguro</option>
              </select>
            </div>
            <Button variant="cta" size="lg" icon={sending ? null : 'arrow-right'}
              style={{ width:'100%',justifyContent:'center',marginTop:8,opacity:sending?0.7:1 }}
              disabled={sending}>
              {sending ? 'Enviando…' : 'Solicitar conversación'}
            </Button>
            <p style={{ fontSize:12,color:'var(--fg3)',margin:'14px 0 0',textAlign:'center' }}>
              Respondemos en menos de 24 horas. Sin spam.
            </p>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ContactModal });
