// Sidebar + Topbar shell

const NAV = [
  { group: 'Observe', items: [
    { id: 'dashboard',  label: 'Command Center', icon: 'command' },
    { id: 'live',       label: 'Live Feed',      icon: 'bolt',  live: true },
    { id: 'identity',   label: 'Identity Graph', icon: 'graph' },
  ]},
  { group: 'Understand', items: [
    { id: 'journey',    label: 'Journey Map',    icon: 'map' },
    { id: 'insights',   label: 'Insights',       icon: 'bulb' },
    { id: 'scope',      label: 'Scope Analytics',icon: 'chart' },
    { id: 'anomalies',  label: 'Anomalies',      icon: 'alert', badge: 3 },
    { id: 'ai',         label: 'AI Assistant',   icon: 'sparkle', kbd: '⌘K' },
  ]},
  { group: 'Act', items: [
    { id: 'decisions',  label: 'Decisions',      icon: 'brain' },
    { id: 'channels',   label: 'Channels',       icon: 'radio' },
    { id: 'community',  label: 'Community',      icon: 'users' },
    { id: 'organic',    label: 'Organic',        icon: 'leaf' },
    { id: 'creator',    label: 'Creators',       icon: 'star' },
    { id: 'video',      label: 'Video Studio',   icon: 'play' },
  ]},
  { group: 'Platform', items: [
    { id: 'brand',      label: 'Brand Profile',  icon: 'tag' },
    { id: 'context',    label: 'AI Visibility',  icon: 'eye' },
    { id: 'partner',    label: 'Partner API',    icon: 'plug' },
    { id: 'memory',     label: 'Memory',         icon: 'clipboard' },
    { id: 'keys',       label: 'API Keys',       icon: 'key' },
    { id: 'settings',   label: 'Settings',       icon: 'cog' },
  ]},
];

const Sidebar = ({ active, setActive }) => {
  const [orgName, setOrgName] = React.useState('Northwind Labs');
  const [orgPlan, setOrgPlan] = React.useState('Growth · 12 seats');

  React.useEffect(() => {
    arFetch('/v1/auth/keys')
      .then(data => {
        if (data.org_name) setOrgName(data.org_name);
        if (data.plan) setOrgPlan(data.plan + (data.seats ? ` · ${data.seats} seats` : ''));
      })
      .catch(() => {});
  }, []);

  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>

      <div className="sidebar-nav-scroll">
        {NAV.map((section, si) => (
          <React.Fragment key={section.group}>
            <div className="nav-section-label" style={{marginTop: si > 0 ? 10 : 0}}>
              {section.group}
            </div>
            {section.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 && <span className="nav-badge alert">{it.badge}</span>}
                {it.kbd && !it.badge && !it.live && <span className="nav-badge">{it.kbd}</span>}
              </div>
            ))}
          </React.Fragment>
        ))}
      </div>

      <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">{orgName}</div>
            <div className="org-plan">{orgPlan}</div>
          </div>
          <div
            title="Sign out"
            onClick={() => {
              localStorage.removeItem('ar_token');
              localStorage.removeItem('ar_demo');
              localStorage.removeItem('ar_active');
              window.location.reload();
            }}
            style={{cursor:'pointer',color:'var(--text-4)',display:'flex',alignItems:'center',padding:'2px 4px',borderRadius:4,flexShrink:0}}
            onMouseOver={e=>e.currentTarget.style.color='var(--rose)'}
            onMouseOut={e=>e.currentTarget.style.color='var(--text-4)'}
          >
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" 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>
          </div>
        </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',
    scope: 'Scope Analytics',
    anomalies: 'Anomalies',
    decisions: 'Decisions',
    channels:  'Channels',
    organic:   'Organic',
    community: 'Community Signals',
    creator:   'Creators',
    video:     'Video Studio',
    brand:     'Brand Profile',
    context:   'AI Visibility',
    partner:   'Partner API',
    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()); setNow(Date.now()); 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'}
      />
      {!connected && (
        <span style={{
          fontSize: 9, fontFamily: 'var(--mono)', color: 'var(--amber)',
          background: 'rgba(245,158,11,0.12)', border: '1px solid rgba(245,158,11,0.3)',
          borderRadius: 4, padding: '1px 6px', marginLeft: 4,
        }}>DEMO</span>
      )}
      <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;
