// ─── Rankings — equipos · vendedores · barrios ─────────────────────────────

function Rankings() {
  const [tab, setTab] = useState('equipos');
  const [periodo, setPeriodo] = useState('ytd');  // '2026-05' | '2026-04' | ... | 'trim' | 'ytd'
  const [anio, setAnio] = useState(2026);
  const [tipo, setTipo] = useState('Todos');
  const user = window.CURRENT_USER;
  const rol = user ? ROLES[user.rol] : null;
  const tabsPermitidas = rol ? rol.rankings : ['equipos','vendedores','barrios'];

  // Filtro temporal sobre el universo de cerradas
  const dataset = useMemo(() => {
    let ops = TODAS_OPS_YTD.filter(o => o.estado === 'Cerrada');
    if (tipo !== 'Todos') ops = ops.filter(o => o.tipo === tipo);
    // Períodos: mes específico ('2026-MM'), trimestre actual o YTD
    if (periodo === 'trim') ops = ops.filter(o => ['2026-03','2026-04','2026-05'].some(p => o.fecha.startsWith(p)));
    else if (periodo === 'ytd') ops = ops.filter(o => o.fecha.startsWith(String(anio)));
    else ops = ops.filter(o => o.fecha.startsWith(periodo));  // YYYY-MM
    return ops;
  }, [periodo, anio, tipo]);

  // Si el rol actual no tiene acceso al tab activo, cambiar al primero permitido
  useEffect(() => {
    if (tabsPermitidas.length === 0) return;
    if (!tabsPermitidas.includes(tab)) setTab(tabsPermitidas[0]);
  }, [user?.email]); // eslint-disable-line

  const TABS = [
    { id: 'equipos',    label: 'Equipos',    icon: I.Users },
    { id: 'vendedores', label: 'Vendedores', icon: I.Spark },
    { id: 'barrios',    label: 'Barrios',    icon: I.Map },
  ].filter(t => tabsPermitidas.includes(t.id));

  return (
    <div className="fade-in">
      <PageHeader
        crumbs={['Inicio', 'Rankings']}
        title="Rankings"
        sub="Desempeño por equipo, vendedor y barrio · operaciones cerradas"
        actions={
          <>
            <Select label="Tipo" value={tipo} onChange={setTipo} w="w-40"
              options={[
                { value: 'Todos',    label: 'Venta + Alquiler' },
                { value: 'Venta',    label: 'Sólo ventas' },
                { value: 'Alquiler', label: 'Sólo alquileres' },
              ]} />
            <Button variant="outline" size="md" icon={<I.Download size={14} />}>Exportar</Button>
          </>
        }
      />

      {/* Filtro mes/año — pills consistentes con resto del dashboard */}
      <PeriodoPills periodo={periodo} setPeriodo={setPeriodo} anio={anio} setAnio={setAnio} count={dataset.length} />

      {/* Resumen del período */}
      <div className="grid grid-cols-12 gap-4 mb-6">
        <StatCard label="Operaciones" value={dataset.length} sub="cerradas en el período" accent="#3D4F5C" />
        <StatCard label="Monto operado" value={USD_C(dataset.reduce((s,o)=>s+o.monto_usd, 0))} sub={`ticket promedio ${USD_C(Math.round(dataset.reduce((s,o)=>s+o.monto_usd,0) / (dataset.length||1)))}`} accent="#A88A47" />
        <StatCard label="m² operados"  value={`${NUM(dataset.reduce((s,o)=>s+o.m2, 0))} m²`} sub={`${dataset.filter(o=>o.tipo==='Venta').length} ventas · ${dataset.filter(o=>o.tipo==='Alquiler').length} alquileres`} accent="#3F8A6B" />
        <StatCard label="Vendedor top" value={topVendedorLabel(dataset)} sub="por monto operado" accent="#C9A961" />
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 mb-5 border-b border-slate-100">
        {TABS.map(t => {
          const Ico = t.icon;
          const active = tab === t.id;
          return (
            <button key={t.id} onClick={() => setTab(t.id)}
              className={`relative inline-flex items-center gap-2 px-4 py-3 text-[12.5px] font-medium transition-colors ${active ? 'text-ink' : 'text-slate-500 hover:text-ink'}`}>
              <Ico size={14} sw={1.6} />
              {t.label}
              {active && <span className="absolute left-2 right-2 -bottom-px h-0.5 bg-gold" />}
            </button>
          );
        })}
      </div>

      {tab === 'equipos'    && <RankingEquipos   data={dataset} />}
      {tab === 'vendedores' && <RankingVendedores data={dataset} />}
      {tab === 'barrios'    && <RankingBarrios   data={dataset} />}
    </div>
  );
}

