// Primus IQ — minimalist sidebar (collapsible)

const PIcon = ({ name, size = 18, color = 'currentColor' }) => {
  const s = { stroke: color, fill: 'none', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const w = size, h = size;
  switch (name) {
    case 'plus':     return <svg width={w} height={h} viewBox="0 0 20 20"><path d="M10 4v12M4 10h12" {...s}/></svg>;
    case 'chat':     return <svg width={w} height={h} viewBox="0 0 20 20"><path d="M4 5.5A2 2 0 0 1 6 3.5h8a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-3.5 3v-3H6a2 2 0 0 1-2-2v-6Z" {...s}/></svg>;
    case 'folder':   return <svg width={w} height={h} viewBox="0 0 20 20"><path d="M3 6a2 2 0 0 1 2-2h3l1.6 1.8H15a2 2 0 0 1 2 2v6.7A2 2 0 0 1 15 16.5H5A2 2 0 0 1 3 14.5V6Z" {...s}/></svg>;
    case 'book':     return <svg width={w} height={h} viewBox="0 0 20 20"><path d="M4 4.5A1.5 1.5 0 0 1 5.5 3H10v14H5.5A1.5 1.5 0 0 1 4 15.5v-11ZM10 3h4.5A1.5 1.5 0 0 1 16 4.5v11A1.5 1.5 0 0 1 14.5 17H10V3Z" {...s}/></svg>;
    case 'search':   return <svg width={w} height={h} viewBox="0 0 20 20"><circle cx="9" cy="9" r="5.5" {...s}/><path d="M16.5 16.5 13.2 13.2" {...s}/></svg>;
    case 'apps':     return <svg width={w} height={h} viewBox="0 0 20 20"><rect x="3" y="3" width="6" height="6" rx="1.2" {...s}/><rect x="11" y="3" width="6" height="6" rx="1.2" {...s}/><rect x="3" y="11" width="6" height="6" rx="1.2" {...s}/><rect x="11" y="11" width="6" height="6" rx="1.2" {...s}/></svg>;
    case 'chev':     return <svg width={w} height={h} viewBox="0 0 20 20"><path d="M6 8l4 4 4-4" {...s}/></svg>;
    case 'star':     return <svg width={w} height={h} viewBox="0 0 20 20"><path d="M10 2.5l2.06 4.18 4.61.67-3.34 3.25.79 4.59L10 17.3 5.88 15.18l.79-4.59L3.33 7.35l4.61-.67L10 2.5Z" fill={color} stroke="none"/></svg>;
    case 'settings': return <svg width={w} height={h} viewBox="0 0 20 20"><circle cx="10" cy="10" r="2.5" {...s}/><path d="M16.5 10c0 .5-.05 1-.13 1.45l1.5 1.18-1.5 2.6-1.78-.7c-.7.6-1.5 1.05-2.4 1.3l-.27 1.9h-3l-.27-1.9c-.9-.25-1.7-.7-2.4-1.3l-1.78.7-1.5-2.6 1.5-1.18A8 8 0 0 1 3.5 10c0-.5.05-1 .13-1.45L2.13 7.37l1.5-2.6 1.78.7c.7-.6 1.5-1.05 2.4-1.3L8.08 2.3h3l.27 1.9c.9.25 1.7.7 2.4 1.3l1.78-.7 1.5 2.6-1.5 1.18c.08.45.13.95.13 1.45Z" {...s}/></svg>;
    case 'panel-left':  return <svg width={w} height={h} viewBox="0 0 20 20"><rect x="3" y="4" width="14" height="12" rx="2" {...s}/><path d="M8 4.5v11" {...s}/></svg>;
    default: return null;
  }
};

const PrimusMark = ({ size = 32 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" style={{ flexShrink: 0 }}>
    <defs>
      <linearGradient id="pm-bg" x1="0" y1="0" x2="1" y2="1">
        <stop offset="0%" stopColor="#7A1C1C"/>
        <stop offset="100%" stopColor="#5B1414"/>
      </linearGradient>
    </defs>
    <rect x="0" y="0" width="32" height="32" rx="8" fill="url(#pm-bg)"/>
    <text x="16" y="22" textAnchor="middle"
          fontFamily="Fraunces, Georgia, serif"
          fontWeight="600" fontSize="20" fill="white">P</text>
    <circle cx="24" cy="9" r="2.4" fill="#B68A3B"/>
  </svg>
);

const STARRED_CHATS = [
  { id: 's1', title: 'Firm-wide GTM strategy 2026', when: '3d' },
  { id: 's2', title: 'KSA giga-project tracker',     when: '1w' },
];

const RECENT_CHATS = [
  { id: 'c1', title: 'GCC fintech IPO scan · 2021–2026', when: '2h' },
  { id: 'c2', title: 'TCFD gap analysis · portfolio co.', when: '1d' },
  { id: 'c3', title: 'Renewables capex benchmarking',     when: '2d' },
  { id: 'c4', title: 'Acme reorg · operating model',      when: '4d' },
  { id: 'c5', title: 'Public Policy whitepaper outline',  when: '1w' },
];

// ──────────────────────────────────────────────────────────────────────────────
// Item row
// ──────────────────────────────────────────────────────────────────────────────
const NavItem = ({ icon, label, active, onClick, collapsed }) => {
  const inner = (
    <button onClick={onClick} title={collapsed ? label : ''} style={{
      height: 40, width: '100%',
      padding: collapsed ? 0 : '0 12px',
      borderRadius: 10,
      background: active ? 'rgba(255,255,255,0.85)' : 'transparent',
      color: active ? 'var(--maroon)' : 'var(--ink-2)',
      border: 'none', cursor: 'pointer',
      display: 'flex', alignItems: 'center',
      justifyContent: collapsed ? 'center' : 'flex-start',
      gap: 13,
      fontSize: 13.5, fontWeight: active ? 600 : 500,
      fontFamily: 'inherit', textAlign: 'left',
      transition: 'background 0.15s, color 0.15s',
      boxShadow: active ? '0 1px 2px rgba(60,30,20,0.04)' : 'none',
    }}
    onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'rgba(255,255,255,0.5)'; }}
    onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
    >
      <PIcon name={icon} size={18} color={active ? 'var(--maroon)' : 'var(--ink-2)'} />
      {!collapsed && <span style={{ flex: 1 }}>{label}</span>}
    </button>
  );
  return inner;
};

