// app-shell.jsx — sidebar + topbar + notifications drawer + toast.
// Wraps every screen. Mode toggle in the topbar.

const PCAS_t = window.PCT;
const PCAS_d = window.PCA;

function Shell({ active, breadcrumb, headerRight, children }) {
  const store = useStore();
  const mode = store.state.mode;

  return (
    <div style={{
      display:'grid',
      gridTemplateColumns: '236px 1fr',
      gridTemplateRows: '56px 1fr',
      height: '100vh',
      background: PCAS_t.c.bg,
      fontFamily: PCAS_t.f.sans,
      color: PCAS_t.c.text,
      overflow:'hidden',
    }}>
      <ShellSidebar mode={mode} active={active}/>
      <ShellTopBar mode={mode} breadcrumb={breadcrumb} right={headerRight}/>
      <main style={{ overflow:'auto', background: PCAS_t.c.bg, position:'relative' }}>
        {children}
      </main>
      <NotificationsDrawer/>
      <ToastHost/>
    </div>
  );
}

function ShellSidebar({ mode, active }) {
  const integratedNav = [
    { group: 'Workspace' },
    { id: 'home',     label:'Dashboard',     icon:'home',   to:'#/' },
    { id: 'frontdesk',label:'Front desk',    icon:'inbox',  to:'#/frontdesk/admit/CLM-2026-0142' },
    { id: 'patients', label:'Patients',      icon:'users',  to:'#/', disabled:true },
    { id: 'ipd',      label:'IPD board',     icon:'bed',    to:'#/', disabled:true },
    { group: 'Revenue' },
    { id: 'invoices', label:'Invoices',      icon:'money',  to:'#/', disabled:true },
    { id: 'claims',   label:'Claims',        icon:'claims', to:'#/claims', badge: 'active' },
    { id: 'cfo',      label:'CFO insights',  icon:'chart',  to:'#/cfo' },
    { group: 'Setup' },
    { id: 'settings', label:'RCM settings',  icon:'gear',   to:'#/settings/insurers' },
  ];
  const standaloneNav = [
    { group: 'Daily work' },
    { id: 'home',     label:'My worklist',   icon:'list',   to:'#/',         badge:'active' },
    { id: 'claims',   label:'All claims',    icon:'claims', to:'#/claims' },
    { id: 'cfo',      label:'CFO insights',  icon:'chart',  to:'#/cfo' },
    { group: 'Setup' },
    { id: 'settings', label:'Payers & tariffs', icon:'gear', to:'#/settings/insurers' },
  ];
  const nav = mode === 'standalone' ? standaloneNav : integratedNav;
  const store = useStore();
  const activeCount = store.state.claims.filter(c =>
    !['SETTLED','CLOSED','DENIED'].includes(c.status)
  ).length;

  return (
    <aside style={{
      gridRow:'1 / span 2',
      background: PCAS_t.c.navBg,
      color: PCAS_t.c.navText,
      borderRight: `1px solid ${PCAS_t.c.navBorder}`,
      display:'flex', flexDirection:'column',
      padding:'18px 12px',
    }}>
      {/* Brand */}
      <div style={{
        display:'flex', alignItems:'center', gap:10,
        padding:'4px 8px 18px',
        borderBottom: `1px solid ${PCAS_t.c.navBorder}`,
        marginBottom: 12,
      }}>
        <BrandMark mode={mode}/>
        <div style={{ minWidth:0 }}>
          <div style={{ fontSize:14, fontWeight:600, letterSpacing:'-.01em', whiteSpace:'nowrap' }}>
            {mode === 'standalone' ? 'PulseChart Claims' : 'PulseChart'}
          </div>
          <div style={{
            fontSize:10, color: PCAS_t.c.navMuted,
            fontFamily: PCAS_t.f.mono, letterSpacing:'.06em', textTransform:'uppercase',
          }}>
            {mode === 'standalone' ? 'RCM workspace' : 'Hospital admin'}
          </div>
        </div>
      </div>

      {/* Hospital switcher */}
      <div style={{
        display:'flex', alignItems:'center', gap:10,
        padding:'9px 10px',
        background: PCAS_t.c.navBgHover,
        borderRadius: 8,
        marginBottom: 8,
        cursor:'pointer',
      }}>
        <div style={{
          width:26, height:26, borderRadius:6,
          background: 'linear-gradient(135deg, #6D28D9, #0369A1)',
          display:'grid', placeItems:'center',
          fontSize:11, fontWeight:700, color:'#fff', fontFamily: PCAS_t.f.mono,
        }}>RA</div>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:12.5, fontWeight:500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{PCAS_d.tenant.name}</div>
          <div style={{ fontSize:10, color: PCAS_t.c.navMuted, fontFamily: PCAS_t.f.mono, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
            {PCAS_d.tenant.city} · ROHINI {PCAS_d.tenant.rohini.split('-').slice(0,2).join('-')}…
          </div>
        </div>
        <AppIcon name="down" size={12} color={PCAS_t.c.navMuted}/>
      </div>

      {/* Nav */}
      <nav style={{ display:'flex', flexDirection:'column', gap:1, flex:1, marginTop:6, overflow:'auto' }}>
        {nav.map((it, i) => it.group ? (
          <div key={'g'+i} style={{
            fontFamily: PCAS_t.f.mono, fontSize:9.5, fontWeight:600,
            letterSpacing:'.12em', textTransform:'uppercase',
            color: PCAS_t.c.navMuted, opacity:.65,
            padding:'12px 10px 5px',
          }}>{it.group}</div>
        ) : (
          <NavItem key={it.id} item={it} active={active === it.id} activeCount={activeCount}/>
        ))}
      </nav>

      {/* User + Reset */}
      <div style={{ borderTop: `1px solid ${PCAS_t.c.navBorder}`, marginTop:8, paddingTop:8 }}>
        <div style={{
          display:'flex', alignItems:'center', gap:10,
          padding:'8px 10px',
        }}>
          <AppAvatar name="Priya M" size={28} bg="#7C3AED"/>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:12.5, fontWeight:500, color: PCAS_t.c.navText }}>Priya Menon</div>
            <div style={{ fontSize:10, color: PCAS_t.c.navMuted, fontFamily: PCAS_t.f.mono, whiteSpace:'nowrap' }}>
              RCM Coordinator
            </div>
          </div>
        </div>
        <button onClick={() => {
          if (confirm('Reset all demo data to seed state?')) useStoreReset();
        }} style={{
          width:'100%', marginTop:4,
          padding:'6px 10px', display:'flex', alignItems:'center', gap:6,
          background:'transparent', border:'none', cursor:'pointer',
          color: PCAS_t.c.navMuted,
          fontFamily: PCAS_t.f.mono, fontSize:10, letterSpacing:'.04em', textTransform:'uppercase',
        }}>
          <AppIcon name="refresh" size={11} color={PCAS_t.c.navMuted}/>
          Reset demo
        </button>
      </div>
    </aside>
  );
}

