/* DUNNGAMES — "Minimal" booking page. Clean scheduler + service-aware form.
   Reuses Pill / ThemeToggle from window.MIN. Exports window.MINBooking. */

const { Pill: BPill, ThemeToggle: BTheme } = window.MIN;
const BA = 'assets';

const M_SERVICES = [
  { t: 'Design Review', slug: 'design-review', dur: '30 min', d: 'We review your core loop, onboarding, and progression systems, then deliver insights and action items to elevate your experience.' },
  { t: 'Studio Mentorship', slug: 'studio-mentorship', dur: '30 min', d: 'We integrate directly with your team to overhaul workflows, build product roadmaps, instill a winning culture, and accelerate growth.' },
  { t: 'Branded Project', slug: 'branded-project', dur: '30 min', d: 'Bring your brand into a world of millions of players. We scope a custom branded game or in-game activation and map the path from concept to launch.' },
];
const M_HOSTS = [
  { img: BA + '/team/grant-dunn.jpg', name: 'Grant Dunn', role: 'CEO & Lead Designer', pos: 'center 30%', scale: 1 },
  { img: BA + '/team/grant-dunn.jpg', name: 'Grant Dunn', role: 'CEO & Lead Designer', pos: 'center 30%', scale: 1 },
  { img: BA + '/team/connor-acosta.png?v=2', name: 'Connor Acosta', role: 'Executive Producer', pos: 'center 30%', scale: 1 },
];
function HostChip({ host }) {
  return (
    <React.Fragment>
      <span style={{ position: 'relative', width: '40px', height: '40px', borderRadius: '999px', flexShrink: 0, overflow: 'hidden', border: '1px solid var(--m-line)', display: 'block' }}>
        <img src={host.img} alt={host.name} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: host.pos, transform: 'scale(' + host.scale + ')' }} />
      </span>
      <div style={{ position: 'relative', minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '14px', color: 'var(--m-ink)', lineHeight: 1.2 }}>{host.name}</div>
        <div style={{ fontFamily: 'var(--m-font-body)', fontSize: '12px', color: 'var(--m-ink-faint)' }}>{host.role}</div>
      </div>
    </React.Fragment>
  );
}
const M_EMAIL = { k: 'email', label: 'Email', req: true, type: 'email', ph: 'you@studio.com' };
const M_FIELDS = [
  [
    { k: 'game', label: 'Game name', req: true, ph: 'e.g. Farming & Friends' },
    { k: 'genre', label: 'Genre', req: true, ph: 'e.g. Simulation, Tycoon, PvP' },
    { k: 'desc', label: 'Description', req: true, area: true, ph: 'Tell us about your game and what you want reviewed.' },
    { k: 'link', label: 'Game link (optional)', req: false, ph: 'roblox.com/games/\u2026' },
  ],
  [
    { k: 'name', label: 'Your name / studio', req: true, ph: 'Who are we mentoring?' },
    { k: 'building', label: 'What are you building?', req: true, ph: 'Your game or studio in a sentence.' },
    { k: 'goal', label: 'Biggest challenge right now', req: true, area: true, ph: 'What would you most like help with?' },
  ],
  [
    { k: 'brand', label: 'Brand / company', req: true, ph: 'e.g. Acme Beverages' },
    { k: 'idea', label: 'Info', req: true, area: true, ph: 'Tell us about the branded experience you want to build.' },
  ],
];
const M_SLOTS_BY_DAY = {
  2: ['11:00am', '11:30am', '2:00pm', '2:30pm', '3:00pm', '3:30pm'],
  3: ['11:00am', '11:30am', '2:00pm', '2:30pm', '3:00pm', '3:30pm'],
  4: ['11:00am', '11:30am', '2:00pm', '2:30pm', '3:00pm', '3:30pm'],
  5: ['11:00am', '11:30am'],
};
const M_TZ = ['Central Time (US & Canada)', 'Eastern Time (US & Canada)', 'Pacific Time (US & Canada)', 'UK / GMT'];
const M_WD = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
const M_MON = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const M_DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

