// App shell: left rail + top bar + router

const { useState: useS0 } = React;

const NAV = [
  { id: 'home',          label: 'Home',          icon: 'Home' },
  { id: 'chat',          label: 'Chat',          icon: 'Chat',     badge: 'new' },
  { id: 'connectors',    label: 'Connectors',    icon: 'Plug' },
  { id: 'memory',        label: 'Memory',        icon: 'Search',   personalOnly: true },
  { id: 'conversations', label: 'Conversations', icon: 'Chat',     personalOnly: true },
  { id: 'teamsync',      label: 'Team Sync',     icon: 'Link' },
  { id: 'fabric',        label: 'Fabric',        icon: 'Graph' },
  { id: 'learning',      label: 'Learning',      icon: 'Sparkle',  live: true },
  { id: 'api',           label: 'API',           icon: 'Code' },
  { id: 'observability', label: 'Observability', icon: 'Activity' },
  { id: 'members',       label: 'Members',       icon: 'Users',    orgOnly: true },
  { id: 'settings',      label: 'Settings',      icon: 'Settings' },
];

// Personal mode only exposes Home, Connectors, and Team Sync — the knowledge
// surfaces (Fabric/Learning/API/Observability/etc.) are org-only.
const PERSONAL_NAV = new Set(['home', 'connectors', 'memory', 'conversations', 'teamsync']);

