const { useState } = React;

function ConfirmModal({ open, onClose }) {
  const [form, setForm] = useState({
    nombre: '', apellidos: '', empresa: '', cargo: '', email: '',
    interests: [], lunch: null, extra: '', consent: false
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  if (!open) return null;

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleInterest = (x) => {
    const has = form.interests.includes(x);
    set('interests', has ? form.interests.filter(i => i !== x) : [...form.interests, x]);
  };

  const validate = () => {
    const e = {};
    if (!form.nombre.trim()) e.nombre = 'Requerido';
    if (!form.apellidos.trim()) e.apellidos = 'Requerido';
    if (!form.empresa.trim()) e.empresa = 'Requerido';
    if (!form.email.trim()) e.email = 'Requerido';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Email no válido';
    if (form.lunch === null) e.lunch = 'Indica si acudirás';
    if (!form.consent) e.consent = 'Debes aceptar la política';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setSubmitted(true);
  };

  const close = () => {
    setSubmitted(false);
    setForm({ nombre: '', apellidos: '', empresa: '', cargo: '', email: '', interests: [], lunch: null, extra: '', consent: false });
    setErrors({});
    onClose();
  };

  return (
    <div className="modal-scrim" onClick={(e) => { if (e.target.classList.contains('modal-scrim')) close(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <button className="close" onClick={close} aria-label="Cerrar">✕</button>

        {submitted ? (
          <div className="success">
            <div className="big-num">✓</div>
            <h4>Tu asistencia está confirmada</h4>
            <p>
              Te hemos enviado una copia de tu inscripción a <strong>{form.email}</strong>.
              Recibirás un recordatorio con los detalles unos días antes del evento.
            </p>
            <div style={{display:'flex', justifyContent:'center', gap: 10}}>
              <button className="btn btn-primary" onClick={close}>Volver a la invitación</button>
              <a
                className="btn btn-ghost"
                href={buildIcs()}
                download="spring-meeting-2026.ics"
              >
                Añadir al calendario
              </a>
            </div>
            <div className="mono" style={{fontSize: 10, color:'var(--ink-4)', marginTop: 28, letterSpacing: '0.08em', textTransform: 'uppercase'}}>
              ID de confirmación · SM-2026-{Math.random().toString(36).slice(2, 8).toUpperCase()}
            </div>
          </div>
        ) : (
          <form onSubmit={submit} noValidate>
            <h3>Confirmar asistencia</h3>
            <p className="lede">Estamos deseando vernos en persona y poder disfrutar juntos de este evento.</p>

            <div className="form-grid">
              <div className="field">
                <label>Nombre</label>
                <input className={errors.nombre ? 'error' : ''} value={form.nombre} onChange={e => set('nombre', e.target.value)} />
                {errors.nombre && <span className="err">{errors.nombre}</span>}
              </div>
              <div className="field">
                <label>Apellidos</label>
                <input className={errors.apellidos ? 'error' : ''} value={form.apellidos} onChange={e => set('apellidos', e.target.value)} />
                {errors.apellidos && <span className="err">{errors.apellidos}</span>}
              </div>
              <div className="field">
                <label>Empresa / Institución</label>
                <input className={errors.empresa ? 'error' : ''} value={form.empresa} onChange={e => set('empresa', e.target.value)} />
                {errors.empresa && <span className="err">{errors.empresa}</span>}
              </div>
              <div className="field">
                <label>Cargo</label>
                <input value={form.cargo} onChange={e => set('cargo', e.target.value)} />
              </div>
              <div className="field full">
                <label>Email</label>
                <input type="email" className={errors.email ? 'error' : ''} value={form.email} onChange={e => set('email', e.target.value)} />
                {errors.email && <span className="err">{errors.email}</span>}
              </div>

              <div className="field full">
                <label>¿Qué te interesa? · Selecciona una o varias</label>
                <div className="interests">
                  {INTERESTS.map(i => (
                    <button
                      key={i}
                      type="button"
                      className={form.interests.includes(i) ? 'on' : ''}
                      onClick={() => toggleInterest(i)}
                    >
                      {i}
                    </button>
                  ))}
                </div>
              </div>

              <div className="field full">
                <label>¿Acudirás al almuerzo?</label>
                <div className="lunch-toggle">
                  <button type="button" className={form.lunch === true ? 'on' : ''} onClick={() => set('lunch', true)}>
                    Sí, asistiré al almuerzo
                  </button>
                  <button type="button" className={form.lunch === false ? 'on' : ''} onClick={() => set('lunch', false)}>
                    No podré quedarme
                  </button>
                </div>
                {errors.lunch && <span className="err">{errors.lunch}</span>}
              </div>

              <div className="field full">
                <label>Información adicional · Intolerancias, alergias, accesibilidad</label>
                <textarea
                  value={form.extra}
                  onChange={e => set('extra', e.target.value)}
                  placeholder="Opcional"
                />
              </div>

              <label className="consent full">
                <input type="checkbox" checked={form.consent} onChange={e => set('consent', e.target.checked)} />
                <span>
                  Acepto el tratamiento de mis datos conforme a la{' '}
                  <a href="privacidad.html" target="_blank">política de privacidad</a> y cláusulas
                  adicionales de IR Soluciones, incluyendo los derechos de imagen del evento.
                  {errors.consent && <span className="err" style={{display:'block', marginTop: 4}}>{errors.consent}</span>}
                </span>
              </label>
            </div>

            <div className="modal-actions">
              <div className="meta">{form.interests.length} interés{form.interests.length === 1 ? '' : 'es'} · Todos los campos marcados son obligatorios</div>
              <button className="btn btn-primary" type="submit">
                Confirmar <span className="arrow">→</span>
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function buildIcs() {
  const dt = (d) => d.toISOString().replace(/[-:]/g,'').replace(/\.\d{3}/,'');
  const start = new Date("2026-05-14T08:00:00Z"); // 10:00 CEST → 08:00 UTC
  const end = new Date("2026-05-14T14:00:00Z");   // 16:00 CEST → 14:00 UTC
  const ics = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//IR Soluciones//Spring Meeting//ES',
    'BEGIN:VEVENT',
    `UID:spring-meeting-2026@irsoluciones.com`,
    `DTSTAMP:${dt(new Date())}`,
    `DTSTART:${dt(start)}`,
    `DTEND:${dt(end)}`,
    'SUMMARY:IV Spring Meeting · IR Soluciones',
    'LOCATION:Edificio Circular Universe\\, C/ Valdegastea 2\\, Logroño',
    'DESCRIPTION:Impulsando tecnológicamente la empresa del futuro.',
    'END:VEVENT',
    'END:VCALENDAR'
  ].join('\r\n');
  return 'data:text/calendar;charset=utf-8,' + encodeURIComponent(ics);
}

window.ConfirmModal = ConfirmModal;
window.buildIcs = buildIcs;
