/* Sidebar + topbar. Navigation is hash-based so every task and review has a
   URL that can be pasted into Slack. */

const NAV = [
  {
    label: 'Work',
    items: [
      { route: 'board', title: 'Board', icon: 'board' },
      { route: 'my', title: 'My tasks', icon: 'list' },
      { route: 'workload', title: 'Workload', icon: 'target' },
    ],
  },
  {
    label: 'Manage',
    items: [
      { route: 'clients', title: 'Clients', icon: 'building', adminOnly: true },
      { route: 'team', title: 'Team', icon: 'users', adminOnly: true },
    ],
  },
];

function Sidebar({ route, go, me, myCount, open, closeMobile }) {
  return (
    <aside className={'sidebar' + (open ? ' open' : '')}>
      <div className="sidebar-brand">
        <img src="/logo-linea.png" alt="Linea" className="brand-logo" />
        <span className="brand-suffix">Studio</span>
      </div>
      <nav className="nav">
        {NAV.map((section) => {
          const items = section.items.filter((i) => !i.adminOnly || me.role === 'admin');
          if (!items.length) return null;
          return (
            <div key={section.label}>
              <div className="nav-label">{section.label}</div>
              {items.map((item) => (
                <div
                  key={item.route}
                  className={'nav-item' + (route === item.route ? ' active' : '')}
                  onClick={() => { go(item.route); closeMobile && closeMobile(); }}
                >
                  <Icon name={item.icon} size={16} />
                  {item.title}
                  {item.route === 'my' && myCount > 0 && <span className="count">{myCount}</span>}
                </div>
              ))}
            </div>
          );
        })}
      </nav>
      <div className="sidebar-foot">
        <Avatar user={me} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {me.name || me.email}
          </div>
          <div className="small muted">{me.job_title || me.role}</div>
        </div>
        <span className="spacer" />
        <button className="btn ghost sm" title="Sign out"
                onClick={() => api.post('/auth/logout').then(() => { location.href = '/login.html'; })}>
          <Icon name="external" size={15} />
        </button>
      </div>
    </aside>
  );
}

function NotificationBell() {
  const [data, setData] = React.useState({ items: [], unread: 0 });
  const [open, setOpen] = React.useState(false);

  const load = React.useCallback(() => {
    api.get('/api/notifications?limit=20').then(setData).catch(() => {});
  }, []);

  React.useEffect(() => {
    load();
    const t = setInterval(load, 60000);
    return () => clearInterval(t);
  }, [load]);

  const openPanel = () => {
    setOpen((v) => !v);
    if (!open && data.unread) api.post('/api/notifications/read').then(load).catch(() => {});
  };

  return (
    <div style={{ position: 'relative' }}>
      <button className="btn ghost" onClick={openPanel} title="Notifications">
        <Icon name="bell" size={17} />
        {data.unread > 0 && (
          <span style={{
            position: 'absolute', top: 2, right: 2, minWidth: 16, height: 16, borderRadius: 10,
            background: 'var(--red)', color: '#fff', fontSize: 10, fontWeight: 700,
            display: 'grid', placeItems: 'center', padding: '0 4px',
          }}>{data.unread}</span>
        )}
      </button>
      {open && (
        <div className="card" style={{
          position: 'absolute', right: 0, top: 44, width: 340, zIndex: 60,
          maxHeight: 420, overflowY: 'auto', boxShadow: 'var(--shadow-lg)',
        }}>
          {data.items.length === 0 && <div className="empty small">Nothing yet</div>}
          {data.items.map((n) => (
            <div key={n.id} style={{ padding: '11px 14px', borderBottom: '1px solid var(--border)', cursor: n.task_id ? 'pointer' : 'default' }}
                 onClick={() => { if (n.task_id) { location.hash = `#/task/${n.task_id}`; setOpen(false); } }}>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{n.title}</div>
              {n.body && <div className="small muted" style={{ marginTop: 2 }}>{n.body}</div>}
              <div className="small muted" style={{ marginTop: 4 }}>{ago(n.created_at)}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function Topbar({ title, actions, onBack, openMenu }) {
  return (
    <header className="topbar">
      <button className="btn ghost sm mobile-menu" onClick={openMenu}>
        <Icon name="menu" size={18} />
      </button>
      {onBack && (
        <button className="btn ghost sm" onClick={onBack} title="Back">
          <Icon name="back" size={16} />
        </button>
      )}
      <h1>{title}</h1>
      <span className="spacer" />
      {actions}
      <NotificationBell />
    </header>
  );
}
