// Vyuu admin console — Sidebar + TopBar
const { LayoutDashboard, Activity, Laptop, Download, Puzzle,
  Settings: SettingsIcon, ChevronRight, ChevronDown, Search, CircleDot,
  Sun, Moon, LogOut } = window.LucideReact;

// Inline product marks — each in its own ink color, matching the brand product-family system.
const ChakravyuhaMark = ({size=18, color='#FBF8F1', opacity=1}) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none" style={{opacity}}>
    <path d="M24 4 A20 20 0 1 1 9.86 9.86" stroke={color} strokeWidth="2.4" strokeLinecap="round"/>
    <path d="M38 24 A14 14 0 1 1 14.1 14.1" stroke={color} strokeWidth="2.2" strokeLinecap="round" opacity="0.78"/>
    <path d="M16 24 A8 8 0 1 1 31.66 26.2" stroke={color} strokeWidth="2" strokeLinecap="round" opacity="0.58"/>
    <circle cx="24" cy="24" r="2.4" fill={color}/>
  </svg>
);
const PromptMark = ({size=16, color=theme.terracottaInk}) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none">
    <path d="M24 4 L40 10 V24 Q40 36 24 44 Q8 36 8 24 V10 Z" stroke={color} strokeWidth="1.6" opacity="0.5" fill="none"/>
    <text x="24" y="31" fontFamily="'Noto Serif Devanagari','Fraunces',serif" fontSize="22" fontWeight="500" textAnchor="middle" fill={color}>व्</text>
  </svg>
);
const McpMark = ({size=16, color=theme.oceanInk}) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none">
    <path d="M8 10 Q24 20 24 40" stroke={color} strokeWidth="2.6" strokeLinecap="round" fill="none"/>
    <path d="M40 10 Q24 20 24 40" stroke={color} strokeWidth="2.6" strokeLinecap="round" fill="none" opacity="0.55"/>
    <circle cx="24" cy="40" r="2.2" fill={color}/>
  </svg>
);
const AgentMark = ({size=16, color=theme.amberInk}) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none">
    <path d="M4 24 Q24 6 44 24 Q24 42 4 24 Z" stroke={color} strokeWidth="2" fill="none"/>
    <circle cx="24" cy="24" r="6" stroke={color} strokeWidth="2" fill="none"/>
    <circle cx="24" cy="24" r="2" fill={color}/>
  </svg>
);

// Three product families get their own Sanskrit-rooted glyphs.
// Non-product operational items use Lucide icons in the muted palette.
const NAV = [
  { key:'overview', label:'Overview', icon:LayoutDashboard, kind:'lucide' },
  { key:'events', label:'Events', icon:Activity, kind:'lucide', children:[
    { key:'events.chat', label:'Chat Interactions' },
    { key:'events.mcp', label:'MCP' },
  ]},
  { key:'policy.prompt', label:'Prompt Protection', mark:PromptMark, kind:'product', productInk:'terracottaInk', productSoft:'terracottaSoft', caption:'रक्षा · Protect every prompt.' },
  { key:'policy.mcp', label:'MCP Security', mark:McpMark, kind:'product', productInk:'oceanInk', productSoft:'oceanSoft', caption:'Govern every tool call.', children:[
    { key:'policy.mcp.invocation', label:'Invocation Policies' },
    { key:'policy.catalog', label:'MCP Catalog' },
  ]},
  { key:'agents', label:'Agent Observability', mark:AgentMark, kind:'product', productInk:'amberInk', productSoft:'amberSoft', caption:'दृष्टि · See every agent step.', children:[
    { key:'agents.local', label:'Local Agents' },
    { key:'agents.saas', label:'SaaS Agents' },
  ]},
  { key:'devices', label:'Devices & Inventory', icon:Laptop, kind:'lucide' },
  { key:'downloads', label:'Downloads & Deploy', icon:Download, kind:'lucide' },
  { key:'plugins', label:'Plugins & Add-ins', icon:Puzzle, kind:'lucide', children:[
    { key:'plugins.browser', label:'Browser' },
    { key:'plugins.ide', label:'IDE' },
  ]},
  { key:'settings', label:'Settings', icon:SettingsIcon, kind:'lucide', children:[
    { key:'settings.admin', label:'Admins' },
    { key:'settings.llm', label:'LLM Connectors' },
    { key:'settings.health', label:'Server Identity & Health' },
    { key:'settings.audit', label:'Audit Log' },
  ]},
];