function useStoreReset() {
  // Imperative reset — read fresh store from React tree
  // Since this is called inside an onClick we go through window
  const s = window.__pcStore;
  if (s) s.reset();
  else { localStorage.removeItem('pcclaims.v1'); location.reload(); }
}

function BrandMark({ mode }) {
  if (mode === 'standalone') {
    return (
      <div style={{
        width:28, height:28, borderRadius:7,
        background: 'linear-gradient(135deg, #6D28D9, #4C1D95)',
        display:'grid', placeItems:'center',
        fontFamily: PCAS_t.f.mono, fontWeight:700, color:'#fff', fontSize:13,
        letterSpacing:'-.04em',
      }}>P</div>
    );
  }
  return (
    <div style={{
      width:28, height:28, borderRadius:7,
      background:'#fff',
      display:'grid', placeItems:'center',
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
        <path d="M2 12h4l2-6 4 12 3-9 2 3h5" stroke="#18181A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </div>
  );
}

function NavItem({ item, active, activeCount }) {
  return (
    <a href={item.to} onClick={e => { if (item.disabled) { e.preventDefault(); window.demoNote && window.demoNote({ title: item.label.replace(/&amp;/g,'&') + ' — full module' }); } }} style={{
      display:'flex', alignItems:'center', gap:11,
      padding:'8px 10px', borderRadius:7,
      background: active ? PCAS_t.c.navBgHover : 'transparent',
      color: active ? PCAS_t.c.navText : PCAS_t.c.navMuted,
      cursor: item.disabled ? 'not-allowed' : 'pointer',
      opacity: item.disabled ? .4 : 1,
      position:'relative', textDecoration:'none',
    }}>
      {active && <span style={{ position:'absolute', left:-12, top:6, bottom:6, width:2, background: PCAS_t.c.brand, borderRadius:'0 2px 2px 0' }}/>}
      <AppIcon name={item.icon} size={15} color={active ? '#fff' : PCAS_t.c.navMuted}/>
      <span style={{ fontSize:13, flex:1, fontWeight: active ? 500 : 400, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{item.label}</span>
      {item.badge === 'active' && activeCount > 0 && (
        <span style={{
          background: PCAS_t.c.brand, color:'#fff',
          fontSize:10, fontWeight:600,
          padding:'1px 6px', borderRadius:10,
          fontFamily: PCAS_t.f.mono,
        }}>{activeCount}</span>
      )}
    </a>
  );
}

// ── Top bar ───────────────────────────────────────────────
function ShellTopBar({ mode, breadcrumb, right }) {
  const store = useStore();
  const unreadNotifs = store.state.notifications.length;

  return (
    <header style={{
      height:56, padding:'0 24px',
      borderBottom: `1px solid ${PCAS_t.c.border}`,
      background: PCAS_t.c.surface,
      display:'flex', alignItems:'center', gap:16,
    }}>
      {/* Breadcrumb */}
      <div style={{ display:'flex', alignItems:'center', gap:8, flex:1, minWidth:0 }}>
        {breadcrumb.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <AppIcon name="right" size={12} color={PCAS_t.c.textDim}/>}
            <span style={{
              fontSize: i === breadcrumb.length - 1 ? 14 : 13,
              fontWeight: i === breadcrumb.length - 1 ? 600 : 400,
              color: i === breadcrumb.length - 1 ? PCAS_t.c.text : PCAS_t.c.textMuted,
              letterSpacing: i === breadcrumb.length - 1 ? '-.01em' : 0,
            }}>{c}</span>
          </React.Fragment>
        ))}
      </div>

      {/* Search */}
      <div style={{
        display:'flex', alignItems:'center', gap:8,
        height:34, padding:'0 12px',
        background: PCAS_t.c.surface2,
        borderRadius:8,
        minWidth:260,
        color: PCAS_t.c.textDim,
      }}>
        <AppIcon name="search" size={14} color={PCAS_t.c.textDim}/>
        <span style={{ fontSize:13, color: PCAS_t.c.textDim }}>Search claims, patients, policy no…</span>
        <span style={{
          marginLeft:'auto',
          fontFamily: PCAS_t.f.mono, fontSize:10,
          padding:'2px 5px', borderRadius:4,
          background:'#fff', border: `1px solid ${PCAS_t.c.border}`,
          color: PCAS_t.c.textMuted, letterSpacing:'.02em',
        }}>⌘K</span>
      </div>

      {/* Mode toggle */}
      <ModeToggle mode={mode}/>

      {/* Notifications bell */}
      <button onClick={() => store.toggleNotifDrawer()} style={{
        position:'relative', width:36, height:36, borderRadius:8,
        background: PCAS_t.c.surface2, border: `1px solid ${PCAS_t.c.border}`,
        cursor:'pointer', display:'grid', placeItems:'center',
      }}>
        <AppIcon name="bell" size={16} color={PCAS_t.c.text}/>
        {unreadNotifs > 0 && (
          <span style={{
            position:'absolute', top:-4, right:-4,
            minWidth:18, height:18, padding:'0 4px',
            background: PCAS_t.c.brand, color:'#fff',
            borderRadius:9, fontSize:10, fontWeight:600,
            fontFamily: PCAS_t.f.mono,
            display:'grid', placeItems:'center',
            border:`2px solid ${PCAS_t.c.surface}`,
          }}>{unreadNotifs}</span>
        )}
      </button>

      {right}
    </header>
  );
}

function ModeToggle({ mode }) {
  const store = useStore();
  return (
    <div style={{
      display:'flex', background: PCAS_t.c.surface2,
      borderRadius:7, padding:2, gap:1,
      border: `1px solid ${PCAS_t.c.border}`,
    }}>
      {[
        { id:'integrated', label:'Inside HMS', dot: PCAS_t.c.accent },
        { id:'standalone', label:'Standalone', dot: PCAS_t.c.brand },
      ].map(o => (
        <button key={o.id}
          onClick={() => store.setMode(o.id)}
          style={{
            display:'flex', alignItems:'center', gap:6,
            padding:'4px 10px', borderRadius:5,
            background: mode === o.id ? '#fff' : 'transparent',
            color: mode === o.id ? PCAS_t.c.text : PCAS_t.c.textMuted,
            fontSize:11.5, fontWeight: mode === o.id ? 600 : 500,
            border:'none', cursor:'pointer',
            boxShadow: mode === o.id ? '0 1px 2px rgba(0,0,0,.06)' : 'none',
            fontFamily: PCAS_t.f.sans,
          }}>
          <span style={{ width:6, height:6, borderRadius:'50%', background: o.dot }}/>
          {o.label}
        </button>
      ))}
    </div>
  );
}

// ── Notifications drawer ─────────────────────────────────
function NotificationsDrawer() {
  const store = useStore();
  const { notifDrawerOpen, notifications } = store.state;
  if (!notifDrawerOpen) return null;
  return ReactDOM.createPortal(
    <div style={{
      position:'fixed', inset:0, zIndex:900,
      display:'flex', justifyContent:'flex-end',
    }}>
      <div onClick={() => store.closeNotifDrawer()} style={{
        position:'absolute', inset:0, background:'rgba(24,20,16,.3)',
      }}/>
      <div style={{
        position:'relative', width: 420, height:'100vh',
        background: PCAS_t.c.surface,
        borderLeft: `1px solid ${PCAS_t.c.border}`,
        boxShadow:'-12px 0 32px rgba(0,0,0,.10)',
        display:'flex', flexDirection:'column',
        animation:'pcSlideIn .2s ease-out',
      }}>
        <div style={{
          padding:'18px 22px',
          borderBottom: `1px solid ${PCAS_t.c.border}`,
          display:'flex', alignItems:'center', justifyContent:'space-between',
        }}>
          <div>
            <div style={{ fontSize:15, fontWeight:600 }}>Patient notifications</div>
            <div style={{ fontSize:11.5, color: PCAS_t.c.textMuted, marginTop:2 }}>
              WhatsApp / SMS messages sent · most recent first
            </div>
          </div>
          <button onClick={() => store.closeNotifDrawer()} style={{
            border:'none', background:'transparent', cursor:'pointer',
            width:28, height:28, borderRadius:6, display:'grid', placeItems:'center',
            color: PCAS_t.c.textMuted,
          }}>
            <AppIcon name="x" size={16}/>
          </button>
        </div>
        <div style={{ flex:1, overflow:'auto', padding:'8px 0' }}>
          {notifications.length === 0 ? (
            <AppEmpty icon="bell" title="No notifications yet" body="Status changes will show up here."/>
          ) : notifications.map(n => (
            <NotifRow key={n.id} n={n}/>
          ))}
        </div>
      </div>
    </div>,
    document.body,
  );
}

function NotifRow({ n }) {
  const insurer = PCAS_d.findInsurer((window.__pcStore || {}).state?.claims?.find(c => c.id === n.claimId)?.insurer);
  const age = ageOf(n.sentAt);
  return (
    <div style={{
      padding:'14px 22px', borderBottom: `1px solid ${PCAS_t.c.border}`,
      display:'flex', gap:11,
    }}>
      <div style={{
        width:32, height:32, borderRadius:8,
        background:'#25D36615',
        display:'grid', placeItems:'center', flexShrink:0,
      }}>
        <AppIcon name="whatsapp" size={18}/>
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', justifyContent:'space-between', gap:8 }}>
          <div style={{ fontSize:12, color: PCAS_t.c.textMuted, fontFamily: PCAS_t.f.mono }}>
            {n.phone}
          </div>
          <div style={{ fontSize:11, color: PCAS_t.c.textDim }}>{age}</div>
        </div>
        <div style={{ fontSize:12.5, color: PCAS_t.c.text, marginTop:4, lineHeight:1.5 }}>{n.body}</div>
        <div style={{ marginTop:6, display:'flex', alignItems:'center', gap:6 }}>
          <a href={`#/claims/${n.claimId}`} onClick={() => useStore && setTimeout(() => window.__pcStore?.closeNotifDrawer(), 50)} style={{
            fontSize:11, color: PCAS_t.c.accent, fontFamily: PCAS_t.f.mono, textDecoration:'none',
          }}>{n.claimId}</a>
          <span style={{
            display:'inline-flex', alignItems:'center', padding:'1px 6px',
            background: PCAS_t.c.successTint, color: PCAS_t.c.success,
            fontSize:9.5, fontWeight:600, fontFamily: PCAS_t.f.mono,
            borderRadius:3, letterSpacing:'.04em',
          }}>{n.status}</span>
        </div>
      </div>
    </div>
  );
}

function ageOf(ts) {
  const m = Math.floor((Date.now() - ts) / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return m + 'm';
  if (m < 60 * 24) return Math.floor(m/60) + 'h';
  return Math.floor(m / 60 / 24) + 'd';
}

// ── Toast host ───────────────────────────────────────────
function ToastHost() {
  const store = useStore();
  const t = store.state.toast;
  if (!t) return null;
  return ReactDOM.createPortal(
    <div style={{
      position:'fixed', bottom:24, left:'50%', transform:'translateX(-50%)',
      zIndex:1100, animation:'pcToast .2s ease-out',
      background: PCAS_t.c.text, color:'#fff',
      padding:'12px 18px', borderRadius:9,
      boxShadow:'0 8px 24px rgba(0,0,0,.25)',
      display:'flex', alignItems:'center', gap:12,
      minWidth:280, maxWidth:480,
      fontSize:13,
    }}>
      {t.icon === 'whatsapp' && (
        <div style={{
          width:28, height:28, borderRadius:7,
          background:'#25D36625', color:'#25D366',
          display:'grid', placeItems:'center', flexShrink:0,
        }}>
          <AppIcon name="whatsapp" size={16}/>
        </div>
      )}
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontWeight:600, fontSize:13 }}>{t.title}</div>
        {t.body && <div style={{ fontSize:11.5, opacity:.75, marginTop:2, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{t.body}</div>}
      </div>
      <button onClick={() => store.clearToast()} style={{
        border:'none', background:'transparent', cursor:'pointer',
        color:'rgba(255,255,255,.6)', width:24, height:24, borderRadius:5,
        display:'grid', placeItems:'center',
      }}><AppIcon name="x" size={14}/></button>
    </div>,
    document.body,
  );
}

Object.assign(window, { Shell, ShellTopBar, ShellSidebar, NotificationsDrawer, ToastHost });
