/* ============================================================
   BOOKING SERVICE — decoupled scheduling widget
   Consumed by Custom Orders, Packages, and the standalone page.
   Exports: BookingWidget, BookingPage
   ============================================================ */

const BOOKING_TIMES = ['9:00 am','10:00 am','11:00 am','12:00 pm','2:00 pm','3:00 pm','4:00 pm','5:00 pm'];
const MONTH_NAMES   = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const DAY_ABBR      = ['Su','Mo','Tu','We','Th','Fr','Sa'];

function getCalDays(year, month) {
  const first  = new Date(year, month, 1);
  const total  = new Date(year, month + 1, 0).getDate();
  const today  = new Date(); today.setHours(0,0,0,0);
  const minD   = new Date(today); minD.setDate(today.getDate() + 2);
  const cells  = [];
  for (let i = 0; i < first.getDay(); i++) cells.push(null);
  for (let d = 1; d <= total; d++) {
    const date = new Date(year, month, d);
    const wknd = date.getDay() === 0 || date.getDay() === 6;
    cells.push({ d, date, disabled: wknd || date < minD });
  }
  return cells;
}

function getSlotsForDay(date) {
  const h = date.getFullYear() * 10000 + date.getMonth() * 100 + date.getDate();
  return BOOKING_TIMES.map((time, i) => ({ time, available: (h * 7 + i * 13) % 5 !== 0 }));
}

/* ── BookingWidget ───────────────────────────────────────────
   Props:
     onConfirm(details)   — called on successful booking
     onBack()             — optional back handler
     compact              — smaller padding when embedded
   ──────────────────────────────────────────────────────────── */