function Rail({ route, setRoute, collapsed, setCollapsed, onboarding, startOnboarding, session, mode, onLogout }) {
  // Org mode shows everything (Members is org-only); personal mode is limited to
  // PERSONAL_NAV.
  const navItems = NAV.filter(item => {
    if (item.orgOnly && mode !== 'org') return false;
    if (item.personalOnly && mode === 'org') return false;
    if (mode !== 'org' && !PERSONAL_NAV.has(item.id)) return false;
    return true;
  });
  const acct = session && session.account;
  // Workspace identity reflects the signed-in account; falls back to the demo
  // identity in mock mode (no session).
  const wsName = acct ? (mode === 'org' ? 'Organization' : 'Personal') : 'Acme, Inc.';
  const wsSub  = acct ? acct.email : 'parcle.dev/acme';
  const userName = acct ? (acct.email || '').split('@')[0] : 'Maya K.';
  const userSub  = acct ? acct.email : 'maya@acme';
  const userInitials = acct ? (acct.email || '?').slice(0, 2).toUpperCase() : 'MK';
  return (
    <aside style={{
      width: collapsed ? 56 : 240,
      flexShrink: 0,
      borderRight: '1px solid var(--border-subtle)',
      background: 'var(--bg)',
      display: 'flex', flexDirection: 'column',
      transition: 'width 160ms cubic-bezier(.2,.8,.2,1)',
      overflow: 'hidden',
    }}>
      {/* Org switcher */}
      <div style={{ padding: collapsed ? '12px 8px' : '14px 12px', borderBottom: '1px solid var(--border-subtle)' }}>
        <button style={{
          width: '100%', display: 'flex', alignItems: 'center',
          gap: 10, padding: collapsed ? 6 : '6px 8px',
          borderRadius: 8,
          background: 'transparent',
        }}>
          <div style={{
            width: 24, height: 24, borderRadius: 6,
            background: 'var(--text-primary)',
            color: 'var(--bg)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="M4 12a8 8 0 0116 0"/><circle cx="12" cy="12" r="3" fill="currentColor"/>
            </svg>
          </div>
          {!collapsed && (
            <>
              <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{wsName}</div>
                <div className="mono-sm mono text-tertiary" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{wsSub}</div>
              </div>
              <Icons.ChevronD size={12} style={{ color: 'var(--text-tertiary)' }}/>
            </>
          )}
        </button>
      </div>

      {/* Nav */}
      <nav style={{ flex: 1, padding: 8, display: 'flex', flexDirection: 'column', gap: 1 }}>
        {navItems.map(item => {
          const Icon = Icons[item.icon];
          const active = route === item.id;
          return (
            <button key={item.id}
              onClick={() => setRoute(item.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                height: 32, padding: collapsed ? 0 : '0 10px',
                justifyContent: collapsed ? 'center' : 'flex-start',
                borderRadius: 7,
                background: active ? 'var(--selected)' : 'transparent',
                color: active ? 'var(--text-primary)' : 'var(--text-secondary)',
                fontSize: 13, fontWeight: active ? 500 : 400,
                position: 'relative',
              }}
              onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--hover)'; }}
              onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
            >
              <Icon size={16} style={{ flexShrink: 0 }} />
              {!collapsed && <span style={{ flex: 1, textAlign: 'left' }}>{item.label}</span>}
              {!collapsed && item.count != null && (
                <span className="mono-sm mono" style={{
                  padding: '1px 6px', borderRadius: 4,
                  background: 'var(--accent-muted)', color: 'var(--accent-text)',
                  fontSize: 11, lineHeight: '16px'
                }}>{item.count}</span>
              )}
              {!collapsed && item.badge === 'new' && (
                <span style={{
                  padding: '1px 5px', borderRadius: 3,
                  background: 'var(--accent)', color: 'var(--on-accent)',
                  fontSize: 9, fontWeight: 600, letterSpacing: '0.04em',
                }}>NEW</span>
              )}
              {!collapsed && item.live && (
                <span style={{
                  width: 6, height: 6, borderRadius: '50%',
                  background: 'var(--success)',
                  animation: 'parclePulseLoop 2s ease-out infinite',
                }}/>
              )}
            </button>
          );
        })}
      </nav>

      {/* Onboarding / Bottom */}
      {!collapsed && !onboarding && (
        <div style={{ padding: 12, borderTop: '1px solid var(--border-subtle)' }}>
          <button onClick={startOnboarding} className="btn sm" style={{ width: '100%', justifyContent: 'flex-start', fontSize: 12 }}>
            <Icons.Sparkle size={13} /> Finish setup
          </button>
        </div>
      )}
      <div style={{ padding: collapsed ? 8 : 12, borderTop: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 10, justifyContent: collapsed ? 'center' : 'flex-start' }}>
        <div style={{
          width: 24, height: 24, borderRadius: '50%',
          background: 'linear-gradient(135deg, var(--accent), var(--accent-hover))',
          color: 'var(--on-accent)', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 10, fontWeight: 600,
        }}>{userInitials}</div>
        {!collapsed && (
          <>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{userName}</div>
              <div className="mono-sm mono text-tertiary" style={{ fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{userSub}</div>
            </div>
            {acct && onLogout && (
              <button className="btn sm ghost" onClick={onLogout} title="Sign out">
                <Icons.LogOut size={12}/>
              </button>
            )}
            <button className="btn sm ghost" onClick={() => setCollapsed(true)} title="Collapse">
              <Icons.ChevronL size={12}/>
            </button>
          </>
        )}
        {collapsed && (
          <button className="btn sm ghost" style={{ position: 'absolute', bottom: 8, left: 60, zIndex: 2 }} onClick={() => setCollapsed(false)}>
            <Icons.ChevronR size={12}/>
          </button>
        )}
      </div>
    </aside>
  );
}

function TopBar({ route, setRoute, env, setEnv, setCmdOpen }) {
  const breadcrumb = {
    home: ['Home'],
    chat: ['Chat'],
    connectors: ['Connectors'],
    memory: ['Memory'],
    conversations: ['Conversations'],
    teamsync: ['Team Sync'],
    members: ['Members'],
    fabric: ['Fabric', 'Acme Corp'],
    learning: ['Learning stream'],
    api: ['API', 'Playground'],
    observability: ['Observability', 'Retrievals'],
    settings: ['Settings'],
  }[route] || ['Home'];
  return (
    <header style={{
      height: 48, flexShrink: 0,
      borderBottom: '1px solid var(--border-subtle)',
      background: 'var(--bg)',
      display: 'flex', alignItems: 'center',
      padding: '0 24px', gap: 12,
      position: 'sticky', top: 0, zIndex: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, whiteSpace: 'nowrap', flexShrink: 0 }}>
        {breadcrumb.map((b, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="text-tertiary" style={{ fontSize: 11 }}>/</span>}
            <span style={{ color: i === breadcrumb.length - 1 ? 'var(--text-primary)' : 'var(--text-secondary)', fontWeight: i === breadcrumb.length - 1 ? 500 : 400 }}>{b}</span>
          </React.Fragment>
        ))}
      </div>

      <div style={{ flex: 1 }} />

      <div className="topbar-ticker-wrap">
        <LearningTicker setRoute={setRoute}/>
      </div>

      <button onClick={() => setCmdOpen(true)} className="topbar-search" style={{
        display: 'flex', alignItems: 'center', gap: 8,
        height: 30, padding: '0 10px',
        border: '1px solid var(--border-subtle)', borderRadius: 7,
        background: 'var(--surface)',
        color: 'var(--text-tertiary)',
        fontSize: 12,
      }}>
        <Icons.Search size={13}/>
        <span style={{ flex: 1, textAlign: 'left' }}>Search or jump to…</span>
        <span className="kbd">⌘K</span>
      </button>

      <div className="segmented">
        <button className={env === 'dev' ? 'active' : ''} onClick={() => setEnv('dev')}>dev</button>
        <button className={env === 'prod' ? 'active' : ''} onClick={() => setEnv('prod')}>prod</button>
      </div>

      <button className="btn sm ghost" style={{ position: 'relative' }}>
        <Icons.Bell size={14}/>
        <span style={{ position: 'absolute', top: 4, right: 4, width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }}/>
      </button>
    </header>
  );
}

// Command-K palette — lightweight
function CmdPalette({ open, onClose, setRoute }) {
  if (!open) return null;
  const items = [
    { group: 'Jump to', icon: 'Chat',     label: 'Chat',              route: 'chat' },
    { group: 'Jump to', icon: 'Plug',     label: 'Connectors',        route: 'connectors' },
    { group: 'Jump to', icon: 'Search',   label: 'Memory',            route: 'memory' },
    { group: 'Jump to', icon: 'Chat',     label: 'Conversations',     route: 'conversations' },
    { group: 'Jump to', icon: 'Graph',    label: 'Fabric · Acme Corp',route: 'fabric' },
    { group: 'Jump to', icon: 'Sparkle',  label: 'Learning stream',   route: 'learning' },
    { group: 'Jump to', icon: 'Code',     label: 'API Playground',    route: 'api' },
    { group: 'Jump to', icon: 'Activity', label: 'Retrievals',        route: 'observability' },
    { group: 'Entities', icon: 'Graph',   label: 'Acme Corp · Org',   route: 'fabric' },
    { group: 'Entities', icon: 'Graph',   label: 'Priya Shah · Person', route: 'fabric' },
    { group: 'Entities', icon: 'Graph',   label: 'Q2 Expansion · Deal', route: 'fabric' },
    { group: 'Actions', icon: 'Plus',     label: 'Add connector',     route: 'connectors' },
    { group: 'Actions', icon: 'Key',      label: 'Create API key',    route: 'settings' },
    { group: 'Docs',    icon: 'Doc',      label: 'Getting started',   route: 'home' },
    { group: 'Docs',    icon: 'Doc',      label: 'MCP client setup',  route: 'home' },
  ];
  const groups = [...new Set(items.map(i => i.group))];
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.4)', zIndex: 100,
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      paddingTop: '15vh',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 600, background: 'var(--surface-raised)',
        border: '1px solid var(--border)',
        borderRadius: 12, boxShadow: 'var(--shadow-2)',
        overflow: 'hidden'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 16px', height: 48, borderBottom: '1px solid var(--border-subtle)' }}>
          <Icons.Search size={14} style={{ color: 'var(--text-tertiary)' }}/>
          <input autoFocus placeholder="Search connectors, entities, endpoints…" style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent',
            fontSize: 14, color: 'var(--text-primary)',
          }}/>
          <span className="kbd">ESC</span>
        </div>
        <div style={{ maxHeight: 360, overflowY: 'auto', padding: 8 }}>
          {groups.map(g => (
            <div key={g} style={{ marginBottom: 8 }}>
              <div className="t-micro text-tertiary" style={{ padding: '6px 8px' }}>{g}</div>
              {items.filter(i => i.group === g).map((i, idx) => {
                const I = Icons[i.icon];
                return (
                  <button key={idx}
                    onClick={() => { setRoute(i.route); onClose(); }}
                    style={{
                      width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                      padding: '8px 10px', borderRadius: 6, fontSize: 13,
                      color: 'var(--text-primary)',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >
                    <I size={14} style={{ color: 'var(--text-secondary)' }}/>
                    <span style={{ flex: 1, textAlign: 'left' }}>{i.label}</span>
                    <Icons.ArrowR size={12} style={{ color: 'var(--text-tertiary)' }}/>
                  </button>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Rail, TopBar, CmdPalette });
