// Dashboard Gestor — painel exclusivo para owner/admin da organização.
// Mostra KPIs globais, gráfico de atividade diária, distribuição por módulo
// e tabela de produtividade por usuário.

// ── Gráfico de barras SVG (atividade diária) ─────────────────────────────────
const GestorBarChart = ({ days = [], colorMap = {} }) => {
  if (!days.length) return (
    <div style={{ height: 120, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>
      Sem dados no período.
    </div>
  );

  const max = Math.max(...days.map(d => d.total), 1);
  const W = 600, H = 100, PAD = 2;
  const barW = Math.max((W / days.length) - PAD, 2);

  // Agrupar entidades principais para stack
  const TYPES = ['task', 'case', 'client', 'document', 'proposta', 'levantamento'];
  const COLORS = {
    task:         '#2563EB',
    case:         '#7C3AED',
    client:       '#059669',
    document:     '#D97706',
    proposta:     '#DC2626',
    levantamento: '#0891B2',
  };

  // Últimos 30 dias: mostrar tick de data a cada 7 dias aprox.
  const tickEvery = Math.max(1, Math.floor(days.length / 6));

  return (
    <div style={{ width: '100%', overflowX: 'auto' }}>
      <svg
        viewBox={`0 0 ${W} ${H + 18}`}
        style={{ width: '100%', display: 'block', minWidth: Math.min(days.length * 10, 300) }}
        preserveAspectRatio="none"
      >
        {days.map((d, i) => {
          const x = i * (W / days.length) + PAD / 2;
          const totalH = (d.total / max) * H;
          let yOffset = H;
          const bars = [];

          // Camadas empilhadas
          for (const type of TYPES) {
            const count = d.by_type?.[type] || 0;
            if (!count) continue;
            const bh = (count / max) * H;
            yOffset -= bh;
            bars.push(
              <rect key={type} x={x} y={yOffset} width={barW} height={bh}
                fill={COLORS[type] || '#94A3B8'} rx={0.5} opacity={0.9} />
            );
          }
          // Resto (outros tipos)
          const typed = TYPES.reduce((s, t) => s + (d.by_type?.[t] || 0), 0);
          const other = d.total - typed;
          if (other > 0) {
            const bh = (other / max) * H;
            yOffset -= bh;
            bars.push(
              <rect key="other" x={x} y={yOffset} width={barW} height={bh}
                fill="#94A3B8" rx={0.5} opacity={0.7} />
            );
          }

          // Tick de data
          const showTick = i % tickEvery === 0;
          const label = d.date ? d.date.slice(5) : ''; // MM-DD

          return (
            <g key={d.date || i}>
              {bars}
              {showTick && (
                <text x={x + barW / 2} y={H + 14} textAnchor="middle"
                  fontSize={7} fill="var(--fg-muted)" fontFamily="inherit">
                  {label}
                </text>
              )}
            </g>
          );
        })}
        {/* Linha de base */}
        <line x1={0} y1={H} x2={W} y2={H} stroke="var(--border)" strokeWidth={0.5} />
      </svg>

      {/* Legenda */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px 16px', marginTop: 8 }}>
        {Object.entries(COLORS).map(([type, color]) => (
          <div key={type} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: 'var(--fg-muted)' }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: color, display: 'inline-block', flexShrink: 0 }} />
            {({ task: 'Tarefa', case: 'Caso', client: 'Cliente', document: 'Documento', proposta: 'Proposta', levantamento: 'MLE' })[type]}
          </div>
        ))}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: 'var(--fg-muted)' }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: '#94A3B8', display: 'inline-block', flexShrink: 0 }} />
          Outros
        </div>
      </div>
    </div>
  );
};

