import { Icon } from "@iconify/react";
import { useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import styled from "styled-components";
import { getDashboardHolding } from "../../../api/suscripciones.service";
import { UserAuth } from "../../../context/AuthContent";
import { sanitizeCell } from "../../_standards";
import { hoyISO } from "../../../utils/fecha";

const ESTADO_COLORS = {
  Activo: "#10b981",
  EnGracia: "#f59e0b",
  Expirado: "#ef4444",
  Cancelado: "#6b7280",
  Pausado: "#8b5cf6",
  "Sin estado": "#374151",
};
const ESTADO_LABELS = {
  Activo: "Activas",
  EnGracia: "En Gracia",
  Expirado: "Expiradas",
  Cancelado: "Canceladas",
  Pausado: "Pausadas",
};

const fmtGs = (v) =>
  v != null ? `${Number(v).toLocaleString("es-PY")} Gs.` : "0 Gs.";
const fmtNum = (v) => (v != null ? Number(v).toLocaleString("es-PY") : "0");

export function DashboardEjecutivo() {
  const { user } = UserAuth();
  const empresaId = user?.empresa?.id;

  const {
    data: resp,
    isLoading,
    error,
  } = useQuery({
    queryKey: ["dashboard-holding", empresaId],
    queryFn: () => getDashboardHolding(empresaId),
    enabled: !!empresaId,
    staleTime: 2 * 60 * 1000,
  });

  const d = resp?.data;
  const [filtroEstado, setFiltroEstado] = useState("todos");
  const [filtroPlan, setFiltroPlan] = useState("todos");
  const [sortKey, setSortKey] = useState("empresa_nombre");
  const [sortDir, setSortDir] = useState("asc");
  const [searchTable, setSearchTable] = useState("");

  const suscFiltradas = useMemo(() => {
    if (!d?.suscripciones) return [];
    let list = [...d.suscripciones];
    if (filtroEstado !== "todos")
      list = list.filter((s) => s.estado === filtroEstado);
    if (filtroPlan !== "todos")
      list = list.filter((s) => s.plan_nombre === filtroPlan);
    if (searchTable.trim()) {
      const q = searchTable.toLowerCase();
      list = list.filter(
        (s) =>
          s.empresa_nombre?.toLowerCase().includes(q) ||
          s.empresa_ruc?.toLowerCase().includes(q) ||
          s.plan_nombre?.toLowerCase().includes(q),
      );
    }
    list.sort((a, b) => {
      let va = a[sortKey],
        vb = b[sortKey];
      if (typeof va === "number" && typeof vb === "number")
        return sortDir === "asc" ? va - vb : vb - va;
      va = String(va ?? "");
      vb = String(vb ?? "");
      return sortDir === "asc" ? va.localeCompare(vb) : vb.localeCompare(va);
    });
    return list;
  }, [
    d?.suscripciones,
    filtroEstado,
    filtroPlan,
    sortKey,
    sortDir,
    searchTable,
  ]);

  const planesUnicos = useMemo(() => {
    if (!d?.suscripciones) return [];
    return [...new Set(d.suscripciones.map((s) => s.plan_nombre))]
      .filter(Boolean)
      .sort();
  }, [d?.suscripciones]);

  const handleSort = (key) => {
    if (sortKey === key) setSortDir((p) => (p === "asc" ? "desc" : "asc"));
    else {
      setSortKey(key);
      setSortDir("asc");
    }
  };

  const exportCSV = () => {
    if (!suscFiltradas.length) return;
    const headers = [
      "Empresa",
      "RUC",
      "Tipo",
      "Plan",
      "Estado",
      "Costo Mensual",
      "Próx. Cobro",
      "Días Restantes",
      "Override",
    ];
    const rows = suscFiltradas.map((s) => [
      s.empresa_nombre,
      s.empresa_ruc,
      s.empresa_tipo,
      s.plan_nombre,
      s.estado,
      s.costo_mensual,
      s.fecha_prox_cobro || "",
      s.dias_restantes ?? "",
      s.tiene_override ? "Sí" : "No",
    ]);
    const csv = [headers, ...rows].map((r) => r.map(sanitizeCell).join(",")).join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `suscripciones-holding-${hoyISO()}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  if (isLoading)
    return (
      <Container>
        <LoadingBox>
          <Icon icon="lucide:loader-2" className="animate-spin" />
          <span>Cargando dashboard...</span>
        </LoadingBox>
      </Container>
    );
  if (error || !d)
    return (
      <Container>
        <ErrorBox>
          <Icon icon="lucide:alert-circle" />
          <span>Error al cargar el dashboard ejecutivo</span>
        </ErrorBox>
      </Container>
    );

  const k = d.kpis;

  return (
    <Container>
      <SectionTitle>
        <Icon icon="lucide:activity" />
        Indicadores Clave
      </SectionTitle>
      <KpiGrid>
        <KpiCard $accent="#10b981">
          <KpiIcon $color="#10b981">
            <Icon icon="lucide:trending-up" />
          </KpiIcon>
          <KpiBody>
            <KpiValue>{fmtGs(k.mrr)}</KpiValue>
            <KpiLabel>Ingreso Recurrente Mensual (MRR)</KpiLabel>
          </KpiBody>
        </KpiCard>
        <KpiCard $accent="#3b82f6">
          <KpiIcon $color="#3b82f6">
            <Icon icon="lucide:building-2" />
          </KpiIcon>
          <KpiBody>
            <KpiValue>
              {fmtNum(k.empresas_activas)}{" "}
              <KpiSub>/ {fmtNum(k.empresas_total)}</KpiSub>
            </KpiValue>
            <KpiLabel>Empresas Activas / Total</KpiLabel>
          </KpiBody>
        </KpiCard>
        <KpiCard $accent="#f88533">
          <KpiIcon $color="#f88533">
            <Icon icon="lucide:credit-card" />
          </KpiIcon>
          <KpiBody>
            <KpiValue>
              {fmtNum(k.suscripciones_activas)}
              {k.suscripciones_en_gracia > 0 && (
                <KpiSub $warn> +{k.suscripciones_en_gracia} en gracia</KpiSub>
              )}
            </KpiValue>
            <KpiLabel>Suscripciones Activas</KpiLabel>
          </KpiBody>
        </KpiCard>
        <KpiCard $accent="#ef4444">
          <KpiIcon $color="#ef4444">
            <Icon icon="lucide:alert-triangle" />
          </KpiIcon>
          <KpiBody>
            <KpiValue>
              {fmtNum(k.cobros_vencidos)}
              {k.cobros_vencidos > 0 && (
                <KpiSub $warn> ({fmtGs(k.cobros_vencidos_monto)})</KpiSub>
              )}
            </KpiValue>
            <KpiLabel>Cobros Vencidos</KpiLabel>
          </KpiBody>
        </KpiCard>
        <KpiCard $accent="#8b5cf6">
          <KpiIcon $color="#8b5cf6">
            <Icon icon="lucide:file-check" />
          </KpiIcon>
          <KpiBody>
            <KpiValue>
              {fmtNum(k.comprobantes_pendientes)}
              {k.comprobantes_pendientes > 0 && (
                <KpiSub> ({fmtGs(k.comprobantes_pendientes_monto)})</KpiSub>
              )}
            </KpiValue>
            <KpiLabel>Comprobantes Pendientes</KpiLabel>
          </KpiBody>
        </KpiCard>
        <KpiCard $accent="#f59e0b">
          <KpiIcon $color="#f59e0b">
            <Icon icon="lucide:percent" />
          </KpiIcon>
          <KpiBody>
            <KpiValue>{k.churn_rate}%</KpiValue>
            <KpiLabel>Churn Rate (este mes)</KpiLabel>
          </KpiBody>
        </KpiCard>
      </KpiGrid>

      <TwoColGrid>
        <Panel>
          <PanelTitle>
            <Icon icon="lucide:pie-chart" />
            Estado de Suscripciones
          </PanelTitle>
          <BarList>
            {Object.entries(d.estados_suscripcion || {}).map(
              ([estado, count]) => {
                const total = d.suscripciones?.length || 1;
                const pct = Math.round((count / total) * 100);
                const color = ESTADO_COLORS[estado] || "#6b7280";
                return (
                  <BarItem key={estado}>
                    <BarLabel>
                      <BarDot $color={color} />
                      {ESTADO_LABELS[estado] || estado}
                    </BarLabel>
                    <BarRight>
                      <BarTrack>
                        <BarFill $pct={pct} $color={color} />
                      </BarTrack>
                      <BarCount>
                        {count} ({pct}%)
                      </BarCount>
                    </BarRight>
                  </BarItem>
                );
              },
            )}
          </BarList>
        </Panel>
        <Panel>
          <PanelTitle>
            <Icon icon="lucide:layers" />
            Distribución por Plan
          </PanelTitle>
          <BarList>
            {(d.distribucion_planes || []).map((p, i) => {
              const maxCount = d.distribucion_planes?.[0]?.count || 1;
              const pct = Math.round((p.count / maxCount) * 100);
              const colors = [
                "#f88533",
                "#3b82f6",
                "#10b981",
                "#8b5cf6",
                "#ef4444",
                "#f59e0b",
              ];
              return (
                <BarItem key={p.plan_id}>
                  <BarLabel>{p.plan_nombre}</BarLabel>
                  <BarRight>
                    <BarTrack>
                      <BarFill $pct={pct} $color={colors[i % colors.length]} />
                    </BarTrack>
                    <BarCount>
                      {p.count} — {fmtGs(p.mrr)}
                    </BarCount>
                  </BarRight>
                </BarItem>
              );
            })}
            {(!d.distribucion_planes || d.distribucion_planes.length === 0) && (
              <EmptyText>Sin datos de planes</EmptyText>
            )}
          </BarList>
        </Panel>
      </TwoColGrid>

      <SectionTitle>
        <Icon icon="lucide:calendar-clock" />
        Flujo de Caja — Próximos 3 Meses
      </SectionTitle>
      <FlujoCajaGrid>
        {(d.flujo_caja || []).map((fc) => (
          <FlujoCard key={fc.mes}>
            <FlujoMes>{fc.mes}</FlujoMes>
            <FlujoMonto>{fmtGs(fc.monto)}</FlujoMonto>
            <FlujoCobros>{fc.count} cobros programados</FlujoCobros>
          </FlujoCard>
        ))}
        {k.cobros_vencidos > 0 && (
          <FlujoCard $vencido>
            <FlujoMes>Vencidos</FlujoMes>
            <FlujoMonto>{fmtGs(k.cobros_vencidos_monto)}</FlujoMonto>
            <FlujoCobros>{k.cobros_vencidos} cobros atrasados</FlujoCobros>
          </FlujoCard>
        )}
        {(!d.flujo_caja || d.flujo_caja.length === 0) &&
          k.cobros_vencidos === 0 && (
            <EmptyText>Sin cobros programados</EmptyText>
          )}
      </FlujoCajaGrid>

      <TwoColGrid>
        <Panel>
          <PanelTitle>
            <Icon icon="lucide:receipt" />
            Comprobantes de Pago
          </PanelTitle>
          <FinGrid>
            <FinItem $color="#f59e0b">
              <FinLabel>Pendientes</FinLabel>
              <FinCount>{d.comprobantes?.pendientes?.count ?? 0}</FinCount>
              <FinMonto>{fmtGs(d.comprobantes?.pendientes?.monto)}</FinMonto>
            </FinItem>
            <FinItem $color="#10b981">
              <FinLabel>Aprobados</FinLabel>
              <FinCount>{d.comprobantes?.aprobados?.count ?? 0}</FinCount>
              <FinMonto>{fmtGs(d.comprobantes?.aprobados?.monto)}</FinMonto>
            </FinItem>
            <FinItem $color="#ef4444">
              <FinLabel>Rechazados</FinLabel>
              <FinCount>{d.comprobantes?.rechazados?.count ?? 0}</FinCount>
              <FinMonto>{fmtGs(d.comprobantes?.rechazados?.monto)}</FinMonto>
            </FinItem>
          </FinGrid>
        </Panel>
        <Panel>
          <PanelTitle>
            <Icon icon="lucide:hand-coins" />
            Comisiones
          </PanelTitle>
          <FinGrid>
            <FinItem $color="#f59e0b">
              <FinLabel>Pendientes</FinLabel>
              <FinCount>{d.comisiones?.pendientes?.count ?? 0}</FinCount>
              <FinMonto>{fmtGs(d.comisiones?.pendientes?.monto)}</FinMonto>
            </FinItem>
            <FinItem $color="#10b981">
              <FinLabel>Pagadas</FinLabel>
              <FinCount>{d.comisiones?.pagadas?.count ?? 0}</FinCount>
              <FinMonto>{fmtGs(d.comisiones?.pagadas?.monto)}</FinMonto>
            </FinItem>
          </FinGrid>
        </Panel>
      </TwoColGrid>

      <SectionTitle>
        <Icon icon="lucide:table" />
        Suscripciones de la Red
        <TableActions>
          <ExportBtn onClick={exportCSV} title="Exportar CSV">
            <Icon icon="lucide:download" />
            CSV
          </ExportBtn>
        </TableActions>
      </SectionTitle>
      <TableControls>
        <TableSearch>
          <Icon icon="lucide:search" />
          <input
            placeholder="Buscar empresa, RUC o plan..."
            value={searchTable}
            onChange={(e) => setSearchTable(e.target.value)}
          />
        </TableSearch>
        <TableFilters>
          <select
            value={filtroEstado}
            onChange={(e) => setFiltroEstado(e.target.value)}
          >
            <option value="todos">Todos los estados</option>
            {Object.entries(ESTADO_LABELS).map(([k2, v]) => (
              <option key={k2} value={k2}>
                {v}
              </option>
            ))}
          </select>
          <select
            value={filtroPlan}
            onChange={(e) => setFiltroPlan(e.target.value)}
          >
            <option value="todos">Todos los planes</option>
            {planesUnicos.map((p) => (
              <option key={p} value={p}>
                {p}
              </option>
            ))}
          </select>
        </TableFilters>
      </TableControls>
      <TableWrap>
        <STable>
          <thead>
            <tr>
              <STh onClick={() => handleSort("empresa_nombre")} $sort>
                Empresa{" "}
                {sortKey === "empresa_nombre" &&
                  (sortDir === "asc" ? "↑" : "↓")}
              </STh>
              <STh onClick={() => handleSort("plan_nombre")} $sort>
                Plan{" "}
                {sortKey === "plan_nombre" && (sortDir === "asc" ? "↑" : "↓")}
              </STh>
              <STh onClick={() => handleSort("estado")} $sort>
                Estado {sortKey === "estado" && (sortDir === "asc" ? "↑" : "↓")}
              </STh>
              <STh onClick={() => handleSort("costo_mensual")} $sort $right>
                Costo Mensual{" "}
                {sortKey === "costo_mensual" && (sortDir === "asc" ? "↑" : "↓")}
              </STh>
              <STh onClick={() => handleSort("fecha_prox_cobro")} $sort>
                Próx. Cobro{" "}
                {sortKey === "fecha_prox_cobro" &&
                  (sortDir === "asc" ? "↑" : "↓")}
              </STh>
              <STh onClick={() => handleSort("dias_restantes")} $sort $right>
                Días Rest.{" "}
                {sortKey === "dias_restantes" &&
                  (sortDir === "asc" ? "↑" : "↓")}
              </STh>
            </tr>
          </thead>
          <tbody>
            {suscFiltradas.map((s) => (
              <STr key={s.suscripcion_id}>
                <STd>
                  <EmpCell>
                    <span>{s.empresa_nombre}</span>
                    <EmpRuc>{s.empresa_ruc}</EmpRuc>
                  </EmpCell>
                </STd>
                <STd>
                  {s.plan_nombre}
                  {s.tiene_override && (
                    <OvChip title="Override activo">⚡</OvChip>
                  )}
                </STd>
                <STd>
                  <EstBadge $color={ESTADO_COLORS[s.estado] || "#6b7280"}>
                    {ESTADO_LABELS[s.estado] || s.estado}
                  </EstBadge>
                </STd>
                <STd $right $mono>
                  {fmtGs(s.costo_mensual)}
                </STd>
                <STd>{s.fecha_prox_cobro || "—"}</STd>
                <STd $right>
                  <DiasChip $dias={s.dias_restantes}>
                    {s.dias_restantes != null ? s.dias_restantes : "—"}
                  </DiasChip>
                </STd>
              </STr>
            ))}
            {suscFiltradas.length === 0 && (
              <STr>
                <STd colSpan={6} style={{ textAlign: "center", opacity: 0.5 }}>
                  Sin resultados
                </STd>
              </STr>
            )}
          </tbody>
        </STable>
      </TableWrap>
      <TableFooter>
        {suscFiltradas.length} suscripciones
        {filtroEstado !== "todos" || filtroPlan !== "todos" || searchTable
          ? " (filtradas)"
          : ""}
      </TableFooter>
    </Container>
  );
}

// ===== STYLED COMPONENTS =====
const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  overflow-x: hidden;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
`;
const LoadingBox = styled.div`
  display: flex;
  align-items: center;
  gap: 0.75rem;
  justify-content: center;
  padding: 4rem;
  color: ${({ theme }) => theme.text}80;
  svg {
    width: 1.5rem;
    height: 1.5rem;
  }
`;
const ErrorBox = styled(LoadingBox)`
  color: #ef4444;
`;
const SectionTitle = styled.h3`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  margin: 0;
  svg {
    width: 1.1rem;
    height: 1.1rem;
    color: #f88533;
  }
`;
const KpiGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 1rem;
  @media (max-width: 640px) {
    grid-template-columns: 1fr;
    gap: 0.75rem;
  }
`;
const KpiCard = styled.div`
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem 1.25rem;
  min-width: 0;
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 12px;
  border-left: 3px solid ${({ $accent }) => $accent};
  transition: all 0.2s;
  &:hover {
    border-color: ${({ $accent }) => $accent};
    transform: translateY(-1px);
    box-shadow: 0 4px 12px ${({ $accent }) => $accent}15;
  }
`;
const KpiValue = styled.span`
  font-size: 1.15rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  line-height: 1.2;
  word-break: break-word;
`;
const KpiSub = styled.span`
  font-size: 0.75rem;
  font-weight: 500;
  color: ${({ $warn, theme }) => ($warn ? "#f59e0b" : theme.text + "60")};
`;
const KpiIcon = styled.div`
  width: 2.75rem;
  height: 2.75rem;
  border-radius: 10px;
  background: ${({ $color }) => $color}15;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  svg {
    width: 1.3rem;
    height: 1.3rem;
    color: ${({ $color }) => $color};
  }
`;
const KpiBody = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.15rem;
  min-width: 0;
`;
const KpiLabel = styled.span`
  font-size: 0.75rem;
  color: ${({ theme }) => theme.text}70;
`;
const TwoColGrid = styled.div`
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.25rem;
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
`;
const Panel = styled.div`
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 12px;
  padding: 1.25rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  overflow: hidden;
`;
const PanelTitle = styled.h4`
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.88rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  margin: 0;
  svg {
    width: 1rem;
    height: 1rem;
    color: #f88533;
  }
`;
const BarList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.65rem;
`;
const BarItem = styled.div`
  display: flex;
  align-items: center;
  gap: 0.75rem;
`;
const BarDot = styled.span`
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: ${({ $color }) => $color};
  flex-shrink: 0;
`;
const BarRight = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex: 1;
  min-width: 0;
`;
const BarTrack = styled.div`
  flex: 1;
  height: 8px;
  background: ${({ theme }) => theme.bg4};
  border-radius: 4px;
  overflow: hidden;
`;
const BarFill = styled.div`
  height: 100%;
  width: ${({ $pct }) => $pct}%;
  background: ${({ $color }) => $color};
  border-radius: 4px;
  transition: width 0.4s ease;
`;
const EmptyText = styled.span`
  font-size: 0.78rem;
  color: ${({ theme }) => theme.text}50;
  text-align: center;
  padding: 1rem 0;
`;
const BarLabel = styled.span`
  display: flex;
  align-items: center;
  gap: 0.35rem;
  font-size: 0.75rem;
  font-weight: 500;
  color: ${({ theme }) => theme.text};
  min-width: 70px;
  max-width: 100px;
  flex-shrink: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  @media (max-width: 640px) {
    min-width: 60px;
    max-width: 80px;
    font-size: 0.7rem;
  }
`;
const BarCount = styled.span`
  font-size: 0.7rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text}80;
  white-space: nowrap;
  min-width: 50px;
  text-align: right;
  @media (max-width: 640px) {
    font-size: 0.65rem;
    min-width: 40px;
  }
`;
const FlujoCajaGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 0.75rem;
`;
const FlujoCard = styled.div`
  background: ${({ theme, $vencido }) => ($vencido ? "#ef444410" : theme.bg3)};
  border: 1px solid
    ${({ theme, $vencido }) => ($vencido ? "#ef444440" : theme.bg4)};
  border-radius: 12px;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
  text-align: center;
`;
const FlujoMes = styled.span`
  font-size: 0.82rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text}90;
  text-transform: capitalize;
`;
const FlujoMonto = styled.span`
  font-size: 1.1rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  word-break: break-word;
  @media (max-width: 640px) {
    font-size: 0.95rem;
  }
`;
const FlujoCobros = styled.span`
  font-size: 0.72rem;
  color: ${({ theme }) => theme.text}60;
`;
const FinGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
  gap: 0.5rem;
`;
const FinItem = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.25rem;
  padding: 0.75rem;
  background: ${({ $color }) => $color}08;
  border: 1px solid ${({ $color }) => $color}25;
  border-radius: 8px;
`;
const FinLabel = styled.span`
  font-size: 0.7rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text}70;
  text-transform: uppercase;
  letter-spacing: 0.03em;
`;
const FinCount = styled.span`
  font-size: 1.3rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
`;
const FinMonto = styled.span`
  font-size: 0.72rem;
  font-weight: 500;
  color: ${({ theme }) => theme.text}80;
`;
const TableActions = styled.div`
  margin-left: auto;
`;
const ExportBtn = styled.button`
  display: flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.35rem 0.75rem;
  border: 1px solid ${({ theme }) => theme.bg4};
  background: ${({ theme }) => theme.bg3};
  color: ${({ theme }) => theme.text};
  border-radius: 6px;
  font-size: 0.72rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.15s;
  &:hover {
    border-color: #f88533;
    color: #f88533;
  }
  svg {
    width: 0.85rem;
    height: 0.85rem;
  }
`;
const TableControls = styled.div`
  display: flex;
  gap: 0.75rem;
  flex-wrap: wrap;
  align-items: center;
  @media (max-width: 640px) {
    flex-direction: column;
    align-items: stretch;
  }
`;
const TableSearch = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex: 1;
  min-width: 200px;
  padding: 0.5rem 0.75rem;
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 8px;
  &:focus-within {
    border-color: #f88533;
  }
  svg {
    width: 1rem;
    height: 1rem;
    color: ${({ theme }) => theme.text}50;
    flex-shrink: 0;
  }
  input {
    flex: 1;
    border: none;
    background: transparent;
    color: ${({ theme }) => theme.text};
    font-size: 0.82rem;
    outline: none;
    min-width: 0;
    &::placeholder {
      color: ${({ theme }) => theme.text}40;
    }
  }
`;
const TableFilters = styled.div`
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  select {
    padding: 0.45rem 0.65rem;
    background: ${({ theme }) => theme.bg3};
    border: 1px solid ${({ theme }) => theme.bg4};
    color: ${({ theme }) => theme.text};
    border-radius: 6px;
    font-size: 0.78rem;
    cursor: pointer;
    &:focus {
      border-color: #f88533;
      outline: none;
    }
  }
`;
const TableWrap = styled.div`
  overflow-x: auto;
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 10px;
`;
const STable = styled.table`
  width: 100%;
  border-collapse: collapse;
  font-size: 0.8rem;
`;
const STh = styled.th`
  padding: 0.65rem 0.85rem;
  text-align: ${({ $right }) => ($right ? "right" : "left")};
  font-size: 0.72rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: ${({ theme }) => theme.text}70;
  background: ${({ theme }) => theme.bg3};
  border-bottom: 1px solid ${({ theme }) => theme.bg4};
  white-space: nowrap;
  cursor: ${({ $sort }) => ($sort ? "pointer" : "default")};
  user-select: none;
  &:hover {
    color: ${({ $sort, theme }) => ($sort ? "#f88533" : theme.text + "70")};
  }
`;
const STr = styled.tr`
  &:not(:last-child) td {
    border-bottom: 1px solid ${({ theme }) => theme.bg4}15;
  }
  &:hover td {
    background: ${({ theme }) => theme.bg3}40;
  }
`;
const STd = styled.td`
  padding: 0.6rem 0.85rem;
  color: ${({ theme }) => theme.text};
  text-align: ${({ $right }) => ($right ? "right" : "left")};
  ${({ $mono }) => $mono && "font-family:monospace;font-size:0.75rem;"}
`;
const EmpCell = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.1rem;
`;
const EmpRuc = styled.span`
  font-size: 0.65rem;
  color: ${({ theme }) => theme.text}50;
  font-family: monospace;
`;
const OvChip = styled.span`
  margin-left: 0.35rem;
  font-size: 0.7rem;
`;
const EstBadge = styled.span`
  display: inline-flex;
  align-items: center;
  padding: 0.15rem 0.5rem;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: 600;
  background: ${({ $color }) => $color}15;
  color: ${({ $color }) => $color};
  border: 1px solid ${({ $color }) => $color}30;
`;
const DiasChip = styled.span`
  font-size: 0.78rem;
  font-weight: 600;
  color: ${({ $dias }) =>
    $dias == null
      ? "#6b7280"
      : $dias <= 0
        ? "#ef4444"
        : $dias <= 7
          ? "#f59e0b"
          : $dias <= 30
            ? "#f88533"
            : "#10b981"};
`;
const TableFooter = styled.div`
  font-size: 0.72rem;
  color: ${({ theme }) => theme.text}50;
  text-align: right;
`;
