// Sidebar + Topbar shell
// NAV follows the UX lifecycle: Observe → Understand → Act → Platform

const NAV = [
  { group: 'observe', label: 'Observe', items: [
    { id: 'dashboard',  label: 'Command Center', icon: 'command' },
    { id: 'live',       label: 'Live Feed',      icon: 'bolt', live: true },
  ]},
  { group: 'understand', label: 'Understand', items: [
    { id: 'identity',   label: 'Identity Graph', icon: 'graph' },
    { id: 'journey',    label: 'Journey Map',    icon: 'map' },
    { id: 'insights',   label: 'Insights',       icon: 'bulb' },
    { id: 'anomalies',  label: 'Anomalies',      icon: 'alert', badge: 3 },
  ]},
  { group: 'act', label: 'Act', items: [
    { id: 'ai',         label: 'AI Assistant',   icon: 'sparkle', kbd: '⌘K' },
    { id: 'decisions',  label: 'Decisions',      icon: 'brain' },
    { id: 'channels',   label: 'Channels',       icon: 'radio' },
    { id: 'geo',        label: 'GEO',            icon: 'search', badge: 'new' },
  ]},
  { group: 'platform', label: 'Platform', items: [
    { id: 'memory',     label: 'Memory',         icon: 'clipboard' },
    { id: 'keys',       label: 'API Keys',       icon: 'key' },
    { id: 'settings',   label: 'Settings',       icon: 'cog' },
  ]},
];

const Sidebar = ({ active, setActive }) => {
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark" />
        <div style={{flex: 1, minWidth: 0}}>
          <div className="brand-name">AstraReach</div>
          <div className="brand-version">v1 · us-east</div>
        </div>
      </div>

      {NAV.map((group, gi) => (
        <React.Fragment key={group.group}>
          <div className="nav-section-label" style={{marginTop: gi > 0 ? 12 : 0}}>
            {group.label}
          </div>
          {group.items.map(it => (
            <div key={it.id}
                 className={`nav-item ${active === it.id ? 'active' : ''}`}
                 onClick={() => !it.disabled && setActive(it.id)}
                 style={{opacity: it.disabled ? 0.5 : 1}}>
              <Icon name={it.icon} size={15} />
              <span>{it.label}</span>
              {it.live && <span className="dot pulse" style={{marginLeft: 'auto'}} />}
              {it.badge === 'new'
                ? <span className="nav-badge" style={{background:'rgba(6,182,212,0.18)',color:'#06B6D4',fontSize:9,fontWeight:700,letterSpacing:'0.05em'}}>NEW</span>
                : it.badge
                  ? <span className="nav-badge alert">{it.badge}</span>
                  : null}
              {it.kbd && !it.badge && !it.live && <span className="nav-badge">{it.kbd}</span>}
            </div>
          ))}
        </React.Fragment>
      ))}

      <div className="sidebar-footer">
        <div className="sys-health">
          <span className="dot pulse" />
          <span style={{fontSize: 11}}>All systems healthy</span>
          <span className="mono" style={{marginLeft: 'auto', fontSize: 10, color: 'var(--text-4)'}}>99.98%</span>
        </div>
        <div className="org-card">
          <div className="org-avatar">NL</div>
          <div style={{flex: 1, minWidth: 0}}>
            <div className="org-name">Northwind Labs</div>
            <div className="org-plan">Growth · 12 seats</div>
          </div>
          <button
            title="Sign out"
            onClick={() => window.AR_SIGNOUT?.()}
            style={{background: 'none', border: '1px solid var(--border)', cursor: 'pointer', padding: '3px 8px', color: 'var(--text-3)', borderRadius: 5, display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0, fontSize: 11}}
            onMouseEnter={e => { e.currentTarget.style.color = 'var(--text-1)'; e.currentTarget.style.borderColor = 'var(--text-3)'; }}
            onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-3)'; e.currentTarget.style.borderColor = 'var(--border)'; }}
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
              <polyline points="16 17 21 12 16 7"/>
              <line x1="21" y1="12" x2="9" y2="12"/>
            </svg>
            Sign out
          </button>
        </div>
      </div>
    </aside>
  );
};

const Topbar = ({ active, setActive, onAskAI, dateRange, setDateRange, onRefresh }) => {
  const titleMap = {
    dashboard: 'Command Center',
    live: 'Live Feed',
    identity: 'Identity Graph',
    journey: 'Journey Map',
    ai: 'AI Assistant',
    insights: 'Insights',
    anomalies: 'Anomalies',
    decisions: 'Decisions',
    channels:  'Channels',
    geo:       'Generative Engine Optimization',
    memory:    'Memory',
    keys:      'API Keys',
    settings:  'Settings',
  };

  const [connected, setConnected] = React.useState(window.AR_CONNECTED);
  React.useEffect(() => {
    const check = () => window.arCheckConnectivity().then(ok => setConnected(ok));
    check();
    const intv = setInterval(check, 30000);
    return () => clearInterval(intv);
  }, []);

  const [lastRefreshed, setLastRefreshed] = React.useState(new Date());
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 15000);
    return () => clearInterval(t);
  }, []);
  const handleRefresh = () => { setLastRefreshed(new Date()); onRefresh && onRefresh(); };
  const secAgo = Math.round((now - lastRefreshed.getTime()) / 1000);
  const timeAgo = secAgo < 60 ? `${secAgo}s ago` : `${Math.round(secAgo / 60)}m ago`;

  return (
    <div className="topbar">
      <div className="breadcrumb">
        <span>Northwind Labs</span>
        <span className="sep">/</span>
        <span className="current">{titleMap[active] || active}</span>
      </div>
      <span
        className="dot"
        style={{width: 7, height: 7, background: connected ? '#10B981' : 'var(--text-4)', flexShrink: 0, marginRight: 4}}
        title={connected ? 'Connected to live API' : 'Mock mode — set API URL in Tweaks'}
      />
      <div className="topbar-spacer" />

      {active !== 'ai' && (
        <div className="seg" style={{marginRight: 4}}>
          {['7d','30d','90d','Custom'].map(w => (
            <button key={w} className={dateRange === w ? 'active' : ''} onClick={() => setDateRange(w)}>{w}</button>
          ))}
        </div>
      )}

      <button className="btn ghost" title="Refresh" onClick={handleRefresh}>
        <Icon name="refresh" size={13} />
        <span style={{fontSize: 11, color: 'var(--text-3)'}}>Updated {timeAgo}</span>
      </button>

      <button className="btn primary" onClick={onAskAI}>
        <Icon name="sparkle" size={13} />
        <span>Ask AI</span>
        <span className="kbd">⌘K</span>
      </button>
    </div>
  );
};

window.Sidebar = Sidebar;
window.Topbar = Topbar;
