// booking.jsx — multi-step booking modal

const { useState, useEffect, useMemo } = React;

function BookingModal({ open, onClose, initialService, initialBarber }) {
  const [step, setStep] = useState(0);
  const [service, setService] = useState(initialService || null);
  const [barber, setBarber] = useState(initialBarber || null);
  const [assignedBarber, setAssignedBarber] = useState(null);
  const [date, setDate] = useState(null);
  const [time, setTime] = useState(null);
  const [form, setForm] = useState({ name: '', phone: '', notes: '' });
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [checking, setChecking] = useState(false);
  const [notice, setNotice] = useState('');
  const [slotAvailability, setSlotAvailability] = useState({});

  useEffect(() => {
    if (open) {
      setStep(0);
      setService(initialService || null);
      setBarber(initialBarber || null);
      setDate(null);
      setTime(null);
      setForm({ name: '', phone: '', notes: '' });
      setSubmitted(false);
      setNotice('');
    }
  }, [open, initialService, initialBarber]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && open) onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const steps = ['Servicio', 'Barbero', 'Fecha y hora', 'Tus datos', 'Confirmar'];

  const canNext = (() => {
    if (step === 0) return !!service;
    if (step === 1) return !!barber;
    if (step === 2) return !!date && !!time;
    if (step === 3) {
  console.log('name:', form.name.trim().length, 'phone:', form.phone.trim().length, 'consent:', form.consent);
  return form.name.trim().length > 1 && form.phone.trim().length > 8 && form.consent === true;
}
    return true;
  })();

  const hint = (() => {
    if (sending || checking) return '';
    if (step === 2 && !canNext) return !date ? 'Elegí un día para ver los horarios disponibles.' : 'Elegí un horario disponible para continuar.';
    if (step === 3 && !canNext) {
      const faltan = [];
      if (form.name.trim().length < 2) faltan.push('tu nombre');
      if (form.phone.trim().length < 9) faltan.push('tu teléfono (con código de área)');
      if (form.consent !== true) faltan.push('tildar la casilla de consentimiento');
      return faltan.length ? 'Falta: ' + faltan.join(', ') + '.' : '';
    }
    return '';
  })();

  const totalPrice = service?.price || 0;

  const fmtDate = (d) => {
    if (!d) return '—';
    return d.toLocaleDateString('es-AR', { weekday: 'long', day: 'numeric', month: 'long' });
  };

  const summaryText = (() => {
    if (!service && !barber) return null;
    const bits = [];
    if (service) bits.push(service.name);
    if (barber) bits.push('con ' + barber.name.split(' ')[0]);
    return bits.join(' · ');
  })();

const slotStillFree = async () => {
  try {
    const pad = (n) => String(n).padStart(2, '0');
    const fecha = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    const res = await fetch('https://pxtqhrisugkmvvcoumfa.supabase.co/rest/v1/rpc/horarios_ocupados', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'apikey': 'sb_publishable_Min_-LzbhUQRZ4hQlOYn3g_8lrZqKMw', 'Authorization': 'Bearer sb_publishable_Min_-LzbhUQRZ4hQlOYn3g_8lrZqKMw' },
      body: JSON.stringify({ p_fecha: fecha })
    });
    const rows = await res.json();
    if (!Array.isArray(rows)) return true;
    const hhmm = (iso) => new Date(iso).toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'America/Argentina/Buenos_Aires' });
    const busy = rows.filter(r => hhmm(r.date_start) === time).map(r => r.peluquero_id);
    if (barber?.name === 'Fede') return !busy.includes(1);
    if (barber?.name === 'Tobi') return !busy.includes(2);
    return !(busy.includes(1) && busy.includes(2));
  } catch (e) {
    return true;
  }
};

const goNext = async () => {
  if (step === 2) {
    setChecking(true);
    const libre = await slotStillFree();
    setChecking(false);
    if (!libre) {
      setNotice('Ese horario se acaba de ocupar. Elegí otro.');
      setTime(null);
      setDate(new Date(date.getTime()));
      return;
    }
  }
  setNotice('');
  setStep(s => s + 1);
};

