// Molara — Booking flow (multi-step, stateful)

// Dental-care grouped reasons. Keys (k) match DOCTORS[i].k so we can shortlist matching dentists.
const REASON_GROUPS = [
  { k: 'emergency', label: 'Emergency 24/7',       icon: 'shield',   reasons: ['Severe tooth ache', 'Swelling or abscess', 'Broken or chipped tooth', 'Wisdom tooth flare-up', 'Bleeding after dental work', 'Other issue'] },
  { k: 'toothache', label: 'Tooth ache',           icon: 'tooth',    reasons: ['Cold sensitivity', 'Pain while chewing', 'Cavity concern', 'Root canal second opinion', 'Gum bleeding', 'Other issue'] },
  { k: 'kids',      label: 'Kids tooth care',      icon: 'baby',     reasons: ['Child tooth pain', 'Milk tooth concern', 'Cavity prevention', 'Teething advice', 'Dental anxiety', 'Other issue'] },
  { k: 'aligners',  label: 'Aligners & braces',   icon: 'settings', reasons: ['Clear aligner opinion', 'Braces consultation', 'Retainer concern', 'Bite correction', 'Mid-treatment review', 'Other issue'] },
  { k: 'cosmetic',  label: 'Whitening & cosmetic',icon: 'sparkle',  reasons: ['Teeth whitening', 'Smile design', 'Veneers opinion', 'Chipped tooth bonding', 'Stain or discoloration', 'Other issue'] },
];

const BOOKING_SLOTS = {
  Morning: ['9:00a','9:30a','10:15a','11:00a','11:45a'],
  Afternoon: ['1:00p','1:45p','2:15p','3:00p','3:45p','4:30p'],
  Evening: ['5:15p','6:00p','6:45p','7:30p'],
};

function slotToMinutes(slot) {
  const m = /^(\d{1,2}):(\d{2})(a|p)$/i.exec(String(slot || '').trim());
  if (!m) return 0;
  let h = Number(m[1]);
  const min = Number(m[2]);
  const mer = m[3].toLowerCase();
  if (mer === 'p' && h !== 12) h += 12;
  if (mer === 'a' && h === 12) h = 0;
  return h * 60 + min;
}

function formatBookingDay(offset) {
  const d = new Date();
  d.setDate(d.getDate() + offset);
  const month = d.toLocaleDateString('en-IN', { month: 'short' });
  const day = d.getDate();
  if (offset === 0) return `Today · ${month} ${day}`;
  if (offset === 1) return `Tomorrow · ${month} ${day}`;
  const weekday = d.toLocaleDateString('en-IN', { weekday: 'short' });
  return `${weekday} · ${month} ${day}`;
}

function bookingDaysFromToday() {
  return [0, 1, 2, 3].map(formatBookingDay);
}

function nextBookingSlot() {
  const now = new Date();
  const currentMinutes = now.getHours() * 60 + now.getMinutes();
  const allSlots = Object.values(BOOKING_SLOTS).flat();
  const future = allSlots.find((s) => slotToMinutes(s) > currentMinutes + 30);
  return future || allSlots[0];
}