function mGrid(y, m) {
  const sd = new Date(y, m, 1).getDay(); const dn = new Date(y, m + 1, 0).getDate(); const c = [];
  for (let i = 0; i < sd; i++) c.push(null);
  for (let d = 1; d <= dn; d++) c.push(d);
  while (c.length % 7) c.push(null);
  return c;
}

function MWordmark() {
  return (
    <a href="/" style={{ display: 'inline-flex', alignItems: 'center', textDecoration: 'none' }}>
      <img src={BA + '/logo-dunngames-short.png'} alt="Dunn Games" style={{ height: '28px', width: 'auto', display: 'block' }} />
    </a>
  );
}

function BookingPage({ theme, onToggle }) {
  const today = new Date(); today.setHours(0, 0, 0, 0);
  // Preselect the service from ?service=<slug> (set by the CTA that linked here).
  const [svc, setSvc] = React.useState(() => {
    try {
      const s = new URLSearchParams(window.location.search).get('service');
      const i = M_SERVICES.findIndex((x) => x.slug === s);
      return i >= 0 ? i : 0;
    } catch (e) { return 0; }
  });
  const [view, setView] = React.useState({ y: today.getFullYear(), m: today.getMonth() });
  const [sel, setSel] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [tz, setTz] = React.useState('Central Time (US & Canada)');
  const [tzOpen, setTzOpen] = React.useState(false);
  const [showForm, setShowForm] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const EMPTY_FORM = { email: '', game: '', genre: '', link: '', desc: '', name: '', building: '', goal: '', brand: '', audience: '', idea: '', budget: '' };
  const [form, setForm] = React.useState(EMPTY_FORM);
  const [availByDate, setAvailByDate] = React.useState({});
  const [availLoading, setAvailLoading] = React.useState(true);
  const [bookErr, setBookErr] = React.useState(null);

  const pad = (n) => String(n).padStart(2, '0');
  const dkey = (y, m, d) => `${y}-${pad(m + 1)}-${pad(d)}`;

  const loadAvail = React.useCallback(() => {
    const last = new Date(view.y, view.m + 1, 0).getDate();
    const from = `${view.y}-${pad(view.m + 1)}-01`;
    const to = `${view.y}-${pad(view.m + 1)}-${pad(last)}`;
    setAvailLoading(true);
    return fetch(`/api/availability?from=${from}&to=${to}`)
      .then((r) => r.json())
      .then((d) => { setAvailByDate(d.byDate || {}); setAvailLoading(false); return d; })
      .catch(() => { setAvailLoading(false); });
  }, [view.y, view.m]);
  React.useEffect(() => { loadAvail(); }, [loadAvail]);

  const cells = mGrid(view.y, view.m);
  const service = M_SERVICES[svc];
  const host = M_HOSTS[svc];
  const fields = M_FIELDS[svc];
  const isPast = (d) => new Date(view.y, view.m, d) < today;
  const dayOk = (d) => { const dy = new Date(view.y, view.m, d).getDay(); return dy >= 2 && dy <= 5; };
  const hasSlots = (d) => (availByDate[dkey(view.y, view.m, d)] || []).length > 0;
  const avail = (d) => !!d && !isPast(d) && (availLoading ? dayOk(d) : hasSlots(d));
  const isSel = (d) => sel && d && sel.getFullYear() === view.y && sel.getMonth() === view.m && sel.getDate() === d;
  const atMin = view.y === today.getFullYear() && view.m === today.getMonth();
  const prev = () => setView((v) => { const d = new Date(v.y, v.m - 1, 1); return { y: d.getFullYear(), m: d.getMonth() }; });
  const next = () => setView((v) => { const d = new Date(v.y, v.m + 1, 1); return { y: d.getFullYear(), m: d.getMonth() }; });
  const pick = (d) => { if (!avail(d)) return; setBookErr(null); setSel(new Date(view.y, view.m, d)); setTime(null); };
  const longDate = sel ? `${M_DAYS[sel.getDay()]}, ${M_MON[sel.getMonth()]} ${sel.getDate()}` : null;
  const selKey = sel ? dkey(sel.getFullYear(), sel.getMonth(), sel.getDate()) : null;
  const slots = selKey ? (availByDate[selKey] || []) : [];

  const emailBad = !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test((form.email || '').trim());
  const missing = (f) => f.req && !(form[f.k] || '').trim();
  const canSubmit = !emailBad && fields.every((f) => !missing(f));

  const confirmSlot = () => { setBookErr(null); setShowForm(true); };

  const submit = () => {
    if (!canSubmit) { setSubmitted(true); return; }
    setSubmitting(true); setBookErr(null);
    fetch('/api/book', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ service: svc, date: selKey, time, form }) })
      .then(async (r) => {
        const j = await r.json().catch(() => ({}));
        setSubmitting(false);
        if (r.ok) { setDone(true); }
        else { setShowForm(false); setTime(null); setBookErr(j.error || 'Could not book that slot.'); loadAvail(); }
      })
      .catch(() => { setSubmitting(false); setBookErr('Network error. Please try again.'); });
  };
  const reset = () => { setDone(false); setShowForm(false); setSubmitted(false); setSubmitting(false); setSel(null); setTime(null); setBookErr(null); setForm(EMPTY_FORM); loadAvail(); };

  const label = { fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '11px', letterSpacing: '1.4px', textTransform: 'uppercase', color: 'var(--m-ink-faint)', marginBottom: '12px' };
  const fieldStyle = (bad) => ({ width: '100%', padding: '12px 14px', borderRadius: '12px', border: '1px solid ' + (bad ? '#E5484D' : 'var(--m-line)'), background: 'var(--m-page-2)', color: 'var(--m-ink)', fontFamily: 'var(--m-font-body)', fontWeight: 500, fontSize: '14px', outline: 'none', resize: 'vertical', boxSizing: 'border-box' });
  const renderField = (f) => {
    const bad = submitted && (f.k === 'email' ? emailBad : missing(f));
    return (
      <label key={f.k} style={{ display: 'block' }}>
        <span style={{ display: 'block', fontFamily: 'var(--m-font-body)', fontWeight: 600, fontSize: '13px', color: 'var(--m-ink)', marginBottom: '6px' }}>{f.label}{f.req ? <span style={{ color: '#E5484D' }}> *</span> : null}</span>
        {f.area
          ? <textarea rows={3} value={form[f.k]} onChange={(e) => setForm((p) => ({ ...p, [f.k]: e.target.value }))} placeholder={f.ph} style={fieldStyle(bad)} />
          : <input type={f.type || 'text'} value={form[f.k]} onChange={(e) => setForm((p) => ({ ...p, [f.k]: e.target.value }))} placeholder={f.ph} style={fieldStyle(bad)} />}
      </label>
    );
  };

  const arrowBtn = (dir, on, dis) => (
    <button onClick={on} disabled={dis} style={{ width: '34px', height: '34px', borderRadius: '11px', border: '1px solid var(--m-line)', background: 'var(--m-page)', color: dis ? 'var(--m-ink-faint)' : 'var(--m-ink)', fontSize: '15px', cursor: dis ? 'default' : 'pointer', opacity: dis ? .5 : 1 }}>{dir}</button>
  );
  const dayBtn = (d) => {
    if (!d) return <span />;
    const s = isSel(d); const a = avail(d);
    return (
      <button key={d} onClick={() => pick(d)} disabled={!a} style={{ width: '100%', aspectRatio: '1 / 1', borderRadius: '11px', border: '1px solid ' + (s ? 'var(--m-accent)' : 'transparent'), background: s ? 'var(--m-accent)' : (a ? 'var(--m-accent-soft)' : 'transparent'), color: s ? '#fff' : (a ? 'var(--m-accent)' : 'var(--m-ink-faint)'), fontFamily: 'var(--m-font-display)', fontWeight: 600, fontSize: '14px', cursor: a ? 'pointer' : 'default', opacity: a || s ? 1 : .45 }}>{d}</button>
    );
  };

  return (
    <React.Fragment>
      <header style={{ position: 'sticky', top: 0, zIndex: 50, background: 'color-mix(in srgb, var(--m-page) 85%, transparent)', backdropFilter: 'saturate(1.4) blur(14px)', WebkitBackdropFilter: 'saturate(1.4) blur(14px)', borderBottom: '1px solid var(--m-line)' }}>
        <div style={{ maxWidth: 'var(--m-maxw)', margin: '0 auto', padding: '16px 28px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <MWordmark />
          <div style={{ display: 'flex', alignItems: 'center', gap: '18px' }}>
            <BTheme theme={theme} onToggle={onToggle} />
            <BPill href="/" variant="ghost" size="sm" style={{ boxShadow: 'none' }}>
              Back to site
            </BPill>
          </div>
        </div>
      </header>

      <main style={{ position: 'relative', background: 'var(--m-page-2)', minHeight: 'calc(100vh - 65px)', padding: '56px 24px 80px', overflow: 'hidden' }}>
        <div aria-hidden="true" style={{ position: 'absolute', top: '-120px', left: '50%', transform: 'translateX(-50%)', width: '780px', height: '360px', background: 'radial-gradient(60% 60% at 50% 40%, color-mix(in srgb, var(--m-accent) 16%, transparent) 0%, transparent 70%)', pointerEvents: 'none' }} />
        <div style={{ position: 'relative', maxWidth: '1060px', margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: '34px' }}>
            <div style={{ fontFamily: 'var(--m-font-display)', fontWeight: 800, fontSize: '13px', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--m-accent)', marginBottom: '14px' }}>Book an appointment</div>
            <h1 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 800, fontSize: 'clamp(30px,4vw,46px)', letterSpacing: '-0.02em', margin: 0, color: 'var(--m-ink)' }}>Grab a slot on the calendar</h1>
            <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '15px', color: 'var(--m-ink-soft)', margin: '14px auto 0', maxWidth: '440px', lineHeight: 1.6 }}>Free to book, and easy to reschedule. Pick a service, choose a time, and we'll send a calendar invite.</p>
          </div>

          <div style={{ background: 'var(--m-page)', border: '1px solid var(--m-line)', borderRadius: 'var(--m-r-card)', boxShadow: 'var(--m-shadow-card)', overflow: 'hidden' }}>
            {submitting ? (
              <div style={{ padding: '96px 30px', textAlign: 'center', animation: 'mBookFadeIn .35s ease' }}>
                <span style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '64px', height: '64px', marginBottom: '26px' }}>
                  <span style={{ position: 'absolute', inset: 0, borderRadius: '999px', border: '3px solid var(--m-accent-soft)' }} />
                  <span style={{ position: 'absolute', inset: 0, borderRadius: '999px', border: '3px solid transparent', borderTopColor: 'var(--m-accent)', animation: 'mBookSpin .8s linear infinite' }} />
                </span>
                <h2 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 800, fontSize: '22px', letterSpacing: '-0.01em', margin: 0, color: 'var(--m-ink)' }}>Confirming your slot…</h2>
                <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '14px', color: 'var(--m-ink-faint)', margin: '10px 0 0' }}>Locking in {longDate} at {time}.</p>
              </div>
            ) : done ? (
              <div style={{ padding: '70px 30px', textAlign: 'center', animation: 'mBookFadeIn .4s ease' }}>
                <span style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '72px', height: '72px', borderRadius: '999px', background: 'var(--m-accent)', marginBottom: '22px', boxShadow: '0 0 0 8px var(--m-accent-soft), 0 12px 30px -10px color-mix(in srgb, var(--m-accent) 70%, transparent)' }}>
                  <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
                </span>
                <h2 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 800, fontSize: '30px', letterSpacing: '-0.02em', margin: '0 0 14px', color: 'var(--m-ink)' }}>You're booked.</h2>
                <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '16px', color: 'var(--m-ink-soft)', lineHeight: 1.7, margin: '0 auto 8px', maxWidth: '440px' }}>
                  <strong style={{ color: 'var(--m-ink)' }}>{service.t}</strong> · {service.dur}<br />
                  {longDate} at {time}<br />
                  <span style={{ fontSize: '14px', color: 'var(--m-ink-faint)' }}>{tz}</span><br />
                  <span style={{ fontSize: '14px' }}>A calendar invite and video link are on the way to <strong style={{ color: 'var(--m-ink)' }}>{form.email}</strong> from <strong style={{ color: 'var(--m-ink)' }}>grant@dunngames.com</strong>.</span>
                </p>
                <div style={{ marginTop: '26px', display: 'flex', justifyContent: 'center' }}><BPill variant="ghost" size="sm" onClick={reset}>Book another</BPill></div>
              </div>
            ) : showForm ? (
              <div className="min-book-grid" style={{ display: 'grid', gridTemplateColumns: '0.82fr 1.18fr' }}>
                {/* summary sidebar */}
                <div style={{ padding: 'clamp(28px, 3vw, 40px)', borderRight: '1px solid var(--m-line)', background: 'var(--m-page-2)', display: 'flex', flexDirection: 'column' }}>
                  <div style={label}>Your booking</div>
                  <h2 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 800, fontSize: '24px', letterSpacing: '-0.02em', margin: '0 0 20px', color: 'var(--m-ink)' }}>{service.t}</h2>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '14px', marginBottom: '22px' }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
                      <span style={{ width: '34px', height: '34px', flexShrink: 0, borderRadius: '10px', background: 'var(--m-accent-soft)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="var(--m-accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4.5" width="18" height="16" rx="2.5"/><path d="M3 9h18M8 2.5v4M16 2.5v4"/></svg>
                      </span>
                      <div><div style={{ fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '14px', color: 'var(--m-ink)', lineHeight: 1.3 }}>{longDate}</div>
                        <div style={{ fontFamily: 'var(--m-font-body)', fontSize: '13px', color: 'var(--m-ink-soft)' }}>{time} · {service.dur}</div></div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
                      <span style={{ width: '34px', height: '34px', flexShrink: 0, borderRadius: '10px', background: 'var(--m-accent-soft)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="var(--m-accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 10l5-3v10l-5-3z"/><rect x="3" y="6" width="12" height="12" rx="2.5"/></svg>
                      </span>
                      <div><div style={{ fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '14px', color: 'var(--m-ink)', lineHeight: 1.3 }}>Video call</div>
                        <div style={{ fontFamily: 'var(--m-font-body)', fontSize: '13px', color: 'var(--m-ink-soft)' }}>Link sent on confirm</div></div>
                    </div>
                  </div>
                  <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: '11px', padding: '16px 0', borderTop: '1px solid var(--m-line)', marginTop: 'auto' }}>
                    <HostChip host={host} />
                  </div>
                </div>
                {/* form */}
                <div style={{ padding: 'clamp(28px, 3vw, 40px)' }}>
                  <h3 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '17px', margin: '0 0 4px', color: 'var(--m-ink)' }}>Tell us about your project</h3>
                  <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '13.5px', color: 'var(--m-ink-faint)', margin: '0 0 22px' }}>So we can make the most of your {service.dur}.</p>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                    {renderField(M_EMAIL)}
                    {fields.map(renderField)}
                  </div>
                  {submitted && !canSubmit ? <p style={{ color: '#E5484D', fontSize: '13px', fontWeight: 600, margin: '14px 0 0' }}>Please fill in the required fields (marked *) with a valid email.</p> : null}
                  <div style={{ display: 'flex', gap: '10px', marginTop: '24px' }}>
                    <BPill variant="ghost" size="sm" onClick={() => { setShowForm(false); setSubmitted(false); }}>Back</BPill>
                    <BPill variant="accent" size="sm" arrow onClick={submit} style={{ flex: 1, justifyContent: 'center' }}>Confirm booking</BPill>
                  </div>
                </div>
              </div>
            ) : (
              <div className="min-book-grid" style={{ display: 'grid', gridTemplateColumns: '0.9fr 1.2fr 0.95fr' }}>
                {/* details */}
                <div style={{ padding: '30px', borderRight: '1px solid var(--m-line)' }}>
                  <h2 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 800, fontSize: '22px', letterSpacing: '-0.02em', margin: '0 0 12px', color: 'var(--m-ink)' }}>{service.t}</h2>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '18px' }}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: '9px', color: 'var(--m-ink-soft)', fontSize: '14px' }}><span style={{ width: '6px', height: '6px', borderRadius: '50%', background: 'var(--m-accent)' }}></span>{service.dur} session</span>
                    <span style={{ display: 'flex', alignItems: 'center', gap: '9px', color: 'var(--m-ink-soft)', fontSize: '14px' }}><span style={{ width: '6px', height: '6px', borderRadius: '50%', background: 'var(--m-ink-faint)' }}></span>Video call · link on confirm</span>
                  </div>
                  <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '14px', lineHeight: 1.6, color: 'var(--m-ink-soft)', margin: '0 0 20px' }}>{service.d}</p>
                  <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: '11px', padding: '12px 0', borderTop: '1px solid var(--m-line)', borderBottom: '1px solid var(--m-line)', marginBottom: '20px' }}>
                    <HostChip host={host} />
                  </div>
                  <div style={label}>Switch service</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                    {M_SERVICES.map((s, i) => (
                      <button key={s.t} onClick={() => setSvc(i)} style={{ display: 'flex', alignItems: 'center', gap: '11px', textAlign: 'left', padding: '11px 13px', borderRadius: '12px', cursor: 'pointer', border: '1px solid ' + (svc === i ? 'var(--m-accent)' : 'var(--m-line)'), background: svc === i ? 'var(--m-accent-soft)' : 'var(--m-page)' }}>
                        <span style={{ fontFamily: 'var(--m-font-display)', fontWeight: 800, fontSize: '12px', color: svc === i ? 'var(--m-accent)' : 'var(--m-ink-faint)' }}>{'0' + (i + 1)}</span>
                        <span style={{ fontFamily: 'var(--m-font-body)', fontWeight: 600, fontSize: '13px', color: 'var(--m-ink)' }}>{s.t}</span>
                      </button>
                    ))}
                  </div>
                </div>
                {/* calendar */}
                <div style={{ padding: '30px', borderRight: '1px solid var(--m-line)' }}>
                  <h3 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '18px', margin: '0 0 4px', color: 'var(--m-ink)' }}>Select a date</h3>
                  <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '12.5px', color: 'var(--m-ink-faint)', margin: '0 0 16px' }}>Available Tue–Fri · times shown in Central</p>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '14px' }}>
                    {arrowBtn('‹', prev, atMin)}
                    <span style={{ fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '16px', color: 'var(--m-ink)' }}>{M_MON[view.m]} {view.y}</span>
                    {arrowBtn('›', next, false)}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: '4px', marginBottom: '6px' }}>
                    {M_WD.map((w) => <div key={w} style={{ textAlign: 'center', fontSize: '11px', fontWeight: 700, color: 'var(--m-ink-faint)' }}>{w}</div>)}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: '4px' }}>
                    {cells.map((d, i) => <React.Fragment key={i}>{dayBtn(d)}</React.Fragment>)}
                  </div>
                  <div style={{ marginTop: '20px' }}>
                    <div style={label}>Time zone</div>
                    <div style={{ position: 'relative' }}>
                      <button type="button" onClick={() => setTzOpen((o) => !o)} onBlur={() => setTimeout(() => setTzOpen(false), 120)}
                        style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '10px', padding: '11px 14px', borderRadius: '12px', border: '1px solid ' + (tzOpen ? 'var(--m-accent)' : 'var(--m-line)'), background: 'var(--m-page-2)', color: 'var(--m-ink)', fontFamily: 'var(--m-font-body)', fontWeight: 600, fontSize: '14px', cursor: 'pointer', textAlign: 'left' }}>
                        <span>{tz}</span>
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, transform: tzOpen ? 'rotate(180deg)' : 'none', transition: 'transform .18s ease', color: 'var(--m-ink-faint)' }}><path d="M6 9l6 6 6-6"/></svg>
                      </button>
                      {tzOpen ? (
                        <div style={{ position: 'absolute', bottom: 'calc(100% + 6px)', left: 0, right: 0, zIndex: 20, background: 'var(--m-page)', border: '1px solid var(--m-line)', borderRadius: '14px', boxShadow: 'var(--m-shadow-card)', padding: '6px', overflow: 'hidden' }}>
                          {M_TZ.map((o) => {
                            const on = o === tz;
                            return (
                              <button key={o} type="button" onMouseDown={(e) => { e.preventDefault(); setTz(o); setTzOpen(false); }}
                                style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '10px', padding: '11px 12px', borderRadius: '9px', border: 'none', cursor: 'pointer', textAlign: 'left', background: on ? 'var(--m-accent)' : 'transparent', color: on ? '#fff' : 'var(--m-ink)', fontFamily: 'var(--m-font-body)', fontWeight: on ? 700 : 500, fontSize: '14px' }}
                                onMouseEnter={(e) => { if (!on) e.currentTarget.style.background = 'var(--m-page-2)'; }}
                                onMouseLeave={(e) => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
                                <span style={{ whiteSpace: 'nowrap' }}>{o}</span>
                                {on ? <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M20 6L9 17l-5-5"/></svg> : null}
                              </button>
                            );
                          })}
                        </div>
                      ) : null}
                    </div>
                  </div>
                </div>
                {/* times */}
                <div style={{ padding: '30px' }}>
                  {!sel ? (
                    <div style={{ height: '100%', minHeight: '260px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
                      <span style={{ width: '52px', height: '52px', borderRadius: '14px', background: 'var(--m-accent-soft)', border: '1px solid var(--m-line)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: '16px' }}>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--m-accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4.5" width="18" height="16" rx="2.5"/><path d="M3 9h18M8 2.5v4M16 2.5v4"/><circle cx="12" cy="14.5" r="2.2"/></svg>
                      </span>
                      <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '14px', color: 'var(--m-ink-faint)', margin: 0, maxWidth: '180px', lineHeight: 1.5 }}>Pick a day on the calendar to see available times.</p>
                    </div>
                  ) : (
                    <React.Fragment>
                      <h3 style={{ fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '16px', margin: '0 0 14px', color: 'var(--m-ink)' }}>{longDate}</h3>
                      {bookErr ? <p style={{ color: '#E5484D', fontSize: '13px', fontWeight: 600, margin: '0 0 12px' }}>{bookErr}</p> : null}
                      {slots.length === 0 ? (
                        <p style={{ fontFamily: 'var(--m-font-body)', fontSize: '14px', color: 'var(--m-ink-faint)', margin: 0, lineHeight: 1.5 }}>{availLoading ? 'Loading times…' : 'No open times left for this day.'}</p>
                      ) : (
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '9px' }}>
                        {slots.map((s) => {
                          if (time === s) {
                            return (
                              <div key={s} style={{ display: 'flex', gap: '8px' }}>
                                <button onClick={() => setTime(null)} style={{ flex: 1, padding: '13px 0', borderRadius: '12px', border: '1px solid var(--m-line)', background: 'var(--m-page-2)', color: 'var(--m-ink)', fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '14px', cursor: 'pointer' }}>{s}</button>
                                <button onClick={confirmSlot} style={{ flex: 1, padding: '13px 0', borderRadius: '12px', border: '1px solid var(--m-accent)', background: 'var(--m-accent)', color: '#fff', fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '14px', cursor: 'pointer' }}>Confirm</button>
                              </div>
                            );
                          }
                          return <button key={s} onClick={() => setTime(s)} style={{ width: '100%', padding: '13px 0', borderRadius: '12px', border: '1px solid var(--m-line)', background: 'var(--m-page)', color: 'var(--m-accent)', fontFamily: 'var(--m-font-display)', fontWeight: 700, fontSize: '14px', cursor: 'pointer' }} onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--m-accent)'} onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--m-line)'}>{s}</button>;
                        })}
                      </div>
                      )}
                    </React.Fragment>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </main>
    </React.Fragment>
  );
}

window.MINBooking = { BookingPage };
