// Shared portal shell — sidebar + topbar — used by all logged-in artboards
// Usage: <PortalShell active="appointments"><PageContent/></PortalShell>

const NAV_ITEMS = [
  { k: 'home',         label: 'Home',           icon: 'pulse',    route: '/'             },
  { k: 'profile',      label: 'Profile',        icon: 'user',     route: '/profile'      },
  { k: 'appointments', label: 'Appointments',   icon: 'calendar', route: '/appointments' },
  { k: 'prescriptions', label: 'Prescriptions', icon: 'doc',      route: '/prescriptions' },
  { k: 'records',      label: 'Records',        icon: 'doc',      route: '/records'       },
];

function PortalShell({ active = 'home', children, title, subtitle, action }) {
  const { user } = useAuth();
  const consults = useConsults();
  const pendingAppointments = consults.filter(portalAppointmentIsPending).length;
  const unreadPrescriptions = window.useUnreadPrescriptionCount ? window.useUnreadPrescriptionCount(consults) : 0;
  const initials = user?.initials || (window.molaraAuth?.initialsFor ? window.molaraAuth.initialsFor(user?.name || 'Patient') : 'PT');
  return (
    <div className="ml-root" style={{ display: 'grid', gridTemplateColumns: '232px 1fr', height: '100%' }}>
      {/* Sidebar */}
      <aside style={{
        background: '#fff',
        borderRight: '1px solid var(--line)',
        padding: '22px 16px',
        display: 'flex', flexDirection: 'column', gap: 4,
      }}>
        <div onClick={() => window.navigate && window.navigate('/')} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 10px 18px', cursor: 'pointer' }}>
          <Logo size={18}/>
        </div>

        {NAV_ITEMS.map(item => {
          const on = item.k === active;
          const Icon = I[item.icon];
          const badge = item.k === 'appointments'
            ? pendingAppointments
            : item.k === 'prescriptions'
              ? unreadPrescriptions
              : 0;
          const badgeLabel = item.k === 'appointments'
            ? `${badge} pending appointments`
            : `${badge} unread prescription notifications`;
          return (
            <button key={item.k}
              onClick={() => window.navigate && window.navigate(item.route)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '9px 12px',
                borderRadius: 8,
                background: on ? 'var(--blue-soft)' : 'transparent',
                color: on ? 'var(--blue-deep)' : 'var(--ink-2)',
                fontSize: 13.5, fontWeight: on ? 500 : 400,
                cursor: 'pointer',
                border: 'none', textAlign: 'left',
                fontFamily: 'inherit',
              }}>
              <Icon size={16}/>
              <span>{item.label}</span>
              {badge > 0 && (
                <span aria-label={badgeLabel} style={{
                  marginLeft: 'auto',
                  minWidth: 17,
                  height: 17,
                  padding: '0 5px',
                  borderRadius: 999,
                  background: '#c92a2a',
                  color: '#fff',
                  display: 'inline-grid',
                  placeItems: 'center',
                  fontSize: 10,
                  fontWeight: 800,
                  lineHeight: 1,
                }}>{badge > 9 ? '9+' : badge}</span>
              )}
            </button>
          );
        })}

        <div style={{ marginTop: 'auto', borderTop: '1px solid var(--line)', paddingTop: 14 }}>
          <div style={{
            background: 'oklch(96% 0.02 240)', borderRadius: 12, padding: 14,
            fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5,
          }}>
            <div style={{ fontWeight: 500, color: 'var(--ink)', marginBottom: 4 }}>Need urgent help?</div>
            <div className="ml-muted" style={{ fontSize: 11.5, marginBottom: 8 }}>Book now and receive the dentist WhatsApp link by email.</div>
            <button onClick={() => window.startEmergencyConsult ? window.startEmergencyConsult(user || null) : (window.navigate && window.navigate('/book?emergency=1'))} className="ml-btn ml-btn--primary" style={{ padding: '7px 12px', fontSize: 12, width: '100%', justifyContent: 'center' }}>
              <I.chat size={13}/> Consult now
            </button>
          </div>
        </div>
      </aside>

      {/* Main */}
      <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Topbar */}
        <div style={{
          height: 64, padding: '0 32px',
          borderBottom: '1px solid var(--line)',
          background: '#fff',
          display: 'flex', alignItems: 'center', gap: 16,
        }}>
          <div style={{ flex: 1 }}>
            {title && <div style={{ fontFamily: 'var(--display)', fontSize: 22, letterSpacing: '-0.025em' }}>{title}</div>}
            {subtitle && <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{subtitle}</div>}
          </div>
          {action}
          <div className="ml-avatar" style={{ width: 36, height: 36, borderRadius: '50%', fontSize: 13 }}>{initials}</div>
        </div>

        {/* Page body */}
        <div style={{ flex: 1, overflow: 'auto', background: 'var(--paper)' }}>
          {children}
        </div>
      </div>
    </div>
  );
}

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

window.PortalShell = PortalShell;
window.NAV_ITEMS = NAV_ITEMS;