function bookingRouteParams(route) {
  const q = (route || window.location.hash.replace(/^#/, '') || '').split('?')[1] || '';
  return new URLSearchParams(q);
}

function BookingFlow({ tone = 'warm', route = '' }) {
  const { user } = useAuth();
  useDoctorReviews();
  const routeParams = bookingRouteParams(route);
  const hasRequestedDoctor = routeParams.has('doctor');
  const requestedDocId = Number(routeParams.get('doctor'));
  const requestedFollowup = routeParams.get('followup') === '1';
  const requestedDoc = hasRequestedDoctor && Number.isFinite(requestedDocId) ? DOC_BY_ID(requestedDocId) : null;
  const doctorLocked = !!requestedDoc;
  const [step, setStep] = React.useState(1);
  const [specK, setSpecK] = React.useState(requestedDoc?.k || 'emergency');
  const [reason, setReason] = React.useState('Severe tooth ache');
  const [severity, setSev] = React.useState(2);
  const [slot, setSlot] = React.useState(() => nextBookingSlot());
  const [day, setDay] = React.useState(() => slotToMinutes(nextBookingSlot()) === slotToMinutes(BOOKING_SLOTS.Morning[0]) && new Date().getHours() >= 19 ? 1 : 0);
  const [docId, setDocId] = React.useState(requestedDoc?.id || 1);
  const [mode, setMode] = React.useState('video');
  const [note, setNote] = React.useState('');
  const doc = DOC_BY_ID(docId);
  const BOOKING_DAYS = React.useMemo(() => bookingDaysFromToday(), []);
  const selectedDay = BOOKING_DAYS[day] || BOOKING_DAYS[0];
  const selectedTime = formatSlot(slot);
  const visitFee = doc.fee + (mode === 'audio' ? -100 : mode === 'chat' ? -150 : 0);
  const activeGroup = REASON_GROUPS.find(g => g.k === specK) || REASON_GROUPS[0];
  const availableReasonGroups = doctorLocked
    ? REASON_GROUPS.filter((g) => doctorMatchesSpec(requestedDoc, g.k))
    : REASON_GROUPS;
  const flowSteps = doctorLocked
    ? [{ key: 1, label: 'Symptoms' }, { key: 3, label: 'Mode & Time' }, { key: 4, label: 'Confirm' }]
    : [{ key: 1, label: 'Symptoms' }, { key: 2, label: 'Dentist' }, { key: 3, label: 'Mode & Time' }, { key: 4, label: 'Confirm' }];
  const currentStepIndex = Math.max(0, flowSteps.findIndex((s) => s.key === step));
  const goPrev = () => setStep(flowSteps[Math.max(0, currentStepIndex - 1)].key);
  const goNext = () => setStep(flowSteps[Math.min(flowSteps.length - 1, currentStepIndex + 1)].key);
  const isFinalStep = step === flowSteps[flowSteps.length - 1].key;
  // Shortlist: prefer dentists for the chosen care type, then top-rated online others.
  const shortlist = React.useMemo(() => {
    const matched = DOCTORS.filter(d => d.online && doctorMatchesSpec(d, specK));
    const others  = DOCTORS.filter(d => d.online && !doctorMatchesSpec(d, specK)).sort((a,b) => Number(doctorStats(b).rating) - Number(doctorStats(a).rating));
    return [...matched, ...others].slice(0, 4);
  }, [specK]);
  React.useEffect(() => {
    if (!requestedDoc) return;
    setDocId(requestedDoc.id);
    setSpecK(requestedDoc.k);
    const group = REASON_GROUPS.find(g => g.k === requestedDoc.k) || REASON_GROUPS[0];
    setReason(group.reasons[0]);
    setStep((s) => s === 2 ? 3 : s);
  }, [requestedDoc?.id]);
  // When care type changes, default-pick the first matched dentist so step 2 makes sense.
  React.useEffect(() => {
    if (doctorLocked) return;
    if (shortlist[0] && !shortlist.some(d => d.id === docId)) setDocId(shortlist[0].id);
  }, [specK, doctorLocked]);

  return (
    <div className="ml-root" style={{ height: '100%', overflow: 'hidden', display: 'grid', gridTemplateColumns: '1fr 420px' }}>
      {/* Left: form */}
      <div style={{ padding: '32px 56px 32px', overflowY: 'auto' }}>
        {/* Top bar */}
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 32 }}>
          <Logo size={20}/>
          <div style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <I.shield size={13}/> Encrypted · HIPAA
          </div>
        </div>

        {/* Stepper */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 32 }}>
          {flowSteps.map((s, i) => {
            const active = s.key === step;
            const done = i < currentStepIndex;
            return (
              <div key={s.key} style={{ flex: 1 }}>
                <div style={{ height: 3, borderRadius: 2, background: done || active ? 'var(--blue)' : 'var(--line)' }}/>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 8, fontSize: 12, color: active ? 'var(--ink)' : 'var(--ink-3)' }}>
                  <span style={{ width: 18, height: 18, borderRadius: 9, fontSize: 10, display: 'grid', placeItems: 'center', background: done ? 'var(--blue)' : active ? 'var(--ink)' : 'var(--line-2)', color: done || active ? '#fff' : 'var(--ink-3)', fontFamily: 'var(--mono)' }}>
                    {done ? <I.check size={10}/> : i + 1}
                  </span>
                  {s.label}
                </div>
              </div>
            );
          })}
        </div>

        {step === 1 && (
          <section>
            <h1 style={{ fontSize: 40, marginBottom: 8 }}>
              {tone === 'warm' ? 'What dental issue brings you in today?' : 'Describe your dental concern.'}
            </h1>
            <p style={{ color: 'var(--ink-3)', marginBottom: 28 }}>
              {tone === 'warm' ? 'Pick what sounds closest — you can explain more in a minute.' : 'Select the dental category that best matches. Additional details collected next.'}
            </p>
            <div className="ml-label" style={{ marginBottom: 10 }}>Dental care type</div>

            {/* Dental care tabs */}
            <div style={{ display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
              {availableReasonGroups.map((g) => {
                const Ic = I[g.icon];
                const active = g.k === specK;
                return (
                  <button key={g.k}
                    onClick={() => { setSpecK(g.k); setReason(g.reasons[0]); }}
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      padding: '8px 12px', borderRadius: 999, fontSize: 12, fontWeight: 500,
                      border: '1px solid ' + (active ? 'var(--ink)' : 'var(--line)'),
                      background: active ? 'var(--ink)' : '#fff',
                      color: active ? '#fff' : 'var(--ink-2)',
                      cursor: 'pointer', whiteSpace: 'nowrap',
                    }}>
                    {Ic && <Ic size={13}/>}
                    {g.label}
                  </button>
                );
              })}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10, marginBottom: 28 }}>
              {activeGroup.reasons.map((r) => (
                <button key={r} onClick={() => setReason(r)}
                  className="ml-card"
                  style={{ padding: 16, textAlign: 'left', border: '1px solid ' + (reason === r ? 'var(--blue)' : 'var(--line)'),
                    background: reason === r ? 'var(--blue-tint)' : '#fff', cursor: 'pointer', fontWeight: 500, fontSize: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ width: 16, height: 16, borderRadius: 8, border: '1.5px solid ' + (reason === r ? 'var(--blue)' : 'var(--ink-4)'),
                    background: reason === r ? 'var(--blue)' : 'transparent', display: 'grid', placeItems: 'center' }}>
                    {reason === r && <span style={{ width: 6, height: 6, borderRadius: 3, background: '#fff' }}/>}
                  </span>
                  {r}
                </button>
              ))}
            </div>

            <div className="ml-label" style={{ marginBottom: 10 }}>Pain level (if applicable)</div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              {[0,1,2,3,4,5,6,7,8,9,10].map((n) => (
                <button key={n} onClick={() => setSev(n)}
                  style={{ flex: 1, padding: '10px 0', border: '1px solid var(--line)', background: n === severity ? 'var(--ink)' : '#fff',
                    color: n === severity ? '#fff' : 'var(--ink)', borderRadius: 6, fontFamily: 'var(--mono)', fontSize: 13, cursor: 'pointer' }}>
                  {n}
                </button>
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', marginBottom: 40 }}>
              <span>NONE</span><span>TOLERABLE</span><span>SEVERE</span>
            </div>

            {doctorLocked && (
              <>
                <div className="ml-card" style={{ padding: 16, display: 'grid', gridTemplateColumns: '52px 1fr auto', gap: 14, alignItems: 'center', marginBottom: 20 }}>
                  <div className="ml-avatar" style={{ width: 52, height: 52, borderRadius: 12, fontSize: 16,
                    background: TONE_BG[doc.tone], color: TONE_FG[doc.tone] }}>{doc.avatar}</div>
                  <div>
                    <div className="ml-label" style={{ marginBottom: 4 }}>Selected dentist</div>
                    <div style={{ fontFamily: 'var(--display)', fontSize: 20, fontWeight: 500 }}>{doc.n}</div>
                    <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{doc.spec} · {doc.wait || '5 min'} wait</div>
                  </div>
                  <span className="ml-pill ml-pill--mint"><span className="ml-live"/> Online</span>
                </div>

                <div className="ml-label" style={{ marginBottom: 10 }}>Anything else {doc.n} should know? (optional)</div>
                <textarea className="ml-input" rows={3} placeholder="Sharp pain on my upper right tooth when I drink cold water. Started Tuesday..."
                  value={note} onChange={(e) => setNote(e.target.value)}
                  style={{ resize: 'none', marginBottom: 32, fontFamily: 'var(--sans)' }}/>
              </>
            )}
          </section>
        )}

        {!doctorLocked && step === 2 && (
          <section>
            <h1 style={{ fontSize: 40, marginBottom: 8 }}>
              {tone === 'warm' ? 'Choose your dentist.' : 'Select dentist.'}
            </h1>
            <p style={{ color: 'var(--ink-3)', marginBottom: 28 }}>
              {tone === 'warm' ? `These dentists are online now — matched for ${activeGroup.label.toLowerCase()}.` : `Dentists available now — filtered by ${activeGroup.label}.`}
            </p>

            <div style={{ display: 'grid', gap: 14, marginBottom: 28 }}>
              {shortlist.map((d) => {
                const active = d.id === docId;
                const stats = doctorStats(d);
                return (
                  <button key={d.id} onClick={() => setDocId(d.id)}
                    className="ml-card"
                    style={{ padding: 20, textAlign: 'left', border: '1px solid ' + (active ? 'var(--blue)' : 'var(--line)'),
                      background: active ? 'var(--blue-tint)' : '#fff', cursor: 'pointer',
                      boxShadow: active ? '0 0 0 3px oklch(92% 0.05 240)' : 'none',
                      display: 'grid', gridTemplateColumns: '72px 1fr auto', gap: 18, alignItems: 'center' }}>
                    <div className="ml-avatar" style={{ width: 72, height: 72, borderRadius: 12, fontSize: 22,
                      background: TONE_BG[d.tone], color: TONE_FG[d.tone] }}>{d.avatar}</div>
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                        <span style={{ fontFamily: 'var(--display)', fontSize: 22, fontWeight: 500 }}>{d.n}</span>
                        <span className="ml-pill ml-pill--ghost" style={{ fontFamily: 'var(--mono)', fontSize: 10 }}>{d.creds}</span>
                        <span className="ml-pill ml-pill--mint"><span className="ml-live"/> Online</span>
                      </div>
                      <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 8 }}>
                        {d.spec} · {d.y} yrs experience · {d.loc}
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--ink-2)', display: 'flex', gap: 14 }}>
                        <span style={bookingInline}><I.star size={12}/> <b>{stats.rating}</b> <span className="ml-quiet">({stats.reviews} reviews)</span></span>
                        <span>{d.bio}</span>
                      </div>
                    </div>
                    <span style={{ width: 20, height: 20, borderRadius: 10, border: '1.5px solid ' + (active ? 'var(--blue)' : 'var(--ink-4)'),
                      background: active ? 'var(--blue)' : 'transparent', display: 'grid', placeItems: 'center' }}>
                      {active && <I.check size={11} style={{ color: '#fff' }}/>}
                    </span>
                  </button>
                );
              })}
            </div>

            <div className="ml-label" style={{ marginBottom: 10 }}>Anything else {doc.n} should know? (optional)</div>
            <textarea className="ml-input" rows={3} placeholder="Sharp pain on my upper right tooth when I drink cold water. Started Tuesday..."
              value={note} onChange={(e) => setNote(e.target.value)}
              style={{ resize: 'none', marginBottom: 32, fontFamily: 'var(--sans)' }}/>
          </section>
        )}

        {step === 3 && (
          <section>
            <h1 style={{ fontSize: 40, marginBottom: 8 }}>
              {tone === 'warm' ? 'How and when?' : 'Select consult mode and window.'}
            </h1>
            <p style={{ color: 'var(--ink-3)', marginBottom: 24 }}>
              {doc.wait === 'No waiting time'
                ? `${doc.n} is available now. Pick how you want to consult.`
                : `${doc.n} has 14 openings across the next 3 days.`}
            </p>

            <div className="ml-label" style={{ marginBottom: 10 }}>Consult mode</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 28 }}>
              {[
                { k: 'video', icon: 'video', label: 'Video call', sub: 'Most personal · 20 min', extra: '+ ₹0' },
                { k: 'audio', icon: 'mic',   label: 'Audio only', sub: 'Low-bandwidth · 20 min', extra: '−₹100' },
                { k: 'chat',  icon: 'chat',  label: 'Chat',       sub: 'Async · within 30 min',  extra: '−₹150' },
              ].map(m => {
                const Icon = I[m.icon];
                const on = mode === m.k;
                return (
                  <button key={m.k} onClick={() => setMode(m.k)}
                    className="ml-card"
                    style={{ padding: 16, textAlign: 'left', cursor: 'pointer',
                      border: '1.5px solid ' + (on ? 'var(--blue)' : 'var(--line)'),
                      background: on ? 'var(--blue-tint)' : '#fff' }}>
                    <Icon size={22} color={on ? 'var(--blue-deep)' : 'var(--ink-2)'}/>
                    <div style={{ fontSize: 14, fontWeight: 500, marginTop: 8 }}>{m.label}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{m.sub}</div>
                    <div style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--ink-4)', marginTop: 4 }}>{m.extra}</div>
                  </button>
                );
              })}
            </div>

            <div className="ml-label" style={{ marginBottom: 10 }}>Day</div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
              {BOOKING_DAYS.map((d, i) => (
                <button key={d} onClick={() => setDay(i)}
                  style={{ padding: '12px 16px', borderRadius: 10, border: '1px solid ' + (day === i ? 'var(--ink)' : 'var(--line)'),
                    background: day === i ? 'var(--ink)' : '#fff', color: day === i ? '#fff' : 'var(--ink)', cursor: 'pointer', fontSize: 13, fontWeight: 500 }}>
                  {d}
                </button>
              ))}
            </div>

            {Object.entries(BOOKING_SLOTS).map(([period, times]) => {
              return (
                <div key={period} style={{ marginBottom: 22 }}>
                  <div className="ml-label" style={{ marginBottom: 10 }}>{period}</div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6,1fr)', gap: 8 }}>
                    {times.map((t) => (
                      <button key={t} onClick={() => setSlot(t)}
                        style={{ padding: '12px 0', borderRadius: 8, border: '1px solid ' + (slot === t ? 'var(--blue)' : 'var(--line)'),
                          background: slot === t ? 'var(--blue)' : '#fff', color: slot === t ? '#fff' : 'var(--ink)', fontFamily: 'var(--mono)', fontSize: 13, cursor: 'pointer' }}>
                        {t}
                      </button>
                    ))}
                  </div>
                </div>
              );
            })}
          </section>
        )}

        {step === 4 && (
          <section>
            <h1 style={{ fontSize: 40, marginBottom: 8 }}>
              {tone === 'warm' ? 'All set — review & confirm.' : 'Confirm appointment details.'}
            </h1>
            <p style={{ color: 'var(--ink-3)', marginBottom: 28 }}>
              You’ll get a reminder 10 minutes before. You can reschedule free until 1 hour prior.
            </p>

            <div className="ml-card" style={{ padding: 24, marginBottom: 16 }}>
              <div style={{ display: 'flex', gap: 16 }}>
                <div className="ml-photo" data-caption="DR" style={{ width: 84, height: 84, borderRadius: 10 }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 22, fontWeight: 500 }}>{doc.n}, {doc.creds}</div>
                  <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>{doc.spec} · {doc.loc} · ⭐ {doctorStats(doc).rating}</div>
                  <div style={{ marginTop: 10, display: 'flex', gap: 18, fontSize: 13, color: 'var(--ink-2)' }}>
                    <span style={bookingInline}><I.calendar size={13}/> {selectedDay} · {selectedTime}</span>
                    <span style={bookingInline}>
                      {mode === 'video' ? <I.video size={13}/> : mode === 'audio' ? <I.mic size={13}/> : <I.chat size={13}/>}
                      {mode === 'chat' ? ' Chat consult · within 30 min' : ` ${mode === 'video' ? 'Video' : 'Audio'} visit · 20 min`}
                    </span>
                  </div>
                </div>
              </div>
              <hr className="ml-hr" style={{ margin: '20px 0' }}/>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 16, fontSize: 13 }}>
                <div>
                  <div className="ml-label" style={{ marginBottom: 6 }}>Reason</div>
                  <div>{reason}</div>
                </div>
                <div>
                  <div className="ml-label" style={{ marginBottom: 6 }}>Pain level</div>
                  <div>{severity} / 10</div>
                </div>
                <div>
                  <div className="ml-label" style={{ marginBottom: 6 }}>Experience</div>
                  <div>{doc.y} years · {doc.creds}</div>
                </div>
                <div>
                  <div className="ml-label" style={{ marginBottom: 6 }}>You pay after</div>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 22 }}>₹{visitFee}<span style={{ fontSize: 12, color: 'var(--ink-3)', marginLeft: 6 }}>· {mode}</span></div>
                </div>
              </div>
            </div>

            <label style={{ display: 'flex', gap: 10, fontSize: 13, color: 'var(--ink-2)', marginBottom: 10 }}>
              <input type="checkbox" defaultChecked/>
              I consent to a telehealth visit and acknowledge the privacy policy.
            </label>
            <label style={{ display: 'flex', gap: 10, fontSize: 13, color: 'var(--ink-2)', marginBottom: 28 }}>
              <input type="checkbox" defaultChecked/>
              Text me a reminder at (•••) •••-4421.
            </label>
          </section>
        )}

        {/* Nav */}
        <div style={{ display: 'flex', gap: 10, borderTop: '1px solid var(--line)', paddingTop: 20, marginTop: 20 }}>
          <button className="ml-btn ml-btn--ghost" onClick={goPrev} disabled={currentStepIndex === 0}>
            <I.chevronL size={13}/> Back
          </button>
          <div style={{ flex: 1 }}/>
          {!isFinalStep ? (
            <button className="ml-btn ml-btn--primary" onClick={goNext}>
              Continue <I.arrowR size={13}/>
            </button>
          ) : (
            <button onClick={async () => {
              const elig = await (window.checkFollowupEligible && window.checkFollowupEligible(docId));
              const created = await (window.createConsult && window.createConsult({
                docId,
                reason,
                severity,
                mode,
                selectedDay,
                slot,
                fee: visitFee,
                careType: activeGroup.label,
                note,
                followUp: requestedFollowup || !!elig?.eligible,
                followUpFor: elig?.lastPaidConsultId || null,
                followUpFreeUntil: elig?.expiresAt || null,
                patientName: user?.name || 'New patient',
                patientInitials: user?.initials || 'PT',
              }));
              // Free follow-up: if patient paid this same dentist within 7 days, skip pay step.
              if (elig?.eligible) {
                window.navigate && window.navigate('/confirmed');
              } else {
                // Send to mock pay page for the freshly-created consult
                const id = created?.id || '';
                window.navigate && window.navigate('/pay?consult=' + encodeURIComponent(id));
              }
            }} className="ml-btn ml-btn--primary" style={{ padding: '12px 22px' }}>
              <I.check size={13}/> Confirm &amp; pay
            </button>
          )}
        </div>
      </div>

      {/* Right: summary rail */}
      <aside style={{ background: 'var(--ink)', color: '#fff', padding: 32, display: 'flex', flexDirection: 'column', gap: 24 }}>
          <div className="ml-label" style={{ color: 'oklch(75% 0.02 240)' }}>YOUR DENTAL VISIT</div>

        <div>
          <div style={{ fontSize: 11, color: 'oklch(75% 0.02 240)' }}>With</div>
          <div style={{ fontFamily: 'var(--display)', fontSize: 22, fontWeight: 500 }}>{doc.n}</div>
          <div style={{ fontSize: 12, color: 'oklch(75% 0.02 240)' }}>{doc.creds} · {doc.y} yrs experience</div>
        </div>

        <div>
          <div style={{ fontSize: 11, color: 'oklch(75% 0.02 240)', marginBottom: 4 }}>When</div>
          <div style={{ fontFamily: 'var(--display)', fontSize: 28, fontWeight: 500, letterSpacing: -0.02 + 'em' }}>
            {selectedDay} · {selectedTime}
          </div>
          <div style={{ fontSize: 12, color: 'oklch(75% 0.02 240)' }}>20 minute dental video consult</div>
        </div>

        <div style={{ background: 'oklch(30% 0.02 240)', padding: 16, borderRadius: 10, border: '1px solid oklch(35% 0.02 240)' }}>
          <div style={{ fontSize: 11, color: 'oklch(75% 0.02 240)', marginBottom: 6 }}>VISIT FEE</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
            <span style={{ fontSize: 13, textTransform: 'capitalize' }}>{mode} consult</span><span>₹{visitFee}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
            <span style={{ fontSize: 13, color: 'oklch(75% 0.02 240)' }}>Follow-up included</span><span>Free</span>
          </div>
          <hr style={{ border: 'none', height: 1, background: 'oklch(35% 0.02 240)', margin: '10px 0' }}/>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--display)', fontSize: 20 }}>
            <span>Pay after consult</span><span>₹{visitFee}</span>
          </div>
        </div>

        <div style={{ marginTop: 'auto', fontSize: 12, color: 'oklch(75% 0.02 240)', lineHeight: 1.55 }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}><I.shield size={14}/> Secure, encrypted video — nothing is recorded without your consent.</div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}><I.clock size={14}/> Free cancellation up to 1 hour before your visit.</div>
          <div style={{ display: 'flex', gap: 8 }}><I.doc size={14}/> Dental plan, Rx guidance, and clinic referrals delivered instantly.</div>
        </div>
      </aside>
    </div>
  );
}

const bookingInline = { display: 'inline-flex', alignItems: 'center', gap: 6 };

Object.assign(window, { BookingFlow });