const sidebarSectionLabel = {
  fontSize: 10.5, fontWeight: 700, color: 'var(--mute)',
  letterSpacing: '0.08em', textTransform: 'uppercase',
  padding: '0 12px 8px', marginTop: 22,
};

const SidebarChatRow = ({ c, starred }) => (
  <button style={{
    height: 36, padding: '0 12px', borderRadius: 9,
    background: 'transparent', border: 'none', cursor: 'pointer',
    display: 'flex', alignItems: 'center', gap: 9, width: '100%',
    fontSize: 13, fontFamily: 'inherit', fontWeight: 500, color: 'var(--ink-2)',
    textAlign: 'left', transition: 'background 0.15s', flexShrink: 0,
  }}
  onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.5)'}
  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
  >
    {starred && <PIcon name="star" size={12} color="var(--gold)" />}
    <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.title}</span>
    <span style={{ fontSize: 11, color: 'var(--mute-2)', flexShrink: 0 }}>{c.when}</span>
  </button>
);

// ──────────────────────────────────────────────────────────────────────────────
// Sidebar
// ──────────────────────────────────────────────────────────────────────────────
const PrimusSidebar = ({ active, setRoute, collapsed, setCollapsed, currentUser, onLogout }) => {
  const [settingsOpen, setSettingsOpen] = React.useState(false);

  const displayName = currentUser?.full_name || 'You';
  const initials = displayName.split(' ').filter(Boolean).map(w => w[0].toUpperCase()).slice(0, 2).join('');
  const designation = currentUser?.designation
    ? currentUser.designation.split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' ')
    : 'Primus Partners';

  const w = collapsed ? 68 : 264;

  return (
    <aside style={{
      width: w, minWidth: w, height: '100%',
      background: 'linear-gradient(180deg, var(--bg-sidebar-2) 0%, var(--bg-sidebar) 100%)',
      borderRight: '1px solid var(--line)',
      display: 'flex', flexDirection: 'column',
      padding: collapsed ? '20px 10px 14px' : '20px 14px 14px',
      transition: 'width 0.22s ease, padding 0.22s ease',
      position: 'relative',
      zIndex: 5,
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center',
        justifyContent: collapsed ? 'center' : 'space-between',
        padding: collapsed ? '0' : '0 4px',
        marginBottom: collapsed ? 12 : 20,
        gap: 8,
        flexDirection: collapsed ? 'column' : 'row',
      }}>
        {!collapsed && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <PrimusMark size={26} />
            <span className="wordmark" style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.005em', color: 'var(--maroon)' }}>
              Primus IQ
            </span>
          </div>
        )}
        {collapsed && <PrimusMark size={30} />}
        <button onClick={() => setCollapsed(!collapsed)} title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          style={{
            width: collapsed ? 38 : 28, height: 28, borderRadius: 8,
            background: 'transparent',
            border: 'none',
            cursor: 'pointer',
            display: 'grid', placeItems: 'center',
            color: 'var(--mute)',
            transition: 'background 0.15s, color 0.15s',
            marginTop: collapsed ? 4 : 0,
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'rgba(122,28,28,0.06)'; e.currentTarget.style.color = 'var(--maroon)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--mute)'; }}
        >
          <PIcon name="panel-left" size={17} />
        </button>
      </div>

      {/* New chat */}
      <button onClick={() => setRoute('chat')} title={collapsed ? 'New chat' : ''} style={{
        height: 40, width: '100%',
        padding: collapsed ? 0 : '0 12px',
        borderRadius: 11,
        background: 'var(--maroon)', color: 'white',
        border: 'none', cursor: 'pointer',
        display: 'flex', alignItems: 'center',
        justifyContent: collapsed ? 'center' : 'flex-start',
        gap: 13,
        fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
        boxShadow: '0 2px 8px rgba(122,28,28,0.16)',
        marginBottom: 10,
        transition: 'all 0.15s',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--maroon-deep)'}
      onMouseLeave={e => e.currentTarget.style.background = 'var(--maroon)'}
      >
        <PIcon name="plus" size={18} color="white" />
        {!collapsed && 'New chat'}
      </button>

      {/* Scroll region — nav + chat history, starts right after New chat (Claude-style) */}
      <div className="pi-thin-scroll" style={{
        flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden',
        display: 'flex', flexDirection: 'column', paddingRight: 4, marginRight: -4,
      }}>
        {/* Primary nav — generous spacing between items */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          <NavItem icon="chat"   label="Chat"         active={active === 'chat'}    onClick={() => setRoute('chat')} collapsed={collapsed}/>
          <NavItem icon="folder" label="Projects"     active={active === 'projects' || active === 'project-detail'} onClick={() => setRoute('projects')} collapsed={collapsed}/>
          <NavItem icon="book"   label="Library"      active={active === 'library'} onClick={() => setRoute('library')} collapsed={collapsed}/>
          <NavItem icon="search" label="Search"       active={active === 'search'}  onClick={() => setRoute('search')} collapsed={collapsed}/>
          <NavItem icon="apps"   label="Applications" active={active === 'apps' || active.startsWith('app-')} onClick={() => setRoute('apps')} collapsed={collapsed}/>
        </div>

        {!collapsed && (
          <>
            {/* Starred */}
            <div style={sidebarSectionLabel}>Starred</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {STARRED_CHATS.map(c => <SidebarChatRow key={c.id} c={c} starred />)}
            </div>

            {/* Recent */}
            <div style={{ ...sidebarSectionLabel, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>Recent</span>
              <button style={{ background: 'none', border: 'none', color: 'var(--mute)', fontSize: 11, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer', padding: 0, textTransform: 'none', letterSpacing: 0 }}>View all</button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {RECENT_CHATS.map(c => <SidebarChatRow key={c.id} c={c} />)}
            </div>
          </>
        )}
      </div>

      {/* User pod */}
      <div style={{ position: 'relative', marginTop: 12 }}>
        {settingsOpen && !collapsed && (
          <div style={{
            position: 'absolute', bottom: '100%', left: 0, right: 0, marginBottom: 6,
            background: 'white', border: '1px solid var(--line-2)', borderRadius: 10,
            boxShadow: '0 8px 24px rgba(26,22,20,0.12)', overflow: 'hidden', zIndex: 20,
          }}>
            <button onClick={() => { setSettingsOpen(false); setRoute('profile'); }} style={settingItemStyle}>
              Edit profile
            </button>
            <div style={{ height: 1, background: 'var(--line)' }} />
            <button onClick={() => { setSettingsOpen(false); onLogout && onLogout(); }} style={{ ...settingItemStyle, color: 'var(--maroon)' }}>
              Sign out
            </button>
          </div>
        )}
        <div onClick={() => !collapsed && setSettingsOpen(o => !o)} style={{
          padding: collapsed ? 6 : 10,
          borderRadius: 12,
          background: settingsOpen ? 'rgba(255,255,255,0.85)' : 'rgba(255,255,255,0.6)',
          border: '1px solid var(--line)',
          display: 'flex', alignItems: 'center',
          justifyContent: collapsed ? 'center' : 'flex-start',
          gap: 10,
          cursor: 'pointer', transition: 'background 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.85)'}
        onMouseLeave={e => { if (!settingsOpen) e.currentTarget.style.background = 'rgba(255,255,255,0.6)'; }}
        title={collapsed ? displayName : ''}
        >
          <div style={{
            width: 30, height: 30, borderRadius: 15,
            background: 'linear-gradient(135deg, var(--maroon), var(--maroon-deep))',
            color: 'white', display: 'grid', placeItems: 'center',
            fontSize: 11, fontWeight: 700, flexShrink: 0,
          }}>{initials}</div>
          {!collapsed && (
            <>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, color: 'var(--ink)', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{displayName}</div>
                <div style={{ fontSize: 10, fontWeight: 500, color: 'var(--mute)' }}>{designation}</div>
              </div>
              <PIcon name="settings" size={14} color="var(--mute)" />
            </>
          )}
        </div>
      </div>
    </aside>
  );
};

const settingItemStyle = {
  width: '100%', padding: '9px 14px', background: 'transparent', border: 'none',
  cursor: 'pointer', textAlign: 'left', fontSize: 12, fontFamily: 'inherit',
  color: 'var(--ink)', transition: 'background 0.12s',
  display: 'block',
};

Object.assign(window, { PrimusSidebar, PIcon, NavItem, PrimusMark, SidebarChatRow, RECENT_CHATS, STARRED_CHATS, settingItemStyle });
