// Molara — fresh patient dashboard

function PatientDashboard({ tone = 'warm' }) {
  const { user } = useAuth();
  const consults = useConsults();
  const consult = consults[0] || null;
  const doc = consult ? DOC_BY_ID(consult.docId) : null;
  const completed = consult ? patientConsultIsCompleted(consult) : false;
  const hasRx = !!(consult?.prescription || consult?.prescribed);
  const anyRx = consults.some((c) => c?.prescription || c?.prescribed);
  const unreadRx = window.unreadPrescriptionCount ? window.unreadPrescriptionCount(consults) : 0;
  const pendingCount = consults.filter((c) => !patientConsultIsCompleted(c)).length;
  const followupConsult = consults.find((c) => c?.prescription || c?.prescribed) || null;
  const canFollowUp = !!followupConsult?.docId;
  const followupRoute = canFollowUp ? `/book?doctor=${encodeURIComponent(followupConsult.docId)}&followup=1&from=${encodeURIComponent(followupConsult.id)}` : '/appointments';

  return (
    <PortalShell
      active="home"
      title={`Good afternoon, ${user?.name?.split(' ')[0] || 'there'}`}
      subtitle={consult ? (completed ? 'Your consultation is complete.' : 'Your dental consultation is booked.') : 'Welcome to Molara. Start by booking your first dental consult.'}
      action={
        <button onClick={() => window.navigate && window.navigate('/find')} className="ml-btn ml-btn--primary" style={{ marginRight: 4 }}>
          <I.plus size={13}/> New consult
        </button>
      }
    >
      <div style={{ padding: '24px 32px 40px', maxWidth: 1180 }}>
        {unreadRx > 0 && (
          <button onClick={() => window.navigate && window.navigate('/prescriptions')} className="ml-card" style={{
            width: '100%',
            padding: 16,
            marginBottom: 16,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 14,
            border: '1px solid oklch(82% 0.06 165)',
            background: 'oklch(97% 0.035 165)',
            color: 'var(--ink)',
            textAlign: 'left',
            cursor: 'pointer',
          }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, fontWeight: 600 }}>
              <span style={{ width: 10, height: 10, borderRadius: 999, background: '#c92a2a', boxShadow: '0 0 0 4px rgba(201,42,42,0.12)' }}/>
              Prescription uploaded
            </span>
            <span style={{ color: 'var(--ink-3)', fontSize: 12.5 }}>Open prescriptions</span>
          </button>
        )}
        {consult ? (
          <div className="ml-card" style={{ padding: 0, marginBottom: 22, overflow: 'hidden', display: 'grid', gridTemplateColumns: '1.25fr 0.9fr' }}>
            <div style={{ padding: 30, background: 'var(--ink)', color: '#fff' }}>
              <span className="ml-pill" style={{ background: 'oklch(40% 0.03 240)', color: '#fff' }}>
                <span className={completed ? '' : 'ml-live'}/> {completed ? 'Completed' : 'Confirmed'}
              </span>
              <h2 style={{ fontSize: 32, color: '#fff', margin: '14px 0 6px', letterSpacing: '-0.02em' }}>
                {(window.bookingModeLabel ? window.bookingModeLabel(consult.mode) : 'WhatsApp consult')} with <span style={{ fontStyle: 'italic', color: 'oklch(85% 0.1 240)' }}>{doc.n}</span>
              </h2>
              <div style={{ color: 'oklch(80% 0.02 240)', fontSize: 14, marginBottom: 20 }}>
                {consult.reason} · {consult.date} · {consult.time}
              </div>
              {completed && (
                <div style={{ color: 'oklch(82% 0.02 240)', fontSize: 12.5, margin: '-10px 0 18px' }}>
                  Actual consultation: {consult.date} · {consult.time}
                </div>
              )}
              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => window.navigate && window.navigate('/appointments')} className="ml-btn" style={{ background: 'transparent', color: '#fff', border: '1px solid oklch(40% 0.03 240)' }}>
                  View booking
                </button>
                {hasRx && (
                  <button onClick={() => window.navigate && window.navigate('/prescriptions')} className="ml-btn" style={{ background: 'transparent', color: '#fff', border: '1px solid oklch(40% 0.03 240)' }}>
                    <I.doc size={13}/> Prescription
                  </button>
                )}
                {canFollowUp && (
                  <button onClick={() => window.navigate && window.navigate(followupRoute)} className="ml-btn" style={{ background: '#fff', color: 'var(--ink)' }}>
                    <I.chat size={13}/> Follow-up
                  </button>
                )}
              </div>
            </div>
            <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div className="ml-label">WHAT THE DENTIST WILL SEE</div>
              {[
                ['Reason', consult.reason],
                ['Pain level', `${consult.severity} / 10`],
                ['Care type', consult.careType],
                ['Note', consult.note || 'No extra note added'],
              ].map(([k, v]) => (
                <div key={k} style={{ display: 'grid', gridTemplateColumns: '90px 1fr', gap: 10, fontSize: 13 }}>
                  <span className="ml-muted">{k}</span>
                  <span>{v}</span>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div className="ml-card" style={{ padding: 54, textAlign: 'center', marginBottom: 22 }}>
            <div style={{ width: 62, height: 62, borderRadius: 18, background: 'var(--blue-soft)', color: 'var(--blue-deep)', display: 'grid', placeItems: 'center', margin: '0 auto 18px' }}>
              <I.tooth size={28}/>
            </div>
            <h2 style={{ fontSize: 32, marginBottom: 10 }}>No consultations yet.</h2>
            <p className="ml-muted" style={{ fontSize: 15, maxWidth: 520, margin: '0 auto 24px', lineHeight: 1.6 }}>
              Book your first dental consultation. After you confirm it, the same booking will appear in your dentist's dashboard.
            </p>
            <button onClick={() => window.navigate && window.navigate('/find')} className="ml-btn ml-btn--primary" style={{ margin: '0 auto' }}>
              Book consultation <I.arrowR size={14}/>
            </button>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {[
            ['Find a dentist', 'Browse online dentists', I.search, '/find'],
            ['My appointments', pendingCount ? `${pendingCount} upcoming` : (consults.length ? 'All consultations completed' : 'No bookings yet'), I.calendar, '/appointments'],
            ['Follow-up', canFollowUp ? 'Book with same dentist' : 'Available after prescription upload', I.chat, followupRoute],
            ['Prescriptions', unreadRx > 0 ? `${unreadRx} new prescription${unreadRx === 1 ? '' : 's'}` : (anyRx ? 'Prescription ready' : 'After your consult'), I.doc, '/prescriptions'],
            ['Dental records', 'Uploaded files and records', I.doc, '/records'],
          ].map(([title, sub, Icon, route]) => (
            <button key={title} onClick={() => window.navigate && window.navigate(route)} className="ml-card" style={{ padding: 20, textAlign: 'left', border: '1px solid var(--line)', background: '#fff', cursor: 'pointer', display: 'flex', gap: 14, alignItems: 'center' }}>
              <div style={{ width: 42, height: 42, borderRadius: 10, background: 'var(--paper-2)', color: 'var(--blue-deep)', display: 'grid', placeItems: 'center' }}>
                <Icon size={18}/>
              </div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{title}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{sub}</div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </PortalShell>
  );
}

function patientConsultIsCompleted(c) {
  if (!c) return false;
  if (c.status === 'completed' || c.status === 'awaiting-prescription' || c.prescription || c.prescribed || c.closedAt || c.completedAt || c.endedAt) return true;
  const startMs = window.consultStartMs ? window.consultStartMs(c) : new Date(c.createdAt || 0).getTime();
  return !!(startMs && Date.now() >= startMs + 15 * 60 * 1000);
}

Object.assign(window, { PatientDashboard });