const submit = async () => {
  if (sending) return;
  setSending(true);
  setNotice('');
  try {
    const pad = (n) => String(n).padStart(2, '0');
    const fecha = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    const peluqueroId = barber?.name === 'Fede' ? 1 : barber?.name === 'Tobi' ? 2 : null;

    const response = await fetch('/api/reservar', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        nombre: form.name,
        telefono: form.phone,
        fecha: fecha,
        hora: time,
        servicio: service?.name || '',
        notas: form.notes || '',
        peluquero_id: peluqueroId
      })
    });
    const result = await response.json().catch(() => null);

    if (response.ok && result && result.ok) {
      setSubmitted(true);
      setStep(4);
    } else if (result && result.motivo === 'horario_ocupado') {
      setNotice(result.mensaje);
      setTime(null);
      setStep(2);
    } else if (result && result.mensaje) {
      setNotice(result.mensaje);
    } else {
      setNotice('Hubo un error al confirmar la reserva. Por favor intentá de nuevo.');
    }
  } catch (err) {
    setNotice('Error de conexión. Por favor intentá de nuevo.');
  } finally {
    setSending(false);
  }
};

 return (
    <div className="modal-back" onClick={(e) => { if (e.target.classList.contains('modal-back')) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-head">
          <h3>{submitted ? 'Reserva confirmada' : 'Reservar turno'}</h3>
          <button className="modal-close" onClick={onClose} aria-label="Cerrar">✕</button>
        </div>

        {!submitted && (
          <div className="steps-strip">
            {steps.slice(0, 4).map((s, i) => (
              <div key={s} className={`step-pip ${i === step ? 'active' : ''} ${i < step ? 'done' : ''}`}>
                <div className="pip"></div>
                <div className="lbl">{String(i + 1).padStart(2, '0')} · {s}</div>
              </div>
            ))}
          </div>
        )}

        <div className="modal-body">
          {step === 0 && (
            <ServiceStep selected={service} onSelect={setService} />
          )}
          {step === 1 && (
            <BarberStep selected={barber} onSelect={setBarber} />
          )}
          {step === 2 && (
            <DateStep date={date} time={time} onDate={(d) => { setNotice(''); setDate(d); }} onTime={(t) => { setNotice(''); setTime(t); }} barber={barber} onSlotAvailability={setSlotAvailability} />
          )}
          {step === 3 && (
            <DetailsStep form={form} onChange={setForm} service={service} barber={barber} date={date} time={time} total={totalPrice} fmtDate={fmtDate} slotAvailability={slotAvailability} />
          )}
{step === 4 && (
  <SuccessStep service={service} barber={barber} date={date} time={time} form={form} fmtDate={fmtDate} onClose={onClose} slotAvailability={slotAvailability} />
)}
        </div>

        {notice && !submitted && (
          <div role="alert" style={{ margin: '0 24px 12px', padding: '10px 14px', borderRadius: 8, background: 'rgba(224, 85, 85, 0.12)', border: '1px solid rgba(224, 85, 85, 0.45)', fontSize: 14, lineHeight: 1.4 }}>
            {notice}
          </div>
        )}
        {!submitted && !notice && hint && (
          <div style={{ margin: '0 24px 12px', fontSize: 13, color: 'var(--muted)' }}>{hint}</div>
        )}
        {!submitted && (
          <div className="modal-foot">
            <div className="summary">
              {summaryText
                ? <span><strong>{service?.name || ''}</strong>{barber ? ' · ' + barber.name.split(' ')[0] : ''}{date ? ' · ' + date.toLocaleDateString('es-AR', { day: 'numeric', month: 'short' }) : ''}{time ? ' · ' + time : ''}</span>
                : <span>Elegí tu servicio para empezar</span>}
              {totalPrice ? <span> · <strong>${totalPrice.toLocaleString('es-AR')}</strong></span> : null}
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              {step > 0 && (
                <button className="btn btn-ghost btn-sm" onClick={() => { setNotice(''); setStep(s => s - 1); }}>← Atrás</button>
              )}
              {step < 3 && (
                <button className="btn btn-primary btn-sm" disabled={!canNext || checking} onClick={goNext} style={{ opacity: (canNext && !checking) ? 1 : 0.4 }}>
                  {checking ? 'Verificando…' : 'Continuar'} <span className="arrow">→</span>
                </button>
              )}
              {step === 3 && (
                <button className="btn btn-primary btn-sm" disabled={!canNext || sending} onClick={submit} style={{ opacity: (canNext && !sending) ? 1 : 0.4 }}>
                  {sending ? 'Confirmando…' : 'Confirmar reserva'} <span className="arrow">→</span>
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );;
}

function ServiceStep({ selected, onSelect }) {
  return (
    <div>
      <div className="step-title">¿Qué te hacemos hoy?</div>
      <div className="step-desc">Elegí el servicio. Podés agregar extras al final.</div>
      <div className="choice-grid">
        {SERVICES.map(s => (
          <button key={s.id} className={`choice ${selected?.id === s.id ? 'selected' : ''}`} onClick={() => onSelect(s)}>
            <div className="choice-row-inner">
              <div className="ch-name">{s.name}</div>
              <div className="ch-meta">{s.time}</div>
            </div>
            <div className="ch-price">${s.price.toLocaleString('es-AR')}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

function BarberStep({ selected, onSelect }) {
  const all = [{ id: 'any', name: 'Cualquier disponible', role: 'Más rápido', initials: '—', rating: '' }, ...BARBERS];
  return (
    <div>
      <div className="step-title">Elegí tu barbero</div>
      <div className="step-desc">Todos están avalados. Si te da igual, dale al primero — te asignamos el que antes se libere.</div>
      <div className="choice-grid">
        {all.map(b => (
          <button key={b.id} className={`choice ${selected?.id === b.id ? 'selected' : ''}`} onClick={() => onSelect(b)}>
            <div className="ch-avatar">{b.initials}</div>
            <div className="choice-row-inner">
              <div className="ch-name">{b.name}</div>
              <div className="ch-meta">{b.role}{b.rating ? ' · ★ ' + b.rating : ''}</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function DateStep({ date, time, onDate, onTime, barber, onSlotAvailability }) {
  const today = new Date();
  const [viewMonth, setViewMonth] = useState(new Date(today.getFullYear(), today.getMonth(), 1));
  const [bookedSlots, setBookedSlots] = useState(new Set());
  const [loadingSlots, setLoadingSlots] = useState(false);

  const monthName = viewMonth.toLocaleDateString('es-AR', { month: 'long', year: 'numeric' });
  const firstDay = (viewMonth.getDay() + 6) % 7;
  const daysInMonth = new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 0).getDate();

  const cells = [];
  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(viewMonth.getFullYear(), viewMonth.getMonth(), d));

  const isPast = (d) => {
    if (!d) return true;
    const t = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    return d < t;
  };
  const isMonday = (d) => d && d.getDay() === 1;
  const isSunday = (d) => d && d.getDay() === 0;
  const isToday = (d) => d && d.toDateString() === today.toDateString();
  const isSelected = (d) => d && date && d.toDateString() === date.toDateString();

  const slots = ['08:30','09:30','10:30','11:30','12:30','13:30','14:30','15:30','16:30','17:30','18:30','19:30'];

  useEffect(() => {
    if (!date) return;
    fetchBookedSlots();
  }, [date, barber]);

const fetchBookedSlots = async () => {
  setLoadingSlots(true);
  const y = date.getFullYear();
  const mo = String(date.getMonth()+1).padStart(2,'0');
  const dd = String(date.getDate()).padStart(2,'0');
  const start = `${y}-${mo}-${dd}T00:00:00-03:00`;
  const end = `${y}-${mo}-${dd}T23:59:59-03:00`;

  const headers = {
    'apikey': 'sb_publishable_Min_-LzbhUQRZ4hQlOYn3g_8lrZqKMw',
    'Authorization': 'Bearer sb_publishable_Min_-LzbhUQRZ4hQlOYn3g_8lrZqKMw'
  };

  const res = await fetch('https://pxtqhrisugkmvvcoumfa.supabase.co/rest/v1/rpc/horarios_ocupados', {
    method: 'POST',
    headers: { ...headers, 'Content-Type': 'application/json' },
    body: JSON.stringify({ p_fecha: `${y}-${mo}-${dd}` })
  });
  const data = await res.json();

  const fedeBusy = new Set();
  const tobiBusy = new Set();

  data.forEach(a => {
    const slotHour = new Date(a.date_start).toLocaleTimeString('es-AR', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false,
      timeZone: 'America/Argentina/Buenos_Aires'
    });
    if (a.peluquero_id === 1) fedeBusy.add(slotHour);
    if (a.peluquero_id === 2) tobiBusy.add(slotHour);
  });

  const booked = new Set();

  if (barber?.name === 'Fede') {
    fedeBusy.forEach(t => booked.add(t));
  } else if (barber?.name === 'Tobi') {
    tobiBusy.forEach(t => booked.add(t));
  } else {
    slots.forEach(t => {
      if (fedeBusy.has(t) && tobiBusy.has(t)) booked.add(t);
    });
  }

  setBookedSlots(booked);

  // Calcular peluquero disponible por slot para "Cualquier disponible"
  console.log('barber id:', barber?.id, 'onSlotAvailability:', !!onSlotAvailability);
  if (barber?.id === 'any' && onSlotAvailability) {
    const availability = {};
    slots.forEach(t => {
      if (!fedeBusy.has(t)) availability[t] = 'Fede';
      else if (!tobiBusy.has(t)) availability[t] = 'Tobi';
      else availability[t] = null;
    });
    console.log('availability:', availability);
    onSlotAvailability(availability);
  }
  setLoadingSlots(false);
};

  const isUnavailable = (t) => {
    if (bookedSlots.has(t)) return true;
    if (date?.toDateString() === today.toDateString()) {
      const [h, m] = t.split(':');
      const slotTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), parseInt(h), parseInt(m));
      const minTime = new Date(today.getTime() + 45 * 60000);
      if (slotTime <= minTime) return true;
    }
    return false;
  };

  const morning = slots.filter(t => parseInt(t) < 12);
  const afternoon = slots.filter(t => parseInt(t) >= 12 && parseInt(t) < 18);
  const evening = slots.filter(t => parseInt(t) >= 18);

  return (
    <div>
      <div className="step-title">¿Cuándo te viene bien?</div>
      <div className="step-desc">Elegí día y horario. Te lo confirmamos por WhatsApp al toque.</div>

      <div className="cal-head">
        <div className="month">{monthName}</div>
        <div className="cal-nav">
          <button onClick={() => setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth() - 1, 1))}>‹</button>
          <button onClick={() => setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 1))}>›</button>
        </div>
      </div>

      <div className="cal-grid" style={{ marginBottom: 4 }}>
        {['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'].map(d => (
          <div key={d} className="cal-dh">{d}</div>
        ))}
      </div>
      <div className="cal-grid">
        {cells.map((d, i) => d == null ? (
          <div key={'e' + i}></div>
        ) : (
          <button
            key={d.getTime()}
            className={`cal-day ${isSelected(d) ? 'selected' : ''} ${isToday(d) ? 'today' : ''}`}
            disabled={isPast(d) || isMonday(d) || isSunday(d)}
            onClick={() => { onDate(d); onTime(null); }}
          >
            {d.getDate()}
          </button>
        ))}
      </div>

      {date && (
        loadingSlots ? <p style={{marginTop: 24, color: 'var(--muted)', fontFamily: 'JetBrains Mono', fontSize: 12}}>Cargando disponibilidad...</p> :
        <>
          {morning.length > 0 && (
            <div className="slot-section">
              <h5>Mañana</h5>
              <div className="slot-grid">
                {morning.map(t => (
                  <button key={t} className={`slot ${time === t ? 'selected' : ''}`} disabled={isUnavailable(t)} onClick={() => onTime(t)}>{t}</button>
                ))}
              </div>
            </div>
          )}
          {afternoon.length > 0 && (
            <div className="slot-section">
              <h5>Tarde</h5>
              <div className="slot-grid">
                {afternoon.map(t => (
                  <button key={t} className={`slot ${time === t ? 'selected' : ''}`} disabled={isUnavailable(t)} onClick={() => onTime(t)}>{t}</button>
                ))}
              </div>
            </div>
          )}
          {evening.length > 0 && (
            <div className="slot-section">
              <h5>Noche</h5>
              <div className="slot-grid">
                {evening.map(t => (
                  <button key={t} className={`slot ${time === t ? 'selected' : ''}`} disabled={isUnavailable(t)} onClick={() => onTime(t)}>{t}</button>
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}

function DetailsStep({ form, onChange, service, barber, date, time, total, fmtDate, slotAvailability }) {
  const set = (k, v) => onChange({ ...form, [k]: v });

  const assignedBarberName = barber?.id === 'any' ? (slotAvailability?.[time] || 'Cualquier disponible') : barber?.name;

  const fmtDateStr = date ? date.toLocaleDateString('es-AR', { weekday: 'long', day: 'numeric', month: 'long' }) : '';

  return (
    <div>
      <div className="summary-card" style={{ marginTop: 0, marginBottom: 24 }}>
        <h5>Resumen de tu reserva</h5>
        <div className="summary-row">
          <span className="k">Servicio</span>
          <span className="v">{service?.name}</span>
        </div>
        <div className="summary-row">
          <span className="k">Peluquero</span>
          <span className="v">{assignedBarberName}</span>
        </div>
        <div className="summary-row">
          <span className="k">Día</span>
          <span className="v" style={{ textTransform: 'capitalize' }}>{fmtDateStr}</span>
        </div>
        <div className="summary-row">
          <span className="k">Hora</span>
          <span className="v">{time}</span>
        </div>
        <div className="summary-row total">
          <span className="k">Total</span>
          <span className="v">${total?.toLocaleString('es-AR')}</span>
        </div>
      </div>

      <div className="step-title" style={{ fontSize: 18, marginBottom: 6 }}>Tus datos</div>
      <div className="step-desc">Necesitamos tu WhatsApp para confirmarte el turno.</div>

      <div className="field-grid">
        <div className="field">
          <label>Nombre y apellido</label>
          <input
            type="text"
            value={form.name}
            onChange={e => set('name', e.target.value)}
            placeholder="Tu nombre y apellido"
          />
        </div>

        <div className="field">
          <label>WhatsApp (formato internacional)</label>
          <input
            type="tel"
            value={form.phone}
            onChange={e => set('phone', e.target.value)}
            placeholder="+5492614123456"
          />
        </div>

        <div className="field">
          <label>Notas para el peluquero (opcional)</label>
          <textarea value={form.notes} onChange={e => set('notes', e.target.value)} placeholder="Ej: quiero fade bajo, barba corta..." />
        </div>

        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 4 }}>
          <input
            type="checkbox"
            id="consent"
            checked={form.consent || false}
            onChange={e => set('consent', e.target.checked)}
            style={{ marginTop: 3, flexShrink: 0 }}
          />
          <label htmlFor="consent" style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.5, cursor: 'pointer' }}>
            Acepto que mis datos sean almacenados para gestionar mis turnos en Corta. Podés solicitar su eliminación escribiéndonos por WhatsApp.
          </label>
        </div>
      </div>
    </div>
  );
}

function SuccessStep({ service, barber, date, time, form, fmtDate, onClose, slotAvailability }) {
  const barberName = barber?.id === 'any' 
    ? (slotAvailability?.[time] || 'el peluquero disponible')
    : barber?.name.split(' ')[0];

  return (
    <div className="success">
      <div className="success-icon">✓</div>
      <h4>¡Listo, {form.name.split(' ')[0]}!</h4>
<p>Te reservamos {service?.name.toLowerCase()} con {barberName} el {fmtDate(date).replace(',', '')} a las {time}.</p>
<p style={{ fontSize: 12, color: 'var(--muted)', marginTop: 8 }}>
  Te mandamos la confirmación por WhatsApp. Para cancelar o modificar tu turno respondé por ahí mismo.
</p>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
        <a className="btn btn-wa btn-sm" href={`https://wa.me/5493516133670?text=${encodeURIComponent('Hola, acabo de reservar ' + service?.name + ' el ' + fmtDate(date) + ' ' + time)}`} target="_blank" rel="noreferrer">
          Abrir WhatsApp
        </a>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>Cerrar</button>
      </div>
    </div>
  );
}

Object.assign(window, { BookingModal });
