// My Appointments — fresh state backed by the current patient booking

function MyAppointments() {
  const consults = useConsults();
  const upcoming = consults.map(consultToAppointment);

  return (
    <PortalShell active="appointments" title="My Appointments" subtitle="Your booked dental consultations"
      action={<button onClick={() => window.navigate && window.navigate('/book')} className="ml-btn ml-btn--primary"><I.plus size={14}/> Book new</button>}>
      <div style={{ padding: '24px 32px', maxWidth: 1100 }}>
        <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--line)', marginBottom: 22 }}>
          {[
            { label: 'Upcoming', count: upcoming.length, on: true },
            { label: 'Completed', count: 0 },
            { label: 'Cancelled', count: 0 },
          ].map(t => (
            <button key={t.label} style={{
              background: 'transparent', border: 'none',
              padding: '12px 16px', fontSize: 13.5,
              color: t.on ? 'var(--ink)' : 'var(--ink-3)',
              fontWeight: t.on ? 500 : 400, fontFamily: 'var(--sans)',
              borderBottom: t.on ? '2px solid var(--blue)' : '2px solid transparent',
              marginBottom: -1, display: 'flex', alignItems: 'center', gap: 6,
            }}>
              {t.label}
              <span style={{
                background: t.on ? 'var(--blue-soft)' : 'var(--paper-2)',
                color: t.on ? 'var(--blue-deep)' : 'var(--ink-3)',
                padding: '1px 7px', borderRadius: 999, fontSize: 11,
              }}>{t.count}</span>
            </button>
          ))}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {upcoming.map(a => <AppointmentRow key={a.id} a={a}/>)}
          {upcoming.length === 0 && (
            <FreshEmptyState
              title="No consultations booked yet."
              body="Once you book your first dental consult, it will appear here and in the dentist's queue."
              actionLabel="Find a dentist"
              actionRoute="/find"
            />
          )}
        </div>
      </div>
    </PortalShell>
  );
}

function consultToAppointment(c) {
  return {
    id: c.id,
    consult: c,
    doc: DOC_BY_ID(c.docId),
    date: c.date,
    time: c.time,
    mode: c.mode,
    reason: c.reason,
    severity: c.severity,
    note: c.note,
    status: 'Confirmed',
  };
}

function AppointmentRow({ a }) {
  const ModeIcon = a.mode === 'video' ? I.video : a.mode === 'audio' ? I.mic : I.chat;
  // Joinability: paid OR follow-up window. We pass the original consult through so we
  // can read paymentStatus/docId straight off it.
  const j = a.consult && window.consultIsJoinable ? window.consultIsJoinable(a.consult) : { ok: true };
  const needsPay = !j.ok && j.reason === 'unpaid';

  const onJoin = () => {
    if (needsPay) {
      window.navigate && window.navigate('/pay?consult=' + encodeURIComponent(a.id));
    } else {
      window.navigate && window.navigate('/visit?consult=' + encodeURIComponent(a.id));
    }
  };

  return (
    <div className="ml-card" style={{
      padding: 20, display: 'grid',
      gridTemplateColumns: '64px 1.4fr 1fr auto', alignItems: 'center', gap: 18,
    }}>
      <div className="ml-avatar" style={{ width: 56, height: 56, borderRadius: '50%', fontSize: 18,
        background: TONE_BG[a.doc.tone], color: TONE_FG[a.doc.tone] }}>{a.doc.avatar}</div>

      <div>
        <div style={{ fontSize: 15, fontWeight: 500 }}>{a.doc.n}</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{a.doc.spec} · {a.doc.creds}</div>
        <div style={{ display: 'flex', gap: 6, marginTop: 8, fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-4)' }}>
          {a.id} · {a.reason}
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <I.calendar size={14} color="var(--ink-3)"/>
          <span style={{ fontSize: 13.5 }}>{a.date} · {a.time}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <ModeIcon size={14} color="var(--ink-3)"/>
          <span style={{ fontSize: 13, color: 'var(--ink-2)', textTransform: 'capitalize' }}>{a.mode} consult</span>
        </div>
        <div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
          <span className="ml-pill ml-pill--mint" style={{ alignSelf: 'flex-start' }}>{a.status}</span>
          {needsPay
            ? <span className="ml-pill" style={{ alignSelf: 'flex-start', background: 'oklch(95% 0.05 25)', color: 'oklch(40% 0.14 25)' }}>Payment due</span>
            : (j.viaFollowup
                ? <span className="ml-pill" style={{ alignSelf: 'flex-start', background: 'oklch(95% 0.06 165)', color: 'oklch(38% 0.10 165)' }}>Free follow-up</span>
                : <span className="ml-pill" style={{ alignSelf: 'flex-start', background: 'oklch(95% 0.06 165)', color: 'oklch(38% 0.10 165)' }}>Paid</span>)}
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end' }}>
        <button onClick={onJoin} className="ml-btn ml-btn--primary" style={{ padding: '8px 14px', fontSize: 12.5 }}>
          {needsPay ? <><I.lock size={13}/> Pay &amp; join</> : <><ModeIcon size={13}/> Join</>}
        </button>
        <button onClick={() => window.navigate && window.navigate('/book')} className="ml-btn ml-btn--link" style={{ fontSize: 12 }}>Reschedule</button>
      </div>
    </div>
  );
}

function FreshEmptyState({ title, body, actionLabel, actionRoute }) {
  return (
    <div className="ml-card" style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)' }}>
      <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--blue-soft)', color: 'var(--blue-deep)', display: 'grid', placeItems: 'center', margin: '0 auto 16px' }}>
        <I.calendar size={22}/>
      </div>
      <h2 style={{ fontSize: 24, marginBottom: 8, color: 'var(--ink)' }}>{title}</h2>
      <p style={{ margin: '0 auto 20px', maxWidth: 420, fontSize: 14, lineHeight: 1.55 }}>{body}</p>
      <button onClick={() => window.navigate && window.navigate(actionRoute)} className="ml-btn ml-btn--primary" style={{ justifyContent: 'center', margin: '0 auto' }}>
        {actionLabel} <I.arrowR size={13}/>
      </button>
    </div>
  );
}

window.MyAppointments = MyAppointments;