// ── Gráfico de rosca SVG (distribuição por módulo) ───────────────────────────
const DonutChart = ({ segments = [], size = 130 }) => {
  const total = segments.reduce((s, d) => s + d.value, 0);
  if (!total) return (
    <div style={{ width: size, height: size, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-muted)', fontSize: 11 }}>
      Sem dados
    </div>
  );

  const cx = size / 2, cy = size / 2;
  const R = size / 2 - 4, r = R * 0.58;
  let angle = -Math.PI / 2;

  const polar = (a, radius) => [
    cx + radius * Math.cos(a),
    cy + radius * Math.sin(a),
  ];

  const slices = segments.map(d => {
    const pct = d.value / total;
    const start = angle;
    angle += pct * 2 * Math.PI;
    return { ...d, start, end: angle, pct };
  });

  const arcPath = (s) => {
    if (s.pct >= 0.9999) {
      // Círculo completo — usar dois semi-círculos
      return `M ${cx} ${cy - R} A ${R} ${R} 0 0 1 ${cx} ${cy + R} A ${R} ${R} 0 0 1 ${cx} ${cy - R} ` +
             `M ${cx} ${cy - r} A ${r} ${r} 0 0 0 ${cx} ${cy + r} A ${r} ${r} 0 0 0 ${cx} ${cy - r} Z`;
    }
    const [x1, y1] = polar(s.start, R);
    const [x2, y2] = polar(s.end, R);
    const [ix1, iy1] = polar(s.start, r);
    const [ix2, iy2] = polar(s.end, r);
    const large = (s.end - s.start) > Math.PI ? 1 : 0;
    return `M ${x1} ${y1} A ${R} ${R} 0 ${large} 1 ${x2} ${y2} ` +
           `L ${ix2} ${iy2} A ${r} ${r} 0 ${large} 0 ${ix1} ${iy1} Z`;
  };

  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} style={{ display: 'block' }}>
      {slices.map((s, i) => (
        <path key={i} d={arcPath(s)} fill={s.color} opacity={0.92} />
      ))}
      <text x={cx} y={cy - 7} textAnchor="middle" dominantBaseline="middle"
        fontSize={Math.round(size * 0.13)} fontWeight={700} fill="var(--octale-navy)" fontFamily="inherit">
        {total}
      </text>
      <text x={cx} y={cy + 10} textAnchor="middle" dominantBaseline="middle"
        fontSize={Math.round(size * 0.07)} fill="var(--fg-muted)" fontFamily="inherit">
        ações
      </text>
    </svg>
  );
};

// ── Cartão de KPI ─────────────────────────────────────────────────────────────
const GestorKpiCard = ({ label, value, sub, accent, warn }) => (
  <div className="kpi" style={{ borderTop: `3px solid ${accent || 'var(--octale-navy)'}` }}>
    <div className="lbl">{label}</div>
    <div className="val" style={{ color: warn ? '#C2253E' : undefined }}>
      {value ?? <span className="spinner" style={{ width: 14, height: 14, verticalAlign: 'middle' }} />}
    </div>
    {sub && <div className="delta">{sub}</div>}
  </div>
);

