/* global React, Button, Chip, Stamp */
const { useState, useMemo } = React;

/* ============================================================
   Booking modal — hard-coded in brand voice, hands off to
   Vagaro at the final step.
   ============================================================ */
const VAGARO_URL = 'https://www.vagaro.com/tokyobikinibar/services';

const SERVICES = [
  { name:'Brazilian',         price:53,  mins:45,  tone:'pink' },
  { name:'Bikini line',       price:28,  mins:25,  tone:'bubble' },
  { name:'Half leg',          price:45,  mins:30,  tone:'sky' },
  { name:'Full leg',          price:70,  mins:60,  tone:'lime' },
  { name:'Underarm',          price:18,  mins:15,  tone:'butter' },
  { name:'Brow wax',          price:18,  mins:15,  tone:'cyan' },
  { name:'Brow tint',         price:18,  mins:10,  tone:'coral' },
  { name:'Brow lam',          price:75,  mins:45,  tone:'pink' },
  { name:'Korean lash lift',  price:95,  mins:60,  tone:'butter' },
  { name:'Lash extensions',   price:100, mins:120, tone:'bubble' },
  { name:'Full back',         price:68,  mins:45,  tone:'sky' },
  { name:'Full body (T1)',    price:110, mins:90,  tone:'lime' },
  { name:'Full body (T2)',    price:200, mins:120, tone:'pink' },
];

// faux availability — 5 days × 6 slots
function buildSlots() {
  const days = ['Thu','Fri','Sat','Sun','Tue'];
  const dates = [14, 15, 16, 17, 19];
  const times = ['10:30 AM','12:00 PM','1:30 PM','3:00 PM','5:30 PM','7:00 PM'];
  return days.map((d, i) => ({
    day: d, date: dates[i],
    times: times.map(t => ({ t, free: Math.random() > 0.32 })),
  }));
}

