/* ============================================================
 *  BOOKING MODAL — reserva de llamada con api.blackstock.es
 *
 *  API:  GET  /api/public/call-slots?date=YYYY-MM-DD
 *        POST /api/public/call-bookings
 *
 *  Flujo:
 *   1. Form: nombre / email / teléfono / plan / experiencia / volumen / mensaje
 *   2. Calendario: 14 días + grid de slots 16:00–22:00 Europe/Madrid
 *   3. Confirmar: POST → 409 si slot ocupado, 200 si OK
 *   4. Pantalla "reservado" con resumen
 *
 *  window.bsOpenBooking(planHint?) abre el modal con plan precargado.
 * ============================================================ */

const BS_BOOKING_API_BASE = 'https://api.blackstock.es';

const BookingModal = () => {
  const [open, setOpen] = React.useState(false);
  const [step, setStep] = React.useState(1); // 1 form, 2 slot, 3 done
  const [planHint, setPlanHint] = React.useState(null);

  // Form fields
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [plan, setPlan] = React.useState('basic');
  const [experience, setExperience] = React.useState('');
  const [volume, setVolume] = React.useState('');
  const [message, setMessage] = React.useState('');

  // Slot picker
  const [slotsMeta, setSlotsMeta] = React.useState(null);
  const [selectedDate, setSelectedDate] = React.useState('');
  const [slotsForDate, setSlotsForDate] = React.useState(null);
  const [selectedTime, setSelectedTime] = React.useState('');

  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [confirmation, setConfirmation] = React.useState(null);

  React.useEffect(() => {
    window.bsOpenBooking = (hint) => {
      setOpen(true);
      setStep(1);
      setError('');
      setConfirmation(null);
      const norm = String(hint || '').trim().toLowerCase();
      if (norm === 'pro' || norm === 'basic') {
        setPlan(norm);
        setPlanHint(norm.toUpperCase());
      } else {
        setPlanHint(null);
      }
    };
    window.bsCloseBooking = () => setOpen(false);
    return () => {
      delete window.bsOpenBooking;
      delete window.bsCloseBooking;
    };
  }, []);

  // ESC + body lock
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [open]);

  // Cargar disponibilidad cuando entras al paso 2
  React.useEffect(() => {
    if (step !== 2) return;
    let cancelled = false;
    setSlotsMeta(null);
    fetch(`${BS_BOOKING_API_BASE}/api/public/call-slots`, { credentials: 'omit' })
      .then((r) => r.json())
      .then((j) => {
        if (cancelled) return;
        if (!j?.ok) throw new Error('slots_failed');
        setSlotsMeta(j);
        const firstFree = (j.days || []).find((d) => d.freeCount > 0);
        if (firstFree && !selectedDate) setSelectedDate(firstFree.date);
      })
      .catch(() => { if (!cancelled) setError('No pudimos cargar la disponibilidad. Inténtalo de nuevo.'); });
    return () => { cancelled = true; };
  }, [step]);

  React.useEffect(() => {
    if (step !== 2 || !selectedDate) return;
    let cancelled = false;
    setSlotsForDate(null);
    setSelectedTime('');
    fetch(`${BS_BOOKING_API_BASE}/api/public/call-slots?date=${selectedDate}`, { credentials: 'omit' })
      .then((r) => r.json())
      .then((j) => { if (!cancelled && j?.ok) setSlotsForDate(j.slots || []); })
      .catch(() => {});
    return () => { cancelled = true; };
  }, [step, selectedDate]);

  if (!open) return null;

  const validateStep1 = () => {
    if (name.trim().length < 2) return 'Tu nombre es obligatorio.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return 'Email no válido.';
    if (phone.replace(/\D/g, '').length < 6) return 'Introduce un teléfono válido.';
    if (experience.trim().length < 4) return 'Cuéntanos un poco tu experiencia (1-2 frases).';
    if (volume.trim().length < 1) return 'Indica un volumen aproximado.';
    return '';
  };

  const handleNextFromForm = () => {
    const err = validateStep1();
    if (err) { setError(err); return; }
    setError('');
    setStep(2);
  };

  const handleSubmit = async () => {
    if (!selectedDate || !selectedTime) {
      setError('Selecciona día y hora.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`${BS_BOOKING_API_BASE}/api/public/call-bookings`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'omit',
        body: JSON.stringify({
          name: name.trim(),
          email: email.trim().toLowerCase(),
          phone: phone.trim(),
          plan,
          experience: experience.trim(),
          volume: volume.trim(),
          message: message.trim(),
          date: selectedDate,
          time: selectedTime,
          source: 'mobiles.blackstock.es',
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data?.ok) {
        if (data?.error === 'slot_taken') {
          setError('Esa hora ya se acaba de reservar. Elige otra disponible.');
          // refrescar slots
          const j = await fetch(`${BS_BOOKING_API_BASE}/api/public/call-slots?date=${selectedDate}`).then((r) => r.json());
          if (j?.ok) setSlotsForDate(j.slots || []);
          setSelectedTime('');
        } else {
          setError('No pudimos completar la reserva. Revisa los datos o inténtalo en unos minutos.');
        }
        setLoading(false);
        return;
      }
      setConfirmation(data.booking);
      setStep(3);
      setLoading(false);
    } catch (e) {
      setError('Error de red. Inténtalo de nuevo.');
      setLoading(false);
    }
  };

  const formatDayLabel = (ymd) => {
    if (!ymd) return '';
    const [y, m, d] = ymd.split('-').map(Number);
    const date = new Date(Date.UTC(y, m - 1, d, 12, 0, 0));
    return new Intl.DateTimeFormat('es-ES', {
      timeZone: 'Europe/Madrid', weekday: 'short', day: 'numeric', month: 'short',
    }).format(date);
  };

  return (
    <div className="bs-modal-overlay bs-booking-overlay" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
      <div className="bs-modal-card bs-booking-card" role="dialog" aria-modal="true" aria-label="Reserva de llamada">
        <button type="button" className="bs-modal-close" aria-label="Cerrar" onClick={() => setOpen(false)}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
        </button>

        {/* Header */}
        <div className="bs-booking-head">
          <div className="bs-brand-mark">
            <svg width="14" height="14" viewBox="0 0 128 128" fill="none">
              <g fill="var(--acid)">
                <path d="M64 14 92 31.5V43L64 26.5 36 43V31.5L64 14Z" />
                <path d="M64 38 99 59.5V72L64 51.5 29 72V59.5L64 38Z" />
                <path d="M64 64 104 87.5V100L64 76.5 24 100V87.5L64 64Z" />
              </g>
            </svg>
          </div>
          <div>
            <div className="kicker">{planHint ? `Plan ${planHint}` : 'Acceso bajo llamada'}</div>
            <div className="title">Agenda una llamada con Blackstock</div>
          </div>
        </div>

        {/* Progress dots */}
        <div className="bs-booking-progress">
          {[1, 2, 3].map((n) => (
            <span key={n} className={`dot ${step >= n ? 'is-on' : ''} ${step === n ? 'is-current' : ''}`} />
          ))}
        </div>

        {step === 1 && (
          <div className="bs-booking-form">
            {/* Honeypot anti-spam */}
            <input type="text" name="website" tabIndex="-1" autoComplete="off" style={{ position: 'absolute', left: -9999, opacity: 0 }} />

            <div className="bs-grid-2">
              <label className="bs-field">
                <span>Nombre</span>
                <input
                  type="text" placeholder="Tu nombre"
                  value={name} onChange={(e) => setName(e.target.value)}
                  disabled={loading}
                  autoCapitalize="words" autoComplete="name"
                />
              </label>
              <label className="bs-field">
                <span>Email</span>
                <input
                  type="email" placeholder="tu@email.com"
                  value={email} onChange={(e) => setEmail(e.target.value)}
                  disabled={loading}
                  inputMode="email" autoComplete="email" autoCapitalize="off" autoCorrect="off"
                />
              </label>
            </div>

            <label className="bs-field">
              <span>Teléfono</span>
              <input
                type="tel" placeholder="+34 600 000 000"
                value={phone} onChange={(e) => setPhone(e.target.value)}
                disabled={loading}
                inputMode="tel" autoComplete="tel"
              />
            </label>

            <div className="bs-field">
              <span>Plan que te interesa</span>
              <div className="bs-booking-plan-toggle">
                {[
                  { c: 'basic', n: 'BASIC', s: 'Todo Blackstock · 22,90€/mes' },
                  { c: 'pro', n: 'PRO', s: 'BASIC + Bazooka · 149,90€/mes', badge: 'incluye Bazooka' },
                ].map((p) => (
                  <button
                    key={p.c}
                    type="button"
                    className={`bs-booking-plan ${plan === p.c ? 'is-on' : ''}`}
                    onClick={() => setPlan(p.c)}
                  >
                    <div className="t">
                      <span className="n">{p.n}</span>
                      {p.badge && <span className="b">{p.badge}</span>}
                    </div>
                    <div className="s">{p.s}</div>
                  </button>
                ))}
              </div>
            </div>

            <label className="bs-field">
              <span>Experiencia vendiendo en Vinted</span>
              <input
                type="text"
                placeholder="Ej. llevo 6 meses, ~50 ventas"
                value={experience}
                onChange={(e) => setExperience(e.target.value)}
                disabled={loading}
              />
            </label>

            <label className="bs-field">
              <span>Volumen actual aproximado</span>
              <input
                type="text"
                placeholder="Ej. 300€/mes, sin volumen aún…"
                value={volume}
                onChange={(e) => setVolume(e.target.value)}
                disabled={loading}
              />
            </label>

            <label className="bs-field">
              <span>Mensaje <small>(opcional)</small></span>
              <textarea
                rows="3"
                placeholder="Algo que debamos saber antes de la llamada"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                disabled={loading}
              />
            </label>

            {error && <div className="bs-modal-error">{error}</div>}

            <button type="button" className="bs-btn bs-btn-acid bs-btn-block" onClick={handleNextFromForm}>
              Elegir día y hora →
            </button>
            <p className="bs-modal-fineprint">
              Te ayudamos a elegir plan en una llamada. Sin pasarela de pago, sin compromiso.
            </p>
          </div>
        )}

        {step === 2 && (
          <div className="bs-booking-slot">
            <div className="bs-booking-slot-head">
              <span className="kicker">Tarde · Europe/Madrid</span>
              <span className="meta">Próximas 2 semanas · 16:00 a 22:00</span>
            </div>

            {!slotsMeta ? (
              <div className="bs-booking-skeleton">
                {Array.from({ length: 6 }).map((_, i) => <span key={i} />)}
              </div>
            ) : (
              <div className="bs-booking-days" role="tablist" aria-label="Día">
                {(slotsMeta.days || []).map((d) => (
                  <button
                    key={d.date}
                    type="button"
                    role="tab"
                    aria-selected={selectedDate === d.date}
                    className={`day ${selectedDate === d.date ? 'is-on' : ''} ${d.freeCount === 0 ? 'is-full' : ''}`}
                    onClick={() => d.freeCount > 0 && setSelectedDate(d.date)}
                    disabled={d.freeCount === 0}
                  >
                    <span className="lbl">{formatDayLabel(d.date)}</span>
                    <span className="num">{d.freeCount === 0 ? 'Lleno' : `${d.freeCount} libre${d.freeCount === 1 ? '' : 's'}`}</span>
                  </button>
                ))}
              </div>
            )}

            <div className="bs-booking-slot-grid-wrap">
              <span className="kicker">Hora</span>
              {!slotsForDate ? (
                <div className="bs-booking-skeleton bs-booking-skeleton-grid">
                  {Array.from({ length: 6 }).map((_, i) => <span key={i} />)}
                </div>
              ) : (
                <div className="bs-booking-slot-grid">
                  {slotsForDate.map((s) => (
                    <button
                      key={s.time}
                      type="button"
                      className={`slot ${s.status} ${selectedTime === s.time ? 'is-on' : ''}`}
                      disabled={s.status !== 'free'}
                      onClick={() => setSelectedTime(s.time)}
                    >
                      {s.time}
                      {s.status === 'taken' && <span className="x">Reservado</span>}
                      {s.status === 'past' && <span className="x">Pasado</span>}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {error && <div className="bs-modal-error">{error}</div>}

            <div className="bs-booking-actions">
              <button type="button" className="bs-btn bs-btn-ghost" onClick={() => setStep(1)} disabled={loading}>← Volver</button>
              <button
                type="button"
                className="bs-btn bs-btn-acid"
                onClick={handleSubmit}
                disabled={loading || !selectedDate || !selectedTime}
              >
                {loading ? <span className="bs-spinner" /> : null}
                {loading ? 'Reservando…' : 'Reservar llamada →'}
              </button>
            </div>
          </div>
        )}

        {step === 3 && confirmation && (
          <div className="bs-booking-done">
            <div className="bs-booking-check">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                <path d="M5 12l5 5L20 7" stroke="#0a0b07" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div className="kicker">Llamada confirmada</div>
            <div className="bs-booking-when">{confirmation.pretty}</div>
            <div className="bs-booking-tz">Europe/Madrid</div>
            <div className="bs-booking-summary">
              <div className="row"><span>Plan</span><strong>{confirmation.plan}{confirmation.bazooka ? ' · incluye Bazooka' : ''}</strong></div>
              <div className="row"><span>Te llamaremos a</span><strong>{phone || email}</strong></div>
            </div>
            <p className="bs-modal-fineprint">
              Te hemos enviado la confirmación por email. Si necesitas reorganizar, responde a ese correo.
            </p>
            <button type="button" className="bs-btn bs-btn-acid bs-btn-block" onClick={() => setOpen(false)}>
              Cerrar
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

window.BsBookingModal = BookingModal;