const Sidebar = ({active, setActive}) => {
  const [expanded, setExpanded] = React.useState({events:true, 'policy.mcp':true, agents:true, plugins:true, settings:true});
  return (
    <aside style={{width:260, background:theme.ivory, borderRight:`1px solid ${theme.line}`,
      padding:'24px 14px', display:'flex', flexDirection:'column', gap:4,
      position:'sticky', top:0, height:'100vh', overflowY:'auto'}}>
      <div style={{display:'flex', alignItems:'center', gap:12, padding:'4px 12px 22px'}}>
        <div style={{width:34, height:34, borderRadius:9,
          background: theme.orangeDeep,
          display:'flex', alignItems:'center', justifyContent:'center',
          boxShadow:`0 2px 8px ${theme.orangeDeep}30`}}>
          <ChakravyuhaMark size={20} color={theme.onPrimary}/>
        </div>
        <div>
          <div style={{fontFamily:theme.serif, fontSize:19, fontWeight:500, color:theme.ink, lineHeight:1, letterSpacing:-0.3}}>Vyuu</div>
          <div style={{fontSize:10, color:theme.muted, letterSpacing:1.8, textTransform:'uppercase', marginTop:2, fontWeight:600}}>AI Shield</div>
        </div>
      </div>

      {NAV.map(item => {
        const isProduct = item.kind === 'product';
        const Icon = item.icon;
        const Mark = item.mark;
        const isTopActive = active === item.key || active.startsWith(item.key + '.');
        const hasChildren = item.children?.length;
        const productInk = isProduct ? theme[item.productInk] : null;
        const productSoft = isProduct ? theme[item.productSoft] : null;
        const activeBg = isTopActive
          ? (isProduct ? productSoft : theme.orangeSoft)
          : 'transparent';
        const activeFg = isTopActive
          ? (isProduct ? productInk : theme.orangeDeep)
          : theme.ink;
        return (
          <div key={item.key} style={{marginBottom: isProduct ? 2 : 0}}>
            <button onClick={()=>{
              if (hasChildren) setExpanded(e=>({...e,[item.key]:!e[item.key]}));
              else setActive(item.key);
            }} style={{
              width:'100%', display:'flex', alignItems:'center', gap:11,
              padding: isProduct ? '10px 12px' : '9px 12px',
              borderRadius:8, border:'none',
              background: isTopActive && !hasChildren ? activeBg : 'transparent',
              color: activeFg,
              fontSize:13, fontWeight: isTopActive?600:500, cursor:'pointer', textAlign:'left',
              fontFamily: theme.sans,
            }}>
              {isProduct
                ? <span style={{width:18, height:18, display:'flex', alignItems:'center', justifyContent:'center'}}><Mark size={18} color={productInk}/></span>
                : <Icon size={16} strokeWidth={1.8}/>}
              <span style={{flex:1}}>{item.label}</span>
              {hasChildren && (expanded[item.key] ? <ChevronDown size={13}/> : <ChevronRight size={13}/>)}
            </button>
            {isProduct && item.caption && (
              <div style={{paddingLeft:41, marginTop:-2, marginBottom:4, fontSize:10.5,
                color:productInk, opacity:0.72, fontFamily:theme.sans, letterSpacing:0.2,
                fontStyle:'italic'}}>{item.caption}</div>
            )}
            {hasChildren && expanded[item.key] && (
              <div style={{marginLeft:28, marginTop:2, marginBottom:4,
                borderLeft:`1px solid ${isProduct ? productSoft : theme.line}`, paddingLeft:10}}>
                {item.children.map(c => (
                  <button key={c.key} onClick={()=>setActive(c.key)} style={{
                    width:'100%', textAlign:'left', padding:'6px 10px', borderRadius:6,
                    border:'none', cursor:'pointer',
                    background: active===c.key ? (isProduct ? productSoft : theme.orangeSoft) : 'transparent',
                    color: active===c.key ? (isProduct ? productInk : theme.orangeDeep) : theme.muted,
                    fontSize:12.5, fontWeight: active===c.key?600:400,
                    fontFamily: theme.sans, marginBottom:1,
                  }}>{c.label}</button>
                ))}
              </div>
            )}
          </div>
        );
      })}

      <div style={{marginTop:20, paddingTop:12, borderTop:`1px solid ${theme.line}`}}>
        {(() => {
          const u = (typeof window !== 'undefined' && window.__user) || { name:'Krishna', email:'krishna@llp.in' };
          const initial = (u.name || u.email || '?').trim().charAt(0).toUpperCase();
          const displayName = u.name || (u.email ? u.email.split('@')[0] : 'User');
          const subline = u.provider
            ? `${u.email} · via ${u.provider[0].toUpperCase()+u.provider.slice(1)}`
            : (u.email || 'LLP · Super Admin');
          return (
            <>
              <div style={{display:'flex', alignItems:'center', gap:10}}>
                <div style={{width:32, height:32, borderRadius:999, background:theme.sand,
                  display:'flex', alignItems:'center', justifyContent:'center',
                  fontFamily:theme.serif, fontSize:14, color:theme.ink, fontWeight:500}}>{initial}</div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:12.5, fontWeight:600, color:theme.ink, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{displayName}</div>
                  <div style={{fontSize:11, color:theme.muted, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{subline}</div>
                </div>
              </div>
              <button onClick={()=>window.__signOut && window.__signOut()} style={{
                marginTop:10, width:'100%', display:'inline-flex', alignItems:'center', justifyContent:'center', gap:7,
                padding:'7px 10px', background:'transparent', border:`1px solid ${theme.line}`, borderRadius:8,
                color:theme.muted, fontSize:12, fontWeight:500, cursor:'pointer', fontFamily:theme.sans,
              }}>
                <LogOut size={12} strokeWidth={1.8}/> Sign out
              </button>
            </>
          );
        })()}
      </div>
    </aside>
  );
};

const TopBar = ({crumbs, mode, setMode}) => (
  <div style={{padding:'18px 40px', borderBottom:`1px solid ${theme.line}`, background:theme.bg,
    display:'flex', alignItems:'center', justifyContent:'space-between', position:'sticky', top:0, zIndex:10}}>
    <div style={{display:'flex', alignItems:'center', gap:8, fontSize:12.5, color:theme.muted}}>
      {crumbs.map((c,i)=>(
        <React.Fragment key={i}>
          <span style={{color:i===crumbs.length-1?theme.ink:theme.muted, fontWeight:i===crumbs.length-1?600:400}}>{c}</span>
          {i<crumbs.length-1 && <ChevronRight size={13} strokeWidth={1.5}/>}
        </React.Fragment>
      ))}
    </div>
    <div style={{display:'flex', alignItems:'center', gap:14}}>
      <div style={{display:'flex', alignItems:'center', gap:8, padding:'7px 14px',
        background:theme.panel, border:`1px solid ${theme.line}`, borderRadius:8,
        width:280, color:theme.muted, fontSize:13}}>
        <Search size={14} strokeWidth={1.8}/>
        <span>Search users, events, MCPs…</span>
        <span style={{marginLeft:'auto', fontSize:10, padding:'2px 6px', background:theme.lineSoft, borderRadius:4}}>⌘K</span>
      </div>
      <button onClick={()=>{
          const next = mode==='dark'?'light':'dark';
          // Mutate theme BEFORE state change so the next render reads fresh values.
          if (window.__setTheme) window.__setTheme(next);
          if (setMode) setMode(next);
        }}
        title={mode==='dark'?'Switch to day mode':'Switch to night mode'}
        style={{display:'inline-flex', alignItems:'center', gap:6, padding:'7px 11px',
          background:theme.panel, border:`1px solid ${theme.line}`, borderRadius:8,
          color:theme.muted, fontSize:12, fontWeight:500, cursor:'pointer', fontFamily:theme.sans}}>
        {mode==='dark' ? <Sun size={14} strokeWidth={1.8}/> : <Moon size={14} strokeWidth={1.8}/>}
        <span>{mode==='dark'?'Day':'Night'}</span>
      </button>
      <div style={{display:'flex', alignItems:'center', gap:8, padding:'6px 12px', background:theme.orangeSoft, borderRadius:999}}>
        <CircleDot size={10} color={theme.orangeDeep} fill={theme.orangeDeep}/>
        <span style={{fontSize:11.5, fontWeight:600, color:theme.orangeDeep, letterSpacing:0.3}}>47 devices live</span>
      </div>
    </div>
  </div>
);

Object.assign(window, {Sidebar, TopBar});
