// sidebar.jsx — left-nav with team header, sections, and freshness footer.
const { useState: sbUseState, useEffect: sbUseEffect } = React;

function Sidebar({ tab, setTab, viewer, selectedTeam, setSelectedTeam, lastLoadedAt, refreshing, onRefresh }) {
  const yd = window.YD;
  const isAdmin = viewer.role === 'admin';
  // Admins get a project picker so they can view any team from a PL's
  // perspective. Lazy-load the team list once on mount — it rarely changes
  // during a session and the response is small.
  const [teamList, setTeamList] = sbUseState(null);
  sbUseEffect(() => {
    if (!isAdmin) return;
    window.YDApp.call('getTeamList', {})
      .then((resp) => setTeamList((resp && resp.teams) || []))
      .catch((e) => console.warn('getTeamList failed', e));
  }, [isAdmin]);

  // Pending-request count (shift changes + time off) for the sidebar
  // badge. Polls every 60s while the tab is visible — cheap. Admin sees
  // company-wide; lead sees their own team only.
  const [pendingRequests, setPendingRequests] = sbUseState(0);
  sbUseEffect(() => {
    let cancelled = false;
    const tick = () => {
      const collections = ['shiftChangeRequests', 'timeOffRequests'];
      Promise.all(collections.map((col) => {
        let q = window.YDApp.firestore.collection(col).where('status', '==', 'pending');
        if (!isAdmin) q = q.where('team', '==', yd.TEAM.teamName || '');
        return q.get({ source: 'server' }).then((snap) => snap.size).catch(() => 0);
      })).then((counts) => {
        if (!cancelled) setPendingRequests(counts.reduce((a, b) => a + b, 0));
      });
    };
    tick();
    const t = setInterval(() => { if (document.visibilityState === 'visible') tick(); }, 60_000);
    return () => { cancelled = true; clearInterval(t); };
  }, [isAdmin, yd.TEAM.teamName]);

  // Custom dropdown for the admin project picker. Native <select> on a
  // dark sidebar looked like an OS form widget glued onto the chrome —
  // this matches the team-name typography and pops a lightweight menu
  // below it. Closes on outside click.
  const [pickerOpen, setPickerOpen] = sbUseState(false);
  sbUseEffect(() => {
    if (!pickerOpen) return;
    const onDoc = (e) => {
      const el = document.getElementById('sb-team-picker');
      if (el && !el.contains(e.target)) setPickerOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [pickerOpen]);
  const counts = yd.BY_SEVERITY;
  const notClocked = yd.MEMBERS.filter(m => m.clockInReason === 'late_critical' || m.clockInReason === 'late_recent').length;
  // Sidebar badge tracks "needs attention" — open actions only, not the
  // full audit. Anything dismissed/resolved/escalated drops off.
  const activeActions = (yd.ACTION_LOG || []).filter(a => a.status === 'open').length;

  const TABS = [
    { id: 'overview',   label: 'Overview',     section: 'Today' },
    { id: 'clockin',    label: 'Clock-in',     section: 'Today', badge: notClocked, badgeTone: notClocked > 50 ? 'danger' : notClocked > 10 ? 'warn' : null },
    { id: 'performance',label: 'Performance',  section: 'Analyze' },
    { id: 'roster',     label: 'Roster',       section: 'Analyze' },
    { id: 'actionlog',  label: 'Action Log',   section: 'Analyze', badge: activeActions || null },
    { id: 'requests',   label: 'Requests',     section: 'Analyze', badge: pendingRequests || null, badgeTone: pendingRequests > 0 ? 'warn' : null },
    { id: 'pl',         label: 'Project Tracking', section: 'Analyze' },
    { id: 'quality',    label: 'Quality',      section: 'Analyze' },
  ];
  if (viewer.role === 'admin') {
    TABS.push({ id: 'admin', label: 'Settings', section: 'Admin' });
  }
  const grouped = TABS.reduce((acc, t) => { (acc[t.section] = acc[t.section] || []).push(t); return acc; }, {});

  const fr = yd.FRESHNESS || {};
  const quidloAgoStr = fr.quidloMinutesAgo == null ? '—' : (fr.quidloMinutesAgo + 'm ago');
  const kpiAgoStr =
    fr.kpiMinutesAgo == null ? '—'
    : fr.kpiMinutesAgo < 60   ? (fr.kpiMinutesAgo + 'm ago')
    : (Math.round(fr.kpiMinutesAgo / 60) + 'h ago');
  const quidloStale = fr.quidloMinutesAgo != null && fr.quidloMinutesAgo > (fr.quidloStaleThreshold || 15);
  const kpiStale    = fr.kpiMinutesAgo    != null && fr.kpiMinutesAgo    > (fr.kpiStaleThreshold    || 240);

  return (
    <div className="sb">
      <div className="sb-top">
        <div className="sb-brand">
          <img src="/img/yenda-mark.png" alt="" width="20" height="20" style={{ borderRadius: '50%' }}/>
          <img src="/img/yenda-wordmark-white.svg" alt="Yenda" height="18"/>
        </div>
        <div className="sb-team" id="sb-team-picker" style={{ position: 'relative' }}>
          {isAdmin && teamList && teamList.length > 0 ? (
            <button
              onClick={() => setPickerOpen((v) => !v)}
              title="Switch project"
              style={{
                background: 'transparent',
                border: 0,
                padding: 0,
                width: '100%',
                textAlign: 'left',
                cursor: 'pointer',
                color: 'inherit',
                font: 'inherit',
              }}>
              <div className="sb-team-name" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {yd.TEAM.teamName}
                </span>
                <span style={{ opacity: 0.55, fontSize: 11, transform: pickerOpen ? 'rotate(180deg)' : 'none', transition: 'transform .15s ease' }}>
                  ▾
                </span>
              </div>
            </button>
          ) : (
            <div className="sb-team-name">{yd.TEAM.teamName}</div>
          )}
          <div className="sb-team-meta">
            <span>Lead: {yd.TEAM.leadName || '—'}</span>
            <span className="dotsep">·</span>
            <span>{yd.MEMBERS.length} people</span>
          </div>

          {pickerOpen && isAdmin && teamList && (
            <div style={{
              position: 'absolute',
              left: 0, right: 0, top: 'calc(100% + 6px)',
              background: '#1a1a1a',
              border: '1px solid rgba(255,255,255,0.1)',
              borderRadius: 8,
              boxShadow: '0 12px 32px rgba(0,0,0,0.45)',
              padding: 4,
              zIndex: 50,
              maxHeight: 360,
              overflowY: 'auto',
            }}>
              {teamList.map((t) => {
                const active = (selectedTeam || yd.TEAM.teamName) === t.name;
                return (
                  <button
                    key={t.name}
                    onClick={() => { setSelectedTeam && setSelectedTeam(t.name); setPickerOpen(false); }}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      width: '100%',
                      padding: '8px 10px',
                      background: active ? 'rgba(255,255,255,0.08)' : 'transparent',
                      border: 0,
                      borderRadius: 6,
                      color: '#fff',
                      cursor: 'pointer',
                      fontSize: 12,
                      fontFamily: 'inherit',
                      textAlign: 'left',
                    }}
                    onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; }}
                    onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
                    <span style={{ fontWeight: active ? 700 : 500 }}>{t.name}</span>
                    <span style={{ color: 'rgba(255,255,255,0.4)', fontSize: 11 }}>{t.memberCount}</span>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>

      <nav className="sb-nav">
        {Object.entries(grouped).map(([section, items]) => (
          <div key={section}>
            <div className="sb-nav-sec">{section}</div>
            {items.map(t => (
              <button
                key={t.id}
                className={'sb-nav-item' + (tab === t.id ? ' active' : '')}
                onClick={() => setTab(t.id)}>
                <span className="lbl">{t.label}</span>
                {t.badge != null && t.badge > 0 && (
                  <span className={'sb-badge ' + (t.badgeTone || '')}>{t.badge}</span>
                )}
              </button>
            ))}
          </div>
        ))}
      </nav>

      <div className="sb-foot">
        <button
          className="sb-refresh"
          onClick={onRefresh}
          disabled={refreshing}
          title="Refresh team data">
          <span className="sb-refresh-icon" style={refreshing ? { animation: 'sbspin 0.8s linear infinite' } : undefined}>↻</span>
          <span>{refreshing ? 'Refreshing…' : 'Refresh' + (lastLoadedAt ? ` · ${minsAgoLabel(lastLoadedAt)}` : '')}</span>
        </button>
        <div className="sb-fresh">
          <span className={'dot' + (quidloStale ? ' stale' : '')}/>
          <span>Quidlo {quidloAgoStr}</span>
        </div>
        <div className="sb-fresh">
          <span className={'dot' + (kpiStale ? ' stale' : '')}/>
          <span>KPI {kpiAgoStr}</span>
        </div>
        <div className="sb-user">
          <Avatar name={viewer.name} size={28}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="nm" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{viewer.name}</div>
            <div className="rl">{viewer.role === 'admin' ? 'Admin' : viewer.role === 'teamLead' ? 'Team lead' : 'Annotator'}</div>
          </div>
          <button
            onClick={() => window.YDApp.signOut()}
            title="Sign out"
            style={{ background: 'transparent', border: 0, color: 'rgba(255,255,255,0.5)', cursor: 'pointer', padding: 4, fontSize: 12 }}>
            ↪
          </button>
        </div>
      </div>
    </div>
  );
}

function minsAgoLabel(ts) {
  if (!ts) return '';
  const m = Math.max(0, Math.round((Date.now() - ts) / 60_000));
  if (m === 0) return 'just now';
  if (m === 1) return '1m ago';
  if (m < 60) return m + 'm ago';
  return Math.round(m / 60) + 'h ago';
}

Object.assign(window, { Sidebar });