function BookingModal({ open, initialService, onClose }) {
  const [step, setStep] = useState(0);
  const [service, setService] = useState(initialService || 'Brazilian');
  const [slotDay, setSlotDay] = useState('Sat');
  const [slotTime, setSlotTime] = useState('1:30 PM');
  const [first, setFirst] = useState('');
  const [phone, setPhone] = useState('');
  const [notes, setNotes] = useState('');
  const slots = useMemo(buildSlots, [open]);

  React.useEffect(() => {
    if (initialService) setService(initialService);
  }, [initialService]);
  React.useEffect(() => {
    if (open) setStep(0);
  }, [open]);

  if (!open) return null;
  const svc = SERVICES.find(s => s.name === service) || SERVICES[0];
  const canContinue = [
    !!service,
    !!slotDay && !!slotTime,
    first.trim().length > 1 && phone.replace(/\D/g,'').length >= 10,
    true,
  ][step];

  const stepTitles = ['Pick your service', 'Pick a time', 'Tell me about you', "You're booked ♡"];
  const stepJp = ['サービス選択','日時選択','お客様情報','確定'];

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:60,
      background:'rgba(10,10,10,0.62)',
      display:'flex', alignItems:'center', justifyContent:'center',
      padding:18, overflowY:'auto',
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        background:'var(--tbb-paper)',
        border:'5px solid var(--tbb-ink)',
        borderRadius:36,
        boxShadow:'12px 12px 0 0 var(--tbb-hotpink)',
        width:680, maxWidth:'100%', maxHeight:'92vh', overflowY:'auto',
        padding:'28px 30px 26px',
        display:'flex', flexDirection:'column', gap:18,
        position:'relative',
      }}>
        {/* close */}
        <button onClick={onClose} style={{
          position:'absolute', top:14, right:14,
          width:42, height:42, borderRadius:999,
          background:'var(--tbb-ink)', color:'var(--tbb-paper)',
          border:'3px solid var(--tbb-ink)', cursor:'pointer',
          fontFamily:'Nunito Sans', fontWeight:900, fontSize:18,
          boxShadow:'3px 3px 0 0 var(--tbb-hotpink)',
        }}>✕</button>

        {/* progress */}
        <div style={{ display:'flex', alignItems:'center', gap:10, flexWrap:'wrap' }}>
          <Chip tone="pink" sticker>Step {Math.min(step+1, 4)} / 4</Chip>
          <div style={{ display:'flex', gap:6 }}>
            {[0,1,2,3].map(i => (
              <div key={i} style={{
                width: step >= i ? 36 : 16, height:10, borderRadius:999,
                background: step >= i ? 'var(--tbb-hotpink)' : 'var(--tbb-paper-warm)',
                border:'2.5px solid var(--tbb-ink)',
                transition:'all 240ms var(--bounce)',
              }}/>
            ))}
          </div>
        </div>

        {/* header */}
        <div>
          <div style={{ fontFamily:'Hiragino Kaku W9, system-ui', fontSize:15, color:'var(--fg2)', marginBottom:2 }}>{stepJp[step]}</div>
          <h3 style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:'clamp(34px, 4vw, 52px)', lineHeight:0.95, margin:0 }}>
            {stepTitles[step]}.
          </h3>
        </div>

        {/* body */}
        {step === 0 && (
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(160px, 1fr))', gap:10 }}>
            {SERVICES.map(s => {
              const active = service === s.name;
              return (
                <button key={s.name} onClick={()=>setService(s.name)} style={{
                  textAlign:'left',
                  padding:'14px 16px',
                  borderRadius:18,
                  border:'3px solid var(--tbb-ink)',
                  background: active ? 'var(--tbb-hotpink)' : 'var(--tbb-white)',
                  color: active ? 'var(--tbb-paper)' : 'var(--tbb-ink)',
                  boxShadow: active ? '5px 5px 0 0 var(--tbb-ink)' : '3px 3px 0 0 var(--tbb-ink)',
                  transform: active ? 'translate(-2px,-2px)' : 'none',
                  cursor:'pointer', transition:'all 180ms var(--bounce)',
                }}>
                  <div style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:24, lineHeight:1 }}>{s.name}</div>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginTop:8, fontFamily:'Nunito Sans', fontWeight:800, fontSize:12, letterSpacing:'0.08em', textTransform:'uppercase' }}>
                    <span>${s.price}</span><span style={{ opacity:0.7 }}>{s.mins} min</span>
                  </div>
                </button>
              );
            })}
          </div>
        )}

        {step === 1 && (
          <div>
            <div style={{ fontFamily:'Nunito Sans', fontWeight:900, fontSize:12, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--fg3)', marginBottom:10 }}>This week</div>
            <div style={{ display:'grid', gridTemplateColumns:`repeat(${slots.length}, 1fr)`, gap:6, marginBottom:14 }}>
              {slots.map(d => (
                <button key={d.day} onClick={()=>setSlotDay(d.day)} style={{
                  padding:'10px 6px', borderRadius:14, border:'3px solid var(--tbb-ink)',
                  background: slotDay===d.day ? 'var(--tbb-lime)' : 'var(--tbb-white)',
                  boxShadow: slotDay===d.day ? '4px 4px 0 0 var(--tbb-ink)' : '2px 2px 0 0 var(--tbb-ink)',
                  cursor:'pointer', transition:'all 180ms var(--bounce)',
                }}>
                  <div style={{ fontFamily:'Nunito Sans', fontWeight:900, fontSize:11, letterSpacing:'0.12em', textTransform:'uppercase' }}>{d.day}</div>
                  <div style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:24, lineHeight:1, marginTop:2 }}>{d.date}</div>
                </button>
              ))}
            </div>
            <div style={{ fontFamily:'Nunito Sans', fontWeight:900, fontSize:12, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--fg3)', marginBottom:10 }}>{slotDay} — available slots</div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(110px, 1fr))', gap:8 }}>
              {(slots.find(d=>d.day===slotDay)?.times || []).map(t => (
                <button key={t.t} disabled={!t.free} onClick={()=>setSlotTime(t.t)} style={{
                  padding:'10px 8px', borderRadius:14, border:'3px solid var(--tbb-ink)',
                  background: !t.free ? 'var(--tbb-paper-warm)'
                            : slotTime===t.t ? 'var(--tbb-hotpink)'
                            : 'var(--tbb-white)',
                  color: !t.free ? '#9C968B'
                       : slotTime===t.t ? 'var(--tbb-paper)' : 'var(--tbb-ink)',
                  boxShadow: !t.free ? 'none' : slotTime===t.t ? '4px 4px 0 0 var(--tbb-ink)' : '2px 2px 0 0 var(--tbb-ink)',
                  cursor: t.free ? 'pointer' : 'not-allowed',
                  fontFamily:'Nunito Sans', fontWeight:900, fontSize:13, letterSpacing:'0.06em', textTransform:'uppercase',
                  textDecoration: !t.free ? 'line-through' : 'none',
                  transition:'all 180ms var(--bounce)',
                }}>{t.t}</button>
              ))}
            </div>
          </div>
        )}

        {step === 2 && (
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            <Field label="First name" value={first} onChange={setFirst} placeholder="Sofia" />
            <Field label="Mobile" value={phone} onChange={setPhone} placeholder="(305) 555-0123" />
            <Field label="Anything I should know? (optional)" value={notes} onChange={setNotes} placeholder="First-time Brazilian, on retinol, etc." multiline />
            <div style={{
              background:'var(--tbb-paper-warm)',
              border:'3px solid var(--tbb-ink)', borderRadius:18,
              padding:'14px 18px',
              display:'flex', justifyContent:'space-between', flexWrap:'wrap', gap:8,
              fontFamily:'Nunito Sans', fontWeight:800, fontSize:13,
            }}>
              <span>{svc.name} · ${svc.price} · {svc.mins} min</span>
              <span>{slotDay} · {slotTime}</span>
            </div>
          </div>
        )}

        {step === 3 && (
          <div style={{ textAlign:'center', padding:'8px 0 4px' }}>
            <img src="assets/mascot-color.png" style={{ width:160, transform:'rotate(-6deg)', filter:'drop-shadow(6px 6px 0 var(--tbb-hotpink))' }} alt=""/>
            <div style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:'clamp(40px, 5vw, 64px)', lineHeight:0.95, margin:'14px 0 8px' }}>
              You're in ♡
            </div>
            <p style={{ fontFamily:'Nunito', fontWeight:600, fontSize:17, color:'var(--fg2)', maxWidth:440, margin:'0 auto 14px' }}>
              Hold on babe — confirming on Vagaro now. Your spot is locked the second you finalize there.
            </p>
            <div style={{
              display:'inline-flex', flexDirection:'column', gap:8,
              border:'3px solid var(--tbb-ink)', borderRadius:24,
              boxShadow:'5px 5px 0 0 var(--tbb-ink)',
              padding:'14px 22px', background:'var(--tbb-lime)',
              marginBottom:18, fontFamily:'Nunito Sans', fontWeight:900, fontSize:14, letterSpacing:'0.06em', textTransform:'uppercase',
            }}>
              <span>{svc.name} · ${svc.price}</span>
              <span>{slotDay} · {slotTime}</span>
              <span>For: {first || 'Babe'}</span>
            </div>
            <div style={{ display:'flex', gap:10, justifyContent:'center', flexWrap:'wrap' }}>
              <Button size="lg" as="a" href={VAGARO_URL} target="_blank" rel="noreferrer">Finalize on Vagaro →</Button>
              <Button size="lg" variant="secondary" onClick={onClose}>See you soon ✦</Button>
            </div>
            <p style={{ fontFamily:'Nunito', fontWeight:500, fontSize:13, color:'var(--fg3)', marginTop:14, maxWidth:420, marginLeft:'auto', marginRight:'auto' }}>
              We use Vagaro for the actual calendar + payments. You'll get a text confirmation once it locks.
            </p>
          </div>
        )}

        {/* footer nav */}
        {step < 3 && (
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:6, gap:10, flexWrap:'wrap' }}>
            <Button size="sm" variant="secondary" onClick={() => setStep(Math.max(0, step-1))} disabled={step===0}>← Back</Button>
            <div style={{ fontFamily:'Nunito Sans', fontWeight:900, fontSize:12, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--fg2)' }}>
              {svc.name} · ${svc.price}{step >= 1 ? ` · ${slotDay} ${slotTime}` : ''}
            </div>
            <Button size="md" onClick={() => canContinue && setStep(step+1)} style={!canContinue ? { opacity:0.45, pointerEvents:'none' } : {}}>
              {step===2 ? 'Confirm ✦' : 'Continue →'}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}

function Field({ label, value, onChange, placeholder, multiline = false }) {
  return (
    <label style={{ display:'flex', flexDirection:'column', gap:6 }}>
      <span style={{ fontFamily:'Nunito Sans', fontWeight:900, fontSize:11, letterSpacing:'0.18em', textTransform:'uppercase', color:'var(--fg2)' }}>{label}</span>
      {multiline ? (
        <textarea value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} rows={3} style={inputStyle}/>
      ) : (
        <input value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} style={inputStyle}/>
      )}
    </label>
  );
}
const inputStyle = {
  fontFamily:'Nunito, system-ui', fontWeight:600, fontSize:16,
  padding:'12px 16px', borderRadius:14,
  border:'3px solid var(--tbb-ink)',
  background:'var(--tbb-white)', color:'var(--tbb-ink)',
  boxShadow:'3px 3px 0 0 var(--tbb-ink)',
  outline:'none',
  resize:'vertical',
};

Object.assign(window, { BookingModal });