function BookingWidget({ onConfirm, onBack, compact }) {
  const today = new Date();
  const [bStep,     setBStep]     = useState(0); // 0=date 1=time 2=contact 3=done
  const [viewYear,  setViewYear]  = useState(today.getFullYear());
  const [viewMonth, setViewMonth] = useState(today.getMonth());
  const [selDate,   setSelDate]   = useState(null);
  const [selTime,   setSelTime]   = useState(null);
  const [form,      setForm]      = useState({ name:'', email:'', phone:'' });
  const [ref,       setRef]       = useState('');
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const days  = getCalDays(viewYear, viewMonth);
  const slots = selDate ? getSlotsForDay(selDate) : [];
  const pad   = compact ? '20px 22px' : 'clamp(24px,4vw,44px)';

  const prevOk = () => {
    const d = new Date(viewYear, viewMonth - 1);
    return d >= new Date(today.getFullYear(), today.getMonth());
  };
  const prevMonth = () => {
    if (!prevOk()) return;
    if (viewMonth === 0) { setViewYear(y => y - 1); setViewMonth(11); }
    else setViewMonth(m => m - 1);
  };
  const nextMonth = () => {
    if (viewMonth === 11) { setViewYear(y => y + 1); setViewMonth(0); }
    else setViewMonth(m => m + 1);
  };

  const confirmBooking = () => {
    if (!form.name.trim() || !form.email.includes('@')) return;
    const r = 'BKG-' + Math.floor(100000 + Math.random() * 900000);
    setRef(r);
    setBStep(3);
    if (onConfirm) onConfirm({ date: selDate, time: selTime, ...form, ref: r });
  };

  const stepLabel = selDate
    ? selDate.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' })
    : '—';

  /* ── Step progress ── */
  const Progress = () => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 24 }}>
      {['Date','Time','Details'].map((l, i) => (
        <React.Fragment key={i}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'grid', placeItems: 'center', fontSize: 12, fontFamily: 'var(--serif)', transition: 'all .3s',
              background: bStep > i ? 'var(--sage)' : bStep === i ? 'var(--gold)' : 'var(--line)',
              color: bStep >= i ? '#fff' : 'var(--ink-faint)' }}>
              {bStep > i
                ? <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg>
                : i + 1}
            </div>
            <span style={{ fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: bStep === i ? 500 : 400,
              color: bStep === i ? 'var(--gold-deep)' : 'var(--ink-faint)' }}>{l}</span>
          </div>
          {i < 2 && <div style={{ flex: 1, height: 1, background: bStep > i ? 'var(--sage)' : 'var(--line)', margin: '0 8px', transition: 'background .4s' }} />}
        </React.Fragment>
      ))}
    </div>
  );

  /* ── Confirmed ── */
  if (bStep === 3) return (
    <div style={{ textAlign: 'center', padding: '32px 0' }}>
      <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'linear-gradient(135deg,var(--gold-deep),var(--gold))', display: 'grid', placeItems: 'center', color: '#fff', margin: '0 auto 20px', boxShadow: '0 8px 28px rgba(44,85,48,.3)' }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </div>
      <p className="eyebrow" style={{ color: 'var(--gold-deep)' }}>Consultation booked</p>
      <h3 style={{ fontSize: 'clamp(24px,3.5vw,36px)', margin: '10px 0 12px' }}>See you <em style={{ fontStyle: 'italic' }}>soon!</em></h3>
      <p style={{ fontSize: 15, color: 'var(--ink-soft)', lineHeight: 1.72, maxWidth: 380, margin: '0 auto 18px' }}>
        Your slot is confirmed for <strong>{selDate?.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })}</strong> at <strong>{selTime}</strong>.<br/>A confirmation will be sent to <strong>{form.email}</strong>.
      </p>
      <p style={{ fontSize: 12, color: 'var(--ink-faint)', letterSpacing: '.08em' }}>Reference: <strong style={{ color: 'var(--gold-deep)' }}>{ref}</strong></p>
    </div>
  );

  return (
    <div style={{ padding: pad }}>
      <Progress />

      {/* ── Step 0: Calendar ── */}
      {bStep === 0 && (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
            <button onClick={prevMonth} style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--cream-deep)', display: 'grid', placeItems: 'center', opacity: prevOk() ? 1 : .3, cursor: prevOk() ? 'pointer' : 'default' }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6"/></svg>
            </button>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 20 }}>{MONTH_NAMES[viewMonth]} {viewYear}</span>
            <button onClick={nextMonth} style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--cream-deep)', display: 'grid', placeItems: 'center' }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 18l6-6-6-6"/></svg>
            </button>
          </div>
          {/* Day headers */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 3, marginBottom: 6 }}>
            {DAY_ABBR.map(d => <div key={d} style={{ textAlign: 'center', fontSize: 10, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-faint)', padding: '3px 0' }}>{d}</div>)}
          </div>
          {/* Day cells */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 3 }}>
            {days.map((day, i) => day
              ? <button key={i} disabled={day.disabled} onClick={() => { setSelDate(day.date); setBStep(1); }}
                  style={{ aspectRatio: '1', borderRadius: 'var(--r-sm)', fontSize: 13, display: 'grid', placeItems: 'center', border: 'none', cursor: day.disabled ? 'not-allowed' : 'pointer', transition: 'all .2s',
                    background: selDate?.getTime() === day.date.getTime() ? 'var(--gold)' : 'var(--cream-deep)',
                    color: day.disabled ? 'var(--ink-faint)' : selDate?.getTime() === day.date.getTime() ? '#fff' : 'var(--ink)',
                    opacity: day.disabled ? .35 : 1 }}>{day.d}</button>
              : <div key={i} />
            )}
          </div>
          <p style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 14, textAlign: 'center' }}>Mon–Sat · {BB.BRAND.hours}</p>
        </div>
      )}

      {/* ── Step 1: Time slots ── */}
      {bStep === 1 && (
        <div>
          <button onClick={() => setBStep(0)} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 16, background: 'none', border: 'none', cursor: 'pointer' }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 5l-7 7 7 7" strokeLinecap="round" strokeLinejoin="round"/></svg>
            {stepLabel}
          </button>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 9 }}>
            {slots.map(({ time, available }) => (
              <button key={time} disabled={!available} onClick={() => { setSelTime(time); setBStep(2); }}
                style={{ padding: '13px 12px', borderRadius: 'var(--r-md)', fontSize: 13.5, border: '1.5px solid', cursor: available ? 'pointer' : 'not-allowed', transition: 'all .2s',
                  borderColor: selTime === time ? 'var(--gold)' : 'var(--line)',
                  background: selTime === time ? 'var(--gold-soft)' : available ? 'var(--ivory)' : 'var(--cream-deep)',
                  color: !available ? 'var(--ink-faint)' : selTime === time ? 'var(--gold-deep)' : 'var(--ink)',
                  opacity: available ? 1 : .45, textDecoration: !available ? 'line-through' : 'none' }}>
                {time}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* ── Step 2: Contact ── */}
      {bStep === 2 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <button onClick={() => setBStep(1)} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 4, background: 'none', border: 'none', cursor: 'pointer' }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 5l-7 7 7 7" strokeLinecap="round" strokeLinejoin="round"/></svg>
            {stepLabel} · {selTime}
          </button>
          {[['name','Full name','Alex Morgan','text','name'],['email','Email','you@email.com','email','email'],['phone','Phone / WhatsApp','+1 555 000 0000','tel','tel']].map(([k, lbl, ph, type, ac]) => (
            <div key={k} style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>{lbl}{k !== 'phone' && <span style={{ color: 'var(--blush)', marginLeft: 2 }}>*</span>}</label>
              <input className="input" type={type} value={form[k]} onChange={e => set(k, e.target.value)} placeholder={ph} autoComplete={ac} />
            </div>
          ))}
          <button className="btn btn-primary" onClick={confirmBooking} style={{ marginTop: 8 }}>
            <span>Confirm Booking</span>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <p style={{ fontSize: 12, color: 'var(--ink-faint)', textAlign: 'center' }}>Your details are never shared.</p>
        </div>
      )}
    </div>
  );
}