function StatCard({ label, value, sub, accent }) {
  return (
    <div className="col-span-3 bg-white rounded-md border border-slate-100 shadow-card p-5">
      <div className="flex items-start justify-between">
        <div className="text-[10px] uppercase tracking-[0.14em] text-slate-500 font-medium">{label}</div>
        {accent && <span className="w-1.5 h-1.5 rounded-full" style={{ background: accent }} />}
      </div>
      <div className="font-mono text-[24px] text-ink leading-none mt-3 truncate">{value}</div>
      {sub && <div className="text-[11.5px] text-slate-500 mt-1.5 truncate">{sub}</div>}
    </div>
  );
}

function topVendedorLabel(ops) {
  const m = {};
  ops.forEach(o => o.brokers.forEach(b => { m[b] = (m[b] || 0) + o.monto_usd / o.brokers.length; }));
  const sorted = Object.entries(m).sort((a, b) => b[1] - a[1]);
  if (sorted.length === 0) return '—';
  return BROKERS[sorted[0][0]]?.nombre.split(' ')[0] || sorted[0][0];
}

// ── RANKING DE EQUIPOS ────────────────────────────────────────────────────
function RankingEquipos({ data }) {
  const rows = Object.values(TEAMS).map(t => {
    const ops = data.filter(o => o.team === t.id);
    return {
      ...t,
      ops: ops.length,
      monto: ops.reduce((s, o) => s + o.monto_usd, 0),
      m2: ops.reduce((s, o) => s + o.m2, 0),
      ventas: ops.filter(o => o.tipo === 'Venta').length,
      alquileres: ops.filter(o => o.tipo === 'Alquiler').length,
    };
  }).sort((a, b) => b.monto - a.monto);

  const maxMonto = Math.max(...rows.map(r => r.monto)) || 1;

  return (
    <div className="grid grid-cols-12 gap-4">
      {/* Podio · cards grandes */}
      <div className="col-span-12 grid grid-cols-2 gap-4">
        {rows.map((r, i) => (
          <div key={r.id} className="relative bg-white rounded-md border border-slate-100 shadow-card p-6 overflow-hidden">
            {/* Banda lateral con color del equipo */}
            <div className="absolute top-0 left-0 bottom-0 w-1" style={{ background: r.color }} />
            <div className="flex items-start justify-between">
              <div>
                <div className="flex items-center gap-3">
                  <span className="font-serif text-[44px] leading-none" style={{ color: i === 0 ? '#C9A961' : '#B5BFC7' }}>#{i + 1}</span>
                  <div>
                    <h3 className="font-serif text-[24px] text-ink leading-tight">{r.nombre}</h3>
                    <div className="text-[11.5px] text-slate-500 mt-0.5">{r.zona}</div>
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-2 text-[11px] text-slate-500">
                <span className="uppercase tracking-[0.12em]">Lider</span>
                <BrokerChip code={r.lider} size={26} />
              </div>
            </div>

            <div className="grid grid-cols-3 gap-4 mt-6 pt-5 border-t border-slate-100">
              <div>
                <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">Monto</div>
                <div className="font-mono text-[18px] text-ink mt-1">{USD_C(r.monto)}</div>
              </div>
              <div>
                <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">Operaciones</div>
                <div className="font-mono text-[18px] text-ink mt-1">{r.ops}</div>
                <div className="text-[10px] text-slate-500 mt-0.5">{r.ventas} v · {r.alquileres} a</div>
              </div>
              <div>
                <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">m² operados</div>
                <div className="font-mono text-[18px] text-ink mt-1">{NUM(r.m2)}</div>
              </div>
            </div>

            <div className="mt-4 h-1.5 bg-slate-50 rounded-full overflow-hidden">
              <div className="h-full" style={{ width: `${r.monto / maxMonto * 100}%`, background: r.color }} />
            </div>

            {/* Mini composición vendedores del equipo */}
            <div className="mt-4 flex items-center justify-between">
              <div className="flex -space-x-2">
                {Object.entries(BROKERS).filter(([_, b]) => b.team === r.id).map(([code]) => (
                  <BrokerChip key={code} code={code} size={26} />
                ))}
              </div>
              <button className="text-[11.5px] text-slate-500 hover:text-ink inline-flex items-center gap-1">
                Ver detalle <I.Arrow size={11} />
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Tabla de detalle */}
      <Card title="Composición por equipo" className="col-span-12" pad="p-0">
        <table className="w-full text-[12.5px]">
          <thead className="bg-slate-50/60">
            <tr className="text-[10px] uppercase tracking-[0.1em] text-slate-500 text-left">
              <th className="font-medium py-3 px-5">#</th>
              <th className="font-medium">Equipo</th>
              <th className="font-medium">Líder</th>
              <th className="font-medium text-right">Operaciones</th>
              <th className="font-medium text-right">m²</th>
              <th className="font-medium text-right">Monto</th>
              <th className="font-medium text-right pr-5">Ticket prom.</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={r.id} className="border-t border-slate-100 tr-hover">
                <td className="py-3.5 px-5 font-serif text-[16px]" style={{ color: i === 0 ? '#C9A961' : '#B5BFC7' }}>{i + 1}</td>
                <td>
                  <div className="flex items-center gap-2.5">
                    <span className="w-2 h-2 rounded-full" style={{ background: r.color }} />
                    <span className="text-ink font-medium">{r.nombre}</span>
                    <span className="text-slate-400 text-[11px]">{r.zona}</span>
                  </div>
                </td>
                <td><div className="flex items-center gap-2"><BrokerChip code={r.lider} size={20} /><span className="text-slate-600 text-[12px]">{BROKERS[r.lider].nombre}</span></div></td>
                <td className="text-right font-mono">{r.ops} <span className="text-slate-400 text-[10px]">({r.ventas}/{r.alquileres})</span></td>
                <td className="text-right font-mono text-slate-700">{NUM(r.m2)}</td>
                <td className="text-right font-mono text-ink">{USD_C(r.monto)}</td>
                <td className="text-right font-mono text-slate-600 pr-5">{r.ops > 0 ? USD_C(Math.round(r.monto / r.ops)) : '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ── RANKING DE VENDEDORES ─────────────────────────────────────────────────
function RankingVendedores({ data }) {
  const rows = Object.entries(BROKERS).map(([code, b]) => {
    const ops = data.filter(o => o.brokers.includes(code));
    const share = (o) => 1 / o.brokers.length;
    return {
      code,
      nombre: b.nombre,
      color: b.color,
      team: b.team,
      ops: ops.length,
      monto: ops.reduce((s, o) => s + o.monto_usd * share(o), 0),
      m2: ops.reduce((s, o) => s + o.m2 * share(o), 0),
      ventas: ops.filter(o => o.tipo === 'Venta').length,
      alquileres: ops.filter(o => o.tipo === 'Alquiler').length,
    };
  }).sort((a, b) => b.monto - a.monto);

  const maxMonto = Math.max(...rows.map(r => r.monto)) || 1;
  const podio = rows.slice(0, 3);
  const resto = rows.slice(3);

  return (
    <div className="grid grid-cols-12 gap-4">
      {/* Podio · 1º central elevado */}
      <div className="col-span-12 bg-white rounded-md border border-slate-100 shadow-card p-8">
        <div className="text-[10px] uppercase tracking-[0.14em] text-slate-500 font-medium mb-6">Podio · top 3 vendedores</div>
        <div className="grid grid-cols-3 gap-4 items-end max-w-[760px] mx-auto">
          {[1, 0, 2].map((pos) => {
            const r = podio[pos];
            if (!r) return <div key={pos} />;
            const heights = ['h-32', 'h-44', 'h-24'];
            const colors = ['#B5BFC7', '#C9A961', '#A88A47'];
            return (
              <div key={r.code} className="flex flex-col items-center">
                <div className="mb-3">
                  <BrokerChip code={r.code} size={52} />
                </div>
                <div className="font-serif text-[18px] text-ink text-center leading-tight">{r.nombre}</div>
                <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400 mt-0.5">{TEAMS[r.team]?.nombre}</div>
                <div className="font-mono text-[18px] text-ink mt-2">{USD_C(r.monto)}</div>
                <div className="text-[10.5px] text-slate-500 mt-0.5">{r.ops} ops · {NUM(Math.round(r.m2))} m²</div>
                <div className={`mt-3 w-full rounded-t-md flex items-start justify-center pt-2 ${heights[pos]}`} style={{ background: colors[pos] }}>
                  <span className="font-serif text-[28px] text-white">{pos + 1}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Detalle completo */}
      <Card title="Detalle de vendedores" className="col-span-12" pad="p-0">
        <table className="w-full text-[12.5px]">
          <thead className="bg-slate-50/60">
            <tr className="text-[10px] uppercase tracking-[0.1em] text-slate-500 text-left">
              <th className="font-medium py-3 px-5">#</th>
              <th className="font-medium">Vendedor</th>
              <th className="font-medium">Equipo</th>
              <th className="font-medium">Ops</th>
              <th className="font-medium text-right">Ventas</th>
              <th className="font-medium text-right">Alquileres</th>
              <th className="font-medium text-right">m²</th>
              <th className="font-medium text-right pr-5">Monto atribuido</th>
              <th className="font-medium pr-5"></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={r.code} className="border-t border-slate-100 tr-hover">
                <td className="py-3.5 px-5 font-serif text-[16px]" style={{ color: i === 0 ? '#C9A961' : i < 3 ? '#A88A47' : '#B5BFC7' }}>{i + 1}</td>
                <td>
                  <div className="flex items-center gap-2.5">
                    <BrokerChip code={r.code} />
                    <span className="text-ink font-medium">{r.nombre}</span>
                  </div>
                </td>
                <td>
                  <span className="inline-flex items-center gap-1.5 text-[11.5px] text-slate-600">
                    <span className="w-1.5 h-1.5 rounded-full" style={{ background: TEAMS[r.team]?.color }} />
                    {TEAMS[r.team]?.nombre}
                  </span>
                </td>
                <td className="text-slate-700 font-mono">{r.ops}</td>
                <td className="text-right text-slate-600 font-mono">{r.ventas}</td>
                <td className="text-right text-slate-600 font-mono">{r.alquileres}</td>
                <td className="text-right text-slate-700 font-mono">{NUM(Math.round(r.m2))}</td>
                <td className="text-right pr-5">
                  <div className="font-mono text-ink">{USD_C(r.monto)}</div>
                  <div className="mt-1 h-1 bg-slate-50 rounded-full overflow-hidden ml-auto" style={{ maxWidth: 120 }}>
                    <div className="h-full bg-gold" style={{ width: `${r.monto / maxMonto * 100}%` }} />
                  </div>
                </td>
                <td className="pr-5 text-slate-400"><I.Chevron size={14} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ── RANKING DE BARRIOS ────────────────────────────────────────────────────
function RankingBarrios({ data }) {
  // Agrupar por barrio
  const map = {};
  data.forEach(o => {
    if (!map[o.barrio]) map[o.barrio] = { barrio: o.barrio, ops: 0, monto: 0, m2: 0, ventas: 0, alquileres: 0, canales: {} };
    const r = map[o.barrio];
    r.ops += 1;
    r.monto += o.monto_usd;
    r.m2 += o.m2;
    if (o.tipo === 'Venta') r.ventas += 1; else r.alquileres += 1;
    r.canales[o.canal] = (r.canales[o.canal] || 0) + 1;
  });
  const rows = Object.values(map).sort((a, b) => b.monto - a.monto);
  const maxMonto = Math.max(...rows.map(r => r.monto)) || 1;
  const maxM2    = Math.max(...rows.map(r => r.m2))    || 1;
  const totalOps = rows.reduce((s, r) => s + r.ops, 0) || 1;

  // Paleta por posición — degradé cálido
  const colors = ['#C9A961', '#A88A47', '#677A88', '#3D4F5C', '#B5BFC7', '#8A9AA5'];

  return (
    <div className="grid grid-cols-12 gap-4">
      {/* Top barrio · destacado */}
      {rows[0] && (
        <div className="col-span-4 bg-white rounded-md border border-slate-100 shadow-card p-6 relative overflow-hidden">
          <div className="absolute -right-8 -top-8 w-40 h-40 rounded-full" style={{ background: 'radial-gradient(circle, rgba(201,169,97,0.18), transparent 70%)' }} />
          <div className="relative">
            <div className="text-[10px] uppercase tracking-[0.14em] text-slate-500 font-medium">Barrio del año</div>
            <div className="font-serif text-[42px] text-ink leading-none mt-3">{rows[0].barrio}</div>
            <div className="text-[12px] text-slate-500 mt-1">{rows[0].ops} operaciones · {Math.round(rows[0].ops / totalOps * 100)}% del volumen</div>

            <div className="mt-6 pt-5 border-t border-slate-100 space-y-3">
              <div className="flex items-baseline justify-between">
                <span className="text-[11px] text-slate-500">Monto operado</span>
                <span className="font-mono text-ink">{USD_C(rows[0].monto)}</span>
              </div>
              <div className="flex items-baseline justify-between">
                <span className="text-[11px] text-slate-500">m² operados</span>
                <span className="font-mono text-ink">{NUM(rows[0].m2)} m²</span>
              </div>
              <div className="flex items-baseline justify-between">
                <span className="text-[11px] text-slate-500">Ticket promedio</span>
                <span className="font-mono text-ink">{USD_C(Math.round(rows[0].monto / rows[0].ops))}</span>
              </div>
              <div className="flex items-baseline justify-between">
                <span className="text-[11px] text-slate-500">Mix</span>
                <span className="font-mono text-slate-700 text-[12px]">{rows[0].ventas} v / {rows[0].alquileres} a</span>
              </div>
            </div>

            <div className="mt-5 pt-4 border-t border-slate-100">
              <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400 mb-2">Canales activos</div>
              <div className="flex flex-wrap gap-1.5">
                {Object.entries(rows[0].canales).sort((a,b) => b[1] - a[1]).map(([id, n]) => (
                  <span key={id} className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-medium"
                    style={{ background: CANAL_BY_ID[id].color + '15', color: CANAL_BY_ID[id].color }}>
                    {CANAL_BY_ID[id].short} · {n}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Lista barrios */}
      <Card title="Ranking completo por barrio" className="col-span-8" pad="p-0">
        <div className="px-5 pt-5 pb-1 text-[10px] uppercase tracking-[0.12em] text-slate-400">por monto operado · YTD</div>
        <ul className="px-2 pb-2">
          {rows.map((r, i) => (
            <li key={r.barrio} className="px-3 py-3 flex items-center gap-4 rounded hover:bg-canvas">
              <span className="font-serif text-[20px] w-7 text-center" style={{ color: colors[i] || '#B5BFC7' }}>{i + 1}</span>
              <div className="flex-1 min-w-0">
                <div className="flex items-baseline justify-between mb-1.5">
                  <span className="font-medium text-ink text-[13.5px]">{r.barrio}</span>
                  <span className="font-mono text-ink text-[13px]">{USD_C(r.monto)}</span>
                </div>
                <div className="h-1.5 bg-slate-50 rounded-full overflow-hidden">
                  <div className="h-full rounded-full" style={{ width: `${r.monto / maxMonto * 100}%`, background: colors[i] || '#B5BFC7' }} />
                </div>
                <div className="flex items-center justify-between mt-1.5 text-[10.5px] text-slate-500">
                  <span>{r.ops} ops · <span className="font-mono">{NUM(r.m2)} m²</span></span>
                  <span className="font-mono">{r.ventas} v / {r.alquileres} a</span>
                </div>
              </div>
            </li>
          ))}
        </ul>
      </Card>

      {/* Mapa de calor por m² */}
      <Card title="Heatmap · m² operados" className="col-span-12">
        <div className="text-[11px] text-slate-500 mb-3">Visualización proporcional — el tamaño del bloque representa los m² operados.</div>
        <div className="flex flex-wrap gap-2">
          {rows.map((r, i) => {
            const size = 80 + (r.m2 / maxM2) * 200;
            return (
              <div key={r.barrio}
                className="rounded-md p-4 flex flex-col justify-between text-white relative overflow-hidden cursor-pointer transition-transform hover:-translate-y-0.5"
                style={{
                  width: size, height: size * 0.7,
                  background: `linear-gradient(135deg, ${colors[i] || '#677A88'} 0%, ${colors[i] || '#677A88'}cc 100%)`,
                }}>
                <div className="font-serif text-[20px] leading-tight">{r.barrio}</div>
                <div>
                  <div className="font-mono text-[18px] leading-none">{NUM(r.m2)}</div>
                  <div className="text-[10px] uppercase tracking-[0.1em] opacity-80 mt-0.5">m² operados</div>
                </div>
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}

window.Rankings = Rankings;

// ── Filtro de mes/año + agrupaciones rápidas ───────────────────────────────
// Pills consistentes con el resto del dashboard (toggle "6 meses").
// Estructura: [año] [Ene Feb Mar Abr May …] · [Q2] [YTD]
function PeriodoPills({ periodo, setPeriodo, anio, setAnio, count }) {
  const MESES = [
    { id: `${anio}-01`, label: 'Ene' },
    { id: `${anio}-02`, label: 'Feb' },
    { id: `${anio}-03`, label: 'Mar' },
    { id: `${anio}-04`, label: 'Abr' },
    { id: `${anio}-05`, label: 'May' },
    { id: `${anio}-06`, label: 'Jun' },
    { id: `${anio}-07`, label: 'Jul' },
    { id: `${anio}-08`, label: 'Ago' },
    { id: `${anio}-09`, label: 'Sep' },
    { id: `${anio}-10`, label: 'Oct' },
    { id: `${anio}-11`, label: 'Nov' },
    { id: `${anio}-12`, label: 'Dic' },
  ];
  const MES_ACTUAL = 5; // mayo 2026 — futuras quedan deshabilitadas
  const ANIOS = [2025, 2026];

  const labelActual =
    periodo === 'ytd'  ? `Año ${anio}` :
    periodo === 'trim' ? `Q2 ${anio}` :
    (() => {
      const m = MESES.find(x => x.id === periodo);
      return m ? `${m.label} ${anio}` : periodo;
    })();

  return (
    <div className="mb-6 bg-white border border-slate-100 rounded-md shadow-card px-4 py-3 flex items-center gap-3 flex-wrap">
      {/* Año */}
      <div className="inline-flex items-center bg-slate-50 rounded-full p-0.5 text-[11px] font-medium">
        {ANIOS.map(a => (
          <button key={a} onClick={() => setAnio(a)}
            className={`px-2.5 py-1 rounded-full transition-colors font-mono ${anio === a ? 'bg-white text-ink shadow-card' : 'text-slate-500 hover:text-ink'}`}>
            {a}
          </button>
        ))}
      </div>

      <div className="h-6 w-px bg-slate-100" />

      {/* Meses */}
      <div className="flex items-center gap-1 flex-wrap">
        {MESES.map((m, i) => {
          const futuro = anio === 2026 && (i + 1) > MES_ACTUAL;
          const active = periodo === m.id;
          return (
            <button key={m.id}
              disabled={futuro}
              onClick={() => setPeriodo(m.id)}
              className={`text-[11.5px] px-2.5 py-1 rounded-full border transition-colors ${
                active ? 'bg-slate-700 border-slate-700 text-white' :
                futuro ? 'bg-white border-slate-100 text-slate-300 cursor-not-allowed' :
                         'bg-white border-slate-200 text-slate-700 hover:border-slate-300'
              }`}>
              {m.label}
            </button>
          );
        })}
      </div>

      <div className="h-6 w-px bg-slate-100" />

      {/* Agrupaciones */}
      <div className="flex items-center gap-1">
        <FilterPill label="Q2 (Mar-May)" active={periodo === 'trim'} onClick={() => setPeriodo('trim')} />
        <FilterPill label="Año a la fecha" active={periodo === 'ytd'} onClick={() => setPeriodo('ytd')} />
      </div>

      <div className="flex-1" />

      <div className="text-[11px] text-slate-500">
        <span className="text-slate-400">Período:</span> <span className="font-medium text-ink">{labelActual}</span>
        <span className="text-slate-300 mx-1.5">·</span>
        <span className="font-mono text-slate-600">{count} ops</span>
      </div>
    </div>
  );
}
