/* Michael Style — Prototype · Booking modal.
   Opened by every website "Book" CTA. Calendar (Tue–Sat 8A–6P) → contact → confirm,
   then simulates a text to the customer and an app notification to the barber.
   Loaded via browser Babel; uses global React + DS namespace. */

const BK = window.MichaelStyleDesignSystem_7fd21b;
const BT = (lang, en, es) => (lang === 'ES' ? es : en);

const BK_MONTHS = {
  EN: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  ES: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
};
const BK_DOW = { EN: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ES: ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'] };
const BK_SLOTS = ['9:00A', '10:00A', '11:00A', '12:00P', '1:00P', '2:00P', '3:00P', '4:00P', '5:00P', '6:00P'];
const BK_SERVICES = {
  EN: ['VIP Cut', 'Cut + Beard + Brows', 'Haircut', 'Beard Design & Cut', 'Line-up / Shape-up', 'Cuts for All Ages', 'Scalp & Beard SMP', 'Eyebrow SMP'],
  ES: ['Corte VIP', 'Corte + Barba + Cejas', 'Corte de Cabello', 'Diseño y Corte de Barba', 'Cerquillo / Perfilado', 'Cortes para Todas las Edades', 'Micropigmentación Capilar y de Barba', 'Micropigmentación de Cejas'],
};

function BookingModal({ open, lang, onClose, onBackToTop, initialSvc }) {
  const [step, setStep] = React.useState(0); // 0 schedule · 1 details · 2 confirmed
  const [svcIdx, setSvcIdx] = React.useState(0);
  const today = React.useMemo(() => { const d = new Date(); d.setHours(0, 0, 0, 0); return d; }, []);
  const [view, setView] = React.useState({ y: today.getFullYear(), m: today.getMonth() });
  const [sel, setSel] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');

  React.useEffect(() => {
    if (open) { setStep(0); setSel(null); setTime(null); setName(''); setPhone(''); setSvcIdx((typeof initialSvc === 'number' && initialSvc >= 0 && initialSvc < BK_SERVICES[lang].length) ? initialSvc : 0); setView({ y: today.getFullYear(), m: today.getMonth() }); }
  }, [open]);

  React.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 firstDow = new Date(view.y, view.m, 1).getDay();
  const daysInMonth = new Date(view.y, view.m + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  const dateOf = (d) => { const dt = new Date(view.y, view.m, d); dt.setHours(0, 0, 0, 0); return dt; };
  const isOpen = (d) => { if (!d) return false; const dt = dateOf(d); const dow = dt.getDay(); return dow >= 2 && dow <= 6 && dt >= today; };
  const isToday = (d) => d && dateOf(d).getTime() === today.getTime();
  const atFloor = view.y === today.getFullYear() && view.m <= today.getMonth();
  const go = (delta) => { let m = view.m + delta, y = view.y; if (m < 0) { m = 11; y--; } if (m > 11) { m = 0; y++; } setView({ y, m }); setSel(null); setTime(null); };
  const selLabel = sel ? `${BK_DOW[lang][dateOf(sel).getDay()]} ${sel} ${BK_MONTHS[lang][view.m]}` : null;
  const phoneOk = phone.replace(/\D/g, '').length >= 10;

  const eyebrow = { fontFamily: 'var(--font-mono)', fontSize: '0.58rem', letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--accent)' };
  const navBtn = (txt, onClick, disabled) => (
    <button onClick={onClick} disabled={disabled} aria-label={txt} style={{
      width: '36px', height: '36px', borderRadius: '50%', cursor: disabled ? 'not-allowed' : 'pointer',
      border: '1px solid var(--bd-d2)', background: 'transparent', color: disabled ? 'var(--muted-2)' : 'var(--bone)',
      fontSize: '1rem', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none',
    }}>{txt}</button>
  );

  return (
    <div role="dialog" aria-modal="true" aria-label={BT(lang, 'Book an appointment', 'Reservar una cita')}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(0,0,0,.72)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '5vh 18px 24px', overflowY: 'auto' }}>
      <div style={{ width: '100%', maxWidth: '560px', background: 'var(--ink-2)', border: '1px solid var(--bd-d2)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-card)', overflow: 'hidden' }}>

        {/* header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px', borderBottom: '1px solid var(--bd-d)' }}>
          <div>
            <div style={eyebrow}>{BT(lang, 'Reservar · Book', 'Reservar · Reserva')}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: '1.35rem', textTransform: 'uppercase', letterSpacing: '-0.03em', color: 'var(--bone)', marginTop: '3px' }}>
              {step === 2 ? BT(lang, "You're booked.", 'Estás reservado.') : BT(lang, 'Book a chair', 'Reserva tu silla')}
            </div>
          </div>
          <button onClick={onClose} aria-label={BT(lang, 'Close', 'Cerrar')} style={{ width: '36px', height: '36px', borderRadius: '50%', border: '1px solid var(--bd-d2)', background: 'transparent', color: 'var(--bone)', fontSize: '1.1rem', cursor: 'pointer', flex: 'none' }}>✕</button>
        </div>

        {/* step indicator */}
        {step < 2 && (
          <div style={{ display: 'flex', gap: '6px', padding: '14px 22px 0' }}>
            {[0, 1].map((i) => (
              <div key={i} style={{ height: '3px', flex: 1, borderRadius: '2px', background: i <= step ? 'var(--accent)' : 'var(--bd-d2)' }} />
            ))}
          </div>
        )}

        <div style={{ padding: '20px 22px 24px' }}>
          {/* STEP 0 — schedule */}
          {step === 0 && (
            <div>
              <label htmlFor="bk-svc" style={{ ...eyebrow, color: 'var(--muted-2)', display: 'block', marginBottom: '9px' }}>{BT(lang, 'Service', 'Servicio')}</label>
              <div style={{ position: 'relative', marginBottom: '20px' }}>
                <select id="bk-svc" value={svcIdx} onChange={(e) => setSvcIdx(Number(e.target.value))} style={{
                  width: '100%', appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
                  fontFamily: 'var(--font-mono)', fontSize: '0.72rem', letterSpacing: '0.06em', textTransform: 'uppercase',
                  padding: '15px 56px 15px 20px', borderRadius: 'var(--radius-pill)',
                  border: '1px solid color-mix(in srgb, var(--accent) 40%, transparent)',
                  background: 'color-mix(in srgb, var(--accent) 9%, var(--card))',
                  color: 'var(--bone)', cursor: 'pointer', outline: 'none',
                }}>
                  {BK_SERVICES[lang].map((s, i) => <option key={s} value={i} style={{ background: 'var(--ink-2)', color: 'var(--bone)', textTransform: 'none' }}>{s}</option>)}
                </select>
                <span style={{ position: 'absolute', right: '7px', top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', width: '32px', height: '32px', borderRadius: '50%', background: 'var(--accent)', color: 'var(--on-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <span style={{ transform: 'rotate(90deg)', display: 'inline-flex' }}><window.Icon name="chevron" size={14} /></span>
                </span>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>
                {navBtn('‹', () => go(-1), atFloor)}
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: '1.1rem', letterSpacing: '-0.02em', color: 'var(--bone)' }}>{`${BK_MONTHS[lang][view.m]} ${view.y}`.toUpperCase()}</div>
                {navBtn('›', () => go(1), false)}
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: '5px', marginBottom: '5px' }}>
                {BK_DOW[lang].map((w, i) => (
                  <div key={i} style={{ textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: '0.5rem', letterSpacing: '0.08em', textTransform: 'uppercase', color: (i >= 2 && i <= 6) ? 'var(--muted)' : 'var(--muted-2)' }}>{w}</div>
                ))}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: '5px' }}>
                {cells.map((d, i) => {
                  if (!d) return <div key={i} />;
                  const open2 = isOpen(d);
                  const on = sel === d;
                  return (
                    <button key={i} disabled={!open2} onClick={() => { setSel(d); setTime(null); }} aria-pressed={on} style={{
                      aspectRatio: '1/1', borderRadius: '11px', cursor: open2 ? 'pointer' : 'not-allowed', position: 'relative',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: '0.86rem', letterSpacing: '-0.02em',
                      border: `1px solid ${on ? 'var(--accent)' : open2 ? 'var(--bd-d2)' : 'transparent'}`,
                      background: on ? 'var(--accent)' : open2 ? 'var(--card)' : 'transparent',
                      color: on ? 'var(--on-accent)' : open2 ? 'var(--bone)' : 'var(--muted-2)', opacity: open2 ? 1 : 0.45,
                    }}>
                      {d}
                      {isToday(d) && !on && <i style={{ position: 'absolute', bottom: '5px', width: '3px', height: '3px', borderRadius: '50%', background: 'var(--accent)' }} />}
                    </button>
                  );
                })}
              </div>

              {sel && (
                <div style={{ marginTop: '18px' }}>
                  <div style={{ ...eyebrow, marginBottom: '10px' }}>{selLabel} · {BT(lang, 'pick a time', 'elige una hora')}</div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(78px,1fr))', gap: '6px' }}>
                    {BK_SLOTS.map((s) => {
                      const on = time === s;
                      return (
                        <button key={s} onClick={() => setTime(s)} aria-pressed={on} style={{
                          fontFamily: 'var(--font-mono)', fontSize: '0.62rem', padding: '10px 4px', borderRadius: 'var(--radius-pill)', cursor: 'pointer',
                          border: `1px solid ${on ? 'var(--accent)' : 'var(--bd-d2)'}`,
                          background: on ? 'var(--accent)' : 'transparent', color: on ? 'var(--on-accent)' : 'var(--bone)',
                        }}>{s}</button>
                      );
                    })}
                  </div>
                </div>
              )}

              <button onClick={() => setStep(1)} disabled={!sel || !time} style={{
                width: '100%', marginTop: '22px', fontFamily: 'var(--font-mono)', fontSize: '0.7rem', letterSpacing: '0.1em', textTransform: 'uppercase',
                padding: '15px', borderRadius: 'var(--radius-pill)', cursor: (sel && time) ? 'pointer' : 'not-allowed',
                border: (sel && time) ? 'none' : '1px solid var(--bd-d)',
                background: (sel && time) ? 'var(--accent)' : 'var(--card)', color: (sel && time) ? 'var(--on-accent)' : 'var(--muted-2)',
              }}>{BT(lang, 'Continue', 'Continuar')}</button>
            </div>
          )}

          {/* STEP 1 — details */}
          {step === 1 && (
            <div>
              <div style={{ background: 'var(--card)', border: '1px solid var(--bd-d)', borderRadius: 'var(--radius-md)', padding: '14px 16px', marginBottom: '20px' }}>
                <div style={{ ...eyebrow, color: 'var(--muted-2)' }}>{BT(lang, 'Your appointment', 'Tu cita')}</div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: '1.05rem', textTransform: 'uppercase', letterSpacing: '-0.02em', color: 'var(--bone)', marginTop: '6px' }}>{BK_SERVICES[lang][svcIdx]}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.66rem', letterSpacing: '0.05em', color: 'var(--accent)', marginTop: '4px' }}>{selLabel} · {time}</div>
              </div>

              <label style={{ ...eyebrow, color: 'var(--muted-2)', display: 'block', marginBottom: '7px' }}>{BT(lang, 'Name', 'Nombre')}</label>
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder={BT(lang, 'Your name', 'Tu nombre')} style={inputStyle} />

              <label style={{ ...eyebrow, color: 'var(--muted-2)', display: 'block', margin: '16px 0 7px' }}>{BT(lang, 'Mobile · for text confirmation', 'Móvil · para confirmación por texto')}</label>
              <input value={phone} onChange={(e) => setPhone(e.target.value)} inputMode="tel" placeholder="(713) 555-0142" style={inputStyle} />

              <div style={{ display: 'flex', alignItems: 'center', gap: '9px', marginTop: '14px', fontSize: '0.66rem', color: 'var(--muted-2)' }}>
                <span style={{ color: 'var(--accent)', flex: 'none' }}><window.Icon name="lock" size={15} /></span>
                {BT(lang, "We'll text you a confirmation and a reminder. No spam.", 'Te enviaremos confirmación y recordatorio por texto. Sin spam.')}
              </div>

              <div style={{ display: 'flex', gap: '9px', marginTop: '22px' }}>
                <button onClick={() => setStep(0)} style={{ flex: '0 0 auto', fontFamily: 'var(--font-mono)', fontSize: '0.66rem', letterSpacing: '0.08em', textTransform: 'uppercase', padding: '15px 18px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--bd-d2)', background: 'transparent', color: 'var(--bone)', cursor: 'pointer' }}>{BT(lang, 'Back', 'Atrás')}</button>
                <button onClick={() => setStep(2)} disabled={!name.trim() || !phoneOk} style={{
                  flex: 1, fontFamily: 'var(--font-mono)', fontSize: '0.7rem', letterSpacing: '0.1em', textTransform: 'uppercase',
                  padding: '15px', borderRadius: 'var(--radius-pill)', cursor: (name.trim() && phoneOk) ? 'pointer' : 'not-allowed',
                  border: (name.trim() && phoneOk) ? 'none' : '1px solid var(--bd-d)',
                  background: (name.trim() && phoneOk) ? 'var(--accent)' : 'var(--card)', color: (name.trim() && phoneOk) ? 'var(--on-accent)' : 'var(--muted-2)',
                }}>{BT(lang, 'Confirm booking', 'Confirmar reserva')}</button>
              </div>
            </div>
          )}

          {/* STEP 2 — confirmation + simulated notifications */}
          {step === 2 && (
            <div>
              <div style={{ textAlign: 'center', padding: '4px 0 18px' }}>
                <div style={{ width: '56px', height: '56px', borderRadius: '50%', background: 'var(--accent)', color: 'var(--on-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px', fontSize: '1.5rem' }}>✓</div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: '1.2rem', textTransform: 'uppercase', letterSpacing: '-0.02em', color: 'var(--bone)' }}>{BK_SERVICES[lang][svcIdx]}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.7rem', letterSpacing: '0.05em', color: 'var(--accent)', marginTop: '5px' }}>{selLabel} · {time}</div>
                <div style={{ fontSize: '0.74rem', color: 'var(--muted)', marginTop: '8px' }}>{BT(lang, 'Confirmations sent', 'Confirmaciones enviadas')}</div>
              </div>

              {/* customer text */}
              <div style={notifLabel}>{BT(lang, 'Text to customer', 'Texto al cliente')}</div>
              <div style={smsBubble}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.5rem', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted-2)', marginBottom: '6px' }}>SMS → {phone || '(713) 555-0142'}</div>
                {BT(lang,
                  `Michael Style: ${name || 'you'}, you're booked for ${BK_SERVICES.EN[svcIdx]} on ${selLabel}, ${time}. Reply C to cancel. Dios primero — see you soon.`,
                  `Michael Style: ${name || 'tú'}, reservaste ${BK_SERVICES.ES[svcIdx]} el ${selLabel}, ${time}. Responde C para cancelar. Dios primero — nos vemos pronto.`)}
              </div>

              {/* barber app notification */}
              <div style={{ ...notifLabel, marginTop: '16px' }}>{BT(lang, 'App alert to Michael', 'Alerta a Michael')}</div>
              <div style={appNotif}>
                <div style={{ width: '34px', height: '34px', borderRadius: '9px', background: 'var(--accent)', color: 'var(--on-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none', fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: '0.7rem' }}>M/S</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: '8px', alignItems: 'baseline' }}>
                    <b style={{ fontSize: '0.74rem', color: 'var(--bone)', whiteSpace: 'nowrap' }}>{BT(lang, 'New booking', 'Nueva reserva')}</b>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.5rem', color: 'var(--muted-2)', flex: 'none' }}>now</span>
                  </div>
                  <div style={{ fontSize: '0.7rem', color: 'var(--muted)', marginTop: '2px' }}>{BT(lang,
                    `${name || 'New client'} · ${BK_SERVICES.EN[svcIdx]} · ${selLabel}, ${time}`,
                    `${name || 'Cliente nuevo'} · ${BK_SERVICES.ES[svcIdx]} · ${selLabel}, ${time}`)}</div>
                </div>
              </div>

              <button onClick={onClose} style={{ width: '100%', marginTop: '22px', fontFamily: 'var(--font-mono)', fontSize: '0.7rem', letterSpacing: '0.1em', textTransform: 'uppercase', padding: '15px', borderRadius: 'var(--radius-pill)', border: 'none', background: 'var(--accent)', color: 'var(--on-accent)', cursor: 'pointer' }}>{BT(lang, 'Done', 'Listo')}</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

const inputStyle = { width: '100%', fontFamily: 'var(--font-body)', fontSize: '0.9rem', padding: '13px 15px', borderRadius: 'var(--radius-input)', border: '1px solid var(--bd-d2)', background: 'var(--card)', color: 'var(--bone)', outline: 'none' };
const notifLabel = { fontFamily: 'var(--font-mono)', fontSize: '0.54rem', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--muted-2)', marginBottom: '8px' };
const smsBubble = { background: 'var(--card)', border: '1px solid var(--bd-d)', borderRadius: '4px 16px 16px 16px', padding: '13px 15px', fontSize: '0.78rem', color: 'var(--bone)', lineHeight: 1.5 };
const appNotif = { display: 'flex', gap: '11px', alignItems: 'flex-start', background: 'var(--card)', border: '1px solid color-mix(in srgb,var(--accent) 30%,transparent)', borderRadius: 'var(--radius-md)', padding: '13px 14px' };

Object.assign(window, { BookingModal });
