// BOOKING — the time picker screen. Full-bleed slide-up, matches v3 mechanics.

function seatCountInit() {
  // [day][slotIndex] seats left — v3 values
  return [
    [47, 12, 27], // today: 12pm, 4pm, 6pm (skip 2pm today)
    [41, 8, 55, 33],
    [68, 72, 51, 79],
  ];
}

const SLOT_HOURS = [
  [{time:'12:00 PM', tz:'Pacific', iso:'12:00'},{time:'4:00 PM', tz:'Pacific', iso:'16:00'},{time:'6:00 PM', tz:'Pacific', iso:'18:00'}],
  [{time:'12:00 PM', tz:'Pacific', iso:'12:00'},{time:'2:00 PM', tz:'Pacific', iso:'14:00'},{time:'4:00 PM', tz:'Pacific', iso:'16:00'},{time:'6:00 PM', tz:'Pacific', iso:'18:00'}],
  [{time:'12:00 PM', tz:'Pacific', iso:'12:00'},{time:'2:00 PM', tz:'Pacific', iso:'14:00'},{time:'4:00 PM', tz:'Pacific', iso:'16:00'},{time:'6:00 PM', tz:'Pacific', iso:'18:00'}],
];

function dayLabels() {
  const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  const out = [];
  for (let i = 0; i < 3; i++) {
    const d = new Date();
    d.setDate(d.getDate() + i);
    out.push({
      short: i === 0 ? 'Today' : i === 1 ? 'Tomorrow' : days[d.getDay()],
      date: months[d.getMonth()] + ' ' + d.getDate(),
      raw: d,
    });
  }
  return out;
}

function TimeScreen() {
  const { booking, updateBooking, countdown } = useApp();
  const [day, setDay] = useState(0);
  const [selected, setSelected] = useState(null);
  const [seats, setSeats] = useState(seatCountInit);
  const [email, setEmail] = useState(booking.email || '');
  const [emailErr, setEmailErr] = useState(false);
  const days = useMemo(() => dayLabels(), []);

  // Decrement seats slowly — realism
  useEffect(() => {
    const id = setInterval(() => {
      setSeats(prev => {
        const next = prev.map(row => row.slice());
        const d = Math.floor(Math.random()*3);
        const s = Math.floor(Math.random()*next[d].length);
        if (next[d][s] > 0) {
          const dec = next[d][s] > 30 ? (Math.random()<0.5?1:2) : 1;
          next[d][s] = Math.max(0, next[d][s] - dec);
        }
        return next;
      });
    }, 5500);
    return () => clearInterval(id);
  }, []);

  const pick = (d, si) => {
    if (seats[d][si] === 0) return;
    setSelected({d, si});
    setDay(d);
  };

  const lock = () => {
    if (!selected) return;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      setEmailErr(true);
      return;
    }
    const slot = SLOT_HOURS[selected.d][selected.si];
    const d = days[selected.d];
    updateBooking({
      email: email.trim(),
      day: selected.d,
      dayDate: d.raw,
      time: slot.time + ' PT',
      iso: slot.iso,
      step: 'confirm',
    });
  };

  const close = () => updateBooking({ step: 'landing' });

  return (
    <div style={{
      position:'fixed',inset:0,zIndex:100,background:'var(--bg)',
      padding:'28px 20px calc(20px + env(safe-area-inset-bottom,0px))',
      overflowY:'auto',animation:'apex-slide-up 0.45s cubic-bezier(0.16,1,0.3,1)',
    }}>
      <div style={{maxWidth:560,margin:'0 auto'}}>
        <div style={{textAlign:'center',marginBottom:26,paddingTop:8}}>
          <div style={{display:'flex',justifyContent:'center',marginBottom:14}}>
            <Orb size={56} float={false}/>
          </div>
          <span style={{
            display:'inline-block',fontSize:10,fontWeight:800,letterSpacing:3,textTransform:'uppercase',
            color:'var(--purple)',background:'rgba(124,58,237,0.1)',
            padding:'6px 12px',borderRadius:999,marginBottom:12,
          }}>Step 2 of 2 · Pick your session</span>
          <h2 style={{
            fontSize:'clamp(26px,5vw,38px)',fontWeight:700,lineHeight:1.1,
            color:'var(--ink)',letterSpacing:'-0.8px',marginBottom:8,
          }}>When do you want <em style={{
            fontStyle:'normal',background:BRAND.gradient,
            WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
          }}>in</em>?</h2>
          <p style={{fontSize:14,color:'var(--mute)'}}>
            45 min. Live on Zoom. Bring a colleague, or the whole office.
          </p>
        </div>

        <BookingBody
          days={days} day={day} setDay={setDay}
          selected={selected} setSelected={setSelected}
          seats={seats}
          countdown={countdown}
        />

        <LiveBookingPing/>

        <Input type="email" value={email} onChange={e=>{setEmail(e.target.value);setEmailErr(false)}}
          placeholder="Email (for calendar invite)"
          style={{marginTop:14, borderColor: emailErr ? '#ef4444' : 'transparent'}}/>

        <Button variant="primary" size="lg" onClick={lock}
          disabled={!selected}
          style={{
            width:'100%',marginTop:14,
            opacity: selected ? 1 : 0.4,
            cursor: selected ? 'pointer' : 'not-allowed',
            textTransform:'uppercase',letterSpacing:1.5,
          }}>
          Lock in my seat →
        </Button>

        <WhatHappensNext/>

        <button onClick={close} style={{
          display:'block',textAlign:'center',marginTop:14,
          background:'none',border:'none',color:'var(--mute)',
          fontFamily:'inherit',fontSize:12,letterSpacing:1,textTransform:'uppercase',
          cursor:'pointer',padding:10,width:'100%',
        }}>← Back</button>
      </div>
    </div>
  );
}

Object.assign(window, { TimeScreen });