/* ── BookingPage (standalone route) ───────────────────────── */
function BookingPage() {
  const { nav } = useStore();
  return (
    <div style={{ background: 'var(--cream)', minHeight: '80vh' }}>
      <div style={{ background: 'var(--ink)', padding: 'clamp(56px,8vw,96px) var(--gutter)', textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 70% 80% at 50% 120%, rgba(44,85,48,.25) 0%, transparent 70%)', pointerEvents: 'none' }} />
        <div style={{ position: 'relative', zIndex: 1 }}>
          <p className="eyebrow" style={{ color: 'rgba(255,255,255,.5)' }}>30 minutes · free · no obligation</p>
          <h1 style={{ fontSize: 'clamp(44px,6.5vw,78px)', color: '#fff', margin: '12px 0 16px', lineHeight: .96 }}>Book a <em style={{ fontStyle: 'italic' }}>consultation</em></h1>
          <p style={{ fontSize: 16, color: 'rgba(255,255,255,.62)', maxWidth: 480, margin: '0 auto', lineHeight: 1.75 }}>Choose a time that works for you. We'll walk through your brief together and build a plan.</p>
        </div>
      </div>

      <div className="container" style={{ maxWidth: 820, padding: 'clamp(40px,6vw,72px) var(--gutter)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 40, alignItems: 'start' }}>
          {/* Info column */}
          <div>
            {[
              ['30-minute call', 'Long enough to cover every detail of your brief — theme, quantities, timeline and delivery.', 'clock'],
              ['WhatsApp or video', 'Pick whatever works. We\'re based in WAT but available to accommodate your timezone.', 'phone'],
              ['Free, always', 'The consultation is on us. No card required, no commitment needed.', 'shield'],
              ['Speak to the team', 'No account managers — you\'ll be talking directly to the people making your order.', 'user'],
            ].map(([t, d, icon]) => (
              <div key={t} style={{ display: 'flex', gap: 14, marginBottom: 26 }}>
                <div style={{ width: 42, height: 42, borderRadius: 'var(--r-sm)', background: 'var(--gold-soft)', display: 'grid', placeItems: 'center', color: 'var(--gold-deep)', flexShrink: 0 }}>
                  {icon === 'clock' && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>}
                  {icon === 'phone' && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12a19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 3.61 1h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 8.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92Z"/></svg>}
                  {icon === 'shield' && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6l8-3Z" strokeLinejoin="round"/></svg>}
                  {icon === 'user' && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 4-6 8-6s8 2 8 6"/></svg>}
                </div>
                <div>
                  <div style={{ fontWeight: 500, fontSize: 15, marginBottom: 3 }}>{t}</div>
                  <div style={{ fontSize: 14, color: 'var(--ink-soft)', lineHeight: 1.6 }}>{d}</div>
                </div>
              </div>
            ))}
          </div>
          {/* Booking card */}
          <div style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-xl)', position: 'sticky', top: 100, overflow: 'hidden' }}>
            <BookingWidget onConfirm={() => {}} compact={false} />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BookingWidget, BookingPage });