// ── Tabela de produtividade por usuário ───────────────────────────────────────
const GestorUserTable = ({ period }) => {
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [sortKey, setSortKey] = React.useState('total');
  const [sortDir, setSortDir] = React.useState('desc');

  React.useEffect(() => {
    setLoading(true);
    window.OctaleApi.dashboard.userActivity(period)
      .then(d => setUsers(d.users || []))
      .catch(() => setUsers([]))
      .finally(() => setLoading(false));
  }, [period]);

  const COLS = [
    { k: 'tasks_created',          label: 'Tarefas criadas',      short: 'Criadas' },
    { k: 'tasks_concluded',        label: 'Tarefas concluídas',   short: 'Concluídas' },
    { k: 'cases_created',          label: 'Casos cadastrados',    short: 'Casos' },
    { k: 'clients_created',        label: 'Clientes cadastrados', short: 'Clientes' },
    { k: 'documents_uploaded',     label: 'Docs enviados',        short: 'Docs' },
    { k: 'propostas_created',      label: 'Propostas criadas',    short: 'Propostas' },
    { k: 'comments_made',          label: 'Comentários',          short: 'Coment.' },
    { k: 'levantamentos_created',  label: 'MLE peticionados',     short: 'MLE pet.' },
    { k: 'levantamentos_received', label: 'MLE recebidos',        short: 'MLE rec.' },
    { k: 'total',                  label: 'Total de ações',       short: 'Total' },
  ];

  const sorted = React.useMemo(() => {
    return [...users].sort((a, b) => {
      const av = a[sortKey] ?? 0, bv = b[sortKey] ?? 0;
      return sortDir === 'desc' ? bv - av : av - bv;
    });
  }, [users, sortKey, sortDir]);

  const totals = React.useMemo(() => {
    const t = {};
    COLS.forEach(c => { t[c.k] = users.reduce((s, u) => s + (u[c.k] || 0), 0); });
    return t;
  }, [users]);

  const sortBy = (k) => {
    if (sortKey === k) setSortDir(d => d === 'desc' ? 'asc' : 'desc');
    else { setSortKey(k); setSortDir('desc'); }
  };

  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
        <thead>
          <tr style={{ background: 'var(--bg-secondary)' }}>
            <th style={{ textAlign: 'left', padding: '8px 12px', fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '.05em', fontSize: 10.5, borderBottom: '1px solid var(--border)' }}>
              Colaborador
            </th>
            {COLS.map(c => (
              <th key={c.k} onClick={() => sortBy(c.k)} title={c.label}
                style={{
                  textAlign: 'center', padding: '8px 6px', fontWeight: 700,
                  color: sortKey === c.k ? 'var(--octale-navy)' : 'var(--fg-muted)',
                  textTransform: 'uppercase', letterSpacing: '.05em', fontSize: 10.5,
                  borderBottom: '1px solid var(--border)', cursor: 'pointer',
                  background: sortKey === c.k ? 'rgba(23,23,15,.04)' : undefined,
                  whiteSpace: 'nowrap',
                }}>
                {c.short} {sortKey === c.k && (sortDir === 'desc' ? '↓' : '↑')}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {loading ? (
            <tr><td colSpan={COLS.length + 1} style={{ padding: 24, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>
              <span className="spinner" style={{ width: 12, height: 12, marginRight: 6, verticalAlign: 'middle' }} /> Carregando…
            </td></tr>
          ) : sorted.length === 0 ? (
            <tr><td colSpan={COLS.length + 1} style={{ padding: 24, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>
              Sem atividade no período.
            </td></tr>
          ) : sorted.map((u, idx) => (
            <tr key={u.user_id} style={{ borderBottom: '1px solid var(--border)', background: idx % 2 === 0 ? undefined : 'rgba(0,0,0,.01)' }}>
              <td style={{ padding: '9px 12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  {/* Ranking badge */}
                  <span style={{
                    width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 10, fontWeight: 700,
                    background: idx === 0 ? '#F59E0B' : idx === 1 ? '#94A3B8' : idx === 2 ? '#CD7F32' : 'var(--bg-secondary)',
                    color: idx < 3 ? '#fff' : 'var(--fg-muted)',
                  }}>
                    {idx + 1}
                  </span>
                  <UserAvatar user={u} size={24} style={{ borderRadius: 5, fontSize: 10 }} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--octale-black)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 160 }}>
                      {u.name}
                    </div>
                    <div style={{ fontSize: 10, color: 'var(--fg-muted)', textTransform: 'capitalize' }}>{u.role?.replace('_', ' ')}</div>
                  </div>
                </div>
              </td>
              {COLS.map(c => {
                const v = u[c.k] || 0;
                const isTotal = c.k === 'total';
                const pct = totals[c.k] > 0 ? Math.round((v / totals[c.k]) * 100) : 0;
                return (
                  <td key={c.k} style={{
                    textAlign: 'center', padding: '9px 6px', position: 'relative',
                    fontWeight: isTotal ? 700 : 500,
                    color: v === 0 ? 'var(--fg-muted)' : isTotal ? 'var(--octale-navy)' : 'var(--octale-black)',
                    opacity: v === 0 ? 0.35 : 1,
                    background: sortKey === c.k ? 'rgba(23,23,15,.02)' : undefined,
                  }}>
                    {v}
                    {!isTotal && v > 0 && (
                      <div style={{
                        position: 'absolute', bottom: 0, left: '10%', right: '10%',
                        height: 2, borderRadius: 1,
                        background: 'var(--octale-navy)', opacity: 0.15 + (pct / 100) * 0.55,
                        width: `${Math.max(pct, 4)}%`,
                      }} />
                    )}
                  </td>
                );
              })}
            </tr>
          ))}
          {/* Totalizador */}
          {!loading && sorted.length > 0 && (
            <tr style={{ background: 'var(--bg-secondary)', borderTop: '2px solid var(--border)' }}>
              <td style={{ padding: '9px 12px', color: 'var(--octale-navy)', fontSize: 12, fontWeight: 700 }}>
                Total da equipe
              </td>
              {COLS.map(c => (
                <td key={c.k} style={{ textAlign: 'center', padding: '9px 6px', color: 'var(--octale-navy)', fontWeight: 700, fontSize: 12 }}>
                  {totals[c.k] || 0}
                </td>
              ))}
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
};

// ── Componente principal ──────────────────────────────────────────────────────
const GestorDashboard = ({ user }) => {
  const [period, setPeriod] = React.useState('30d');
  const [summary, setSummary] = React.useState(null);
  const [timeseries, setTimeseries] = React.useState(null);
  const [loadingKpi, setLoadingKpi] = React.useState(true);
  const [loadingChart, setLoadingChart] = React.useState(true);

  // Summary (KPIs de banco — não depende de período)
  React.useEffect(() => {
    setLoadingKpi(true);
    window.OctaleApi.dashboard.gestorSummary()
      .then(data => setSummary(data))
      .catch(() => setSummary(null))
      .finally(() => setLoadingKpi(false));
  }, []);

  // Timeseries (gráfico — depende do período)
  React.useEffect(() => {
    setLoadingChart(true);
    window.OctaleApi.dashboard.gestorTimeseries(period)
      .then(data => setTimeseries(data))
      .catch(() => setTimeseries(null))
      .finally(() => setLoadingChart(false));
  }, [period]);

  const firstName = user?.name?.split(' ')[0] || 'Gestor';
  const PERIOD_LABEL = { '7d': 'Últimos 7 dias', '30d': 'Últimos 30 dias', '90d': 'Últimos 90 dias', all: 'Todo o período' };

  // Segmentos para o donut (distribuição por tipo no período)
  const DONUT_COLORS = {
    task:         '#2563EB',
    case:         '#7C3AED',
    client:       '#059669',
    document:     '#D97706',
    proposta:     '#DC2626',
    levantamento: '#0891B2',
    subtask:      '#9333EA',
    event:        '#EA580C',
    announcement: '#6B7280',
  };
  const DONUT_LABELS = {
    task: 'Tarefas', case: 'Casos', client: 'Clientes', document: 'Documentos',
    proposta: 'Propostas', levantamento: 'MLE', subtask: 'Subtarefas',
    event: 'Eventos', announcement: 'Comunicados',
  };

  const donutSegments = React.useMemo(() => {
    if (!timeseries?.total_by_type) return [];
    return Object.entries(timeseries.total_by_type)
      .filter(([, v]) => v > 0)
      .sort(([, a], [, b]) => b - a)
      .slice(0, 9)
      .map(([type, value]) => ({
        label: DONUT_LABELS[type] || type,
        value,
        color: DONUT_COLORS[type] || '#94A3B8',
      }));
  }, [timeseries]);

  const totalActions = donutSegments.reduce((s, d) => s + d.value, 0);

  // Taxa de resolução de andamentos e publicações
  const andTreated  = summary?.andamentos?.treated || 0;
  const andPending  = summary?.andamentos?.pending || 0;
  const andTotal    = andTreated + andPending;
  const andRate     = andTotal > 0 ? Math.round((andTreated / andTotal) * 100) : null;

  const pubTreated  = summary?.publicacoes?.treated || 0;
  const pubPending  = summary?.publicacoes?.pending || 0;
  const pubTotal    = pubTreated + pubPending;
  const pubRate     = pubTotal > 0 ? Math.round((pubTreated / pubTotal) * 100) : null;

  return (
    <div className="dash">
      {/* Cabeçalho */}
      <div className="dash-head" style={{ marginBottom: 20 }}>
        <div>
          <div className="eyebrow muted">Dashboard Gestor</div>
          <h1>Visão da organização, {firstName}.</h1>
          <div className="sub">
            Acompanhe o uso da plataforma, a produtividade da equipe e os indicadores operacionais.
          </div>
        </div>
        {/* Seletor de período */}
        <div style={{ display: 'flex', gap: 4, alignSelf: 'flex-end', flexShrink: 0 }}>
          {(['7d', '30d', '90d', 'all']).map(p => (
            <button key={p} onClick={() => setPeriod(p)} style={{
              padding: '6px 12px', borderRadius: 6, fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
              border: period === p ? '1px solid var(--octale-navy)' : '1px solid var(--border)',
              background: period === p ? 'var(--octale-navy)' : 'var(--bg)',
              color: period === p ? '#fff' : 'var(--fg-muted)',
            }}>
              {p === 'all' ? 'Tudo' : p.toUpperCase()}
            </button>
          ))}
        </div>
      </div>

      {/* ── Linha 1: KPIs ao vivo (dados do banco, não dependem de período) ── */}
      <div style={{ marginBottom: 8 }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.07em', color: 'var(--fg-muted)', marginBottom: 10 }}>
          Estado atual da organização
        </div>
        <div className="kpi-row">
          <GestorKpiCard
            label="Colaboradores ativos"
            value={loadingKpi ? undefined : summary?.users?.active ?? '–'}
            sub={summary ? `${summary.users.total} cadastrados` : undefined}
            accent="#2563EB"
          />
          <GestorKpiCard
            label="Casos ativos"
            value={loadingKpi ? undefined : summary?.cases?.active ?? '–'}
            sub={summary ? `${summary.cases.total} no total` : undefined}
            accent="#7C3AED"
          />
          <GestorKpiCard
            label="Clientes"
            value={loadingKpi ? undefined : summary?.clients?.total ?? '–'}
            sub="cadastrados"
            accent="#059669"
          />
          <GestorKpiCard
            label="Processos monitorados"
            value={loadingKpi ? undefined : summary?.processes?.total ?? '–'}
            sub={summary ? `${summary.processes.active} ativos` : undefined}
            accent="#0891B2"
          />
        </div>
      </div>

      {/* ── Linha 2: KPIs de pendências ── */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.07em', color: 'var(--fg-muted)', marginBottom: 10 }}>
          Pendências e tarefas
        </div>
        <div className="kpi-row">
          <GestorKpiCard
            label="Tarefas abertas"
            value={loadingKpi ? undefined : summary?.tasks?.open ?? '–'}
            sub={summary ? `${summary.tasks.concluded} concluídas no total` : undefined}
            accent="#D97706"
            warn={summary?.tasks?.open > 30}
          />
          <GestorKpiCard
            label="Andamentos pendentes"
            value={loadingKpi ? undefined : summary?.andamentos?.pending ?? '–'}
            sub={andRate !== null ? `${andRate}% resolvidos` : andTreated > 0 ? `${andTreated} tratados` : 'nenhum tratado ainda'}
            accent={summary?.andamentos?.pending > 10 ? '#C2253E' : '#D97706'}
            warn={summary?.andamentos?.pending > 10}
          />
          <GestorKpiCard
            label="Publicações pendentes"
            value={loadingKpi ? undefined : summary?.publicacoes?.pending ?? '–'}
            sub={pubRate !== null ? `${pubRate}% resolvidas` : pubTreated > 0 ? `${pubTreated} tratadas` : 'nenhuma tratada ainda'}
            accent={summary?.publicacoes?.pending > 10 ? '#C2253E' : '#D97706'}
            warn={summary?.publicacoes?.pending > 10}
          />
          <GestorKpiCard
            label={`Ações no período (${period === 'all' ? 'geral' : period.toUpperCase()})`}
            value={loadingChart ? undefined : totalActions || 0}
            sub={timeseries ? PERIOD_LABEL[period] : undefined}
            accent="var(--octale-navy)"
          />
        </div>
      </div>

      {/* ── Gráfico de atividade + distribuição ── */}
      <div className="dash-grid" style={{ marginBottom: 24 }}>
        {/* Gráfico de barras — ocupa 2/3 */}
        <div style={{ flex: 2, minWidth: 0 }}>
          <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
            <div className="panel-head" style={{ padding: '14px 16px 12px' }}>
              <h3>Atividade diária da equipe</h3>
              <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{PERIOD_LABEL[period]}</span>
            </div>
            <div style={{ padding: '0 16px 16px' }}>
              {loadingChart
                ? <div style={{ height: 120, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>
                    <span className="spinner" style={{ width: 14, height: 14, marginRight: 8 }} /> Carregando…
                  </div>
                : <GestorBarChart days={timeseries?.days || []} />
              }
            </div>
          </div>
        </div>

        {/* Donut — ocupa 1/3 */}
        <div style={{ flex: 1, minWidth: 180 }}>
          <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
            <div className="panel-head" style={{ padding: '14px 16px 12px' }}>
              <h3>Por módulo</h3>
            </div>
            <div style={{ padding: '0 16px 16px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
              {loadingChart
                ? <div style={{ height: 130, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>
                    <span className="spinner" style={{ width: 14, height: 14, marginRight: 8 }} /> Carregando…
                  </div>
                : <>
                    <DonutChart segments={donutSegments} size={130} />
                    {/* Legenda */}
                    <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 5 }}>
                      {donutSegments.slice(0, 6).map(s => (
                        <div key={s.label} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11 }}>
                          <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color, flexShrink: 0 }} />
                          <span style={{ flex: 1, color: 'var(--fg-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.label}</span>
                          <span style={{ fontWeight: 700, color: 'var(--octale-black)', flexShrink: 0 }}>{s.value}</span>
                          <span style={{ color: 'var(--fg-muted)', fontSize: 10, flexShrink: 0 }}>
                            ({Math.round((s.value / (totalActions || 1)) * 100)}%)
                          </span>
                        </div>
                      ))}
                    </div>
                  </>
              }
            </div>
          </div>
        </div>
      </div>

      {/* ── Tabela de produtividade por usuário ── */}
      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <div className="panel-head" style={{ padding: '14px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <h3 style={{ margin: 0 }}>Produtividade por colaborador</h3>
            <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{PERIOD_LABEL[period]} · clique no cabeçalho para ordenar</span>
          </div>
        </div>
        <GestorUserTable period={period} />
      </div>
    </div>
  );
};

window.GestorDashboard = GestorDashboard;
