import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Collapse,
  Divider,
  Drawer,
  IconButton,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { getFacturas } from "../../../api/facturas.service";
import { getInteresesManuales } from "../../../api/interes-manual.service";
import { EstadoCuentaPdfModal } from "../EstadoCuentaPdfModal";
import {
  getGestionMoraByCliente,
  getRefinanciaciones,
  getRefinanciacionPdfUrl,
  getTimelineGestionesCliente,
} from "../../../api/cobranzas.service";
import { GestionMoraDetalleDrawer } from "../../cobranzas/gestion-mora/GestionMoraDetalleDrawer";
import { ElevarModales } from "../../_standards";
import { fmtFechaCalendario } from "../../../utils/fecha";
import {
  getCobRefiEstadoChip,
  getCobGestionTipoChip,
  getCobGestionResultadoChip,
} from "../../_standards/enums/estados";
import { fmtFechaHora, fmtFechaHoraSoloFecha } from "../../../utils/fecha";

const MORA_ESTADO_COLOR = {
  AL_DIA: "success",
  RECUPERADA: "success",
  GESTION_INTERNA: "warning",
  REFINANCIADA: "warning",
  INFORMCONF: "info",
  DEMANDA: "error",
  INCOBRABLE: "error",
};

const MoraGestionActivaCard = ({ clienteId }) => {
  const [drawerOpen, setDrawerOpen] = useState(false);
  const { data } = useQuery({
    queryKey: ["gestion-mora-cliente", clienteId],
    queryFn: () => getGestionMoraByCliente(clienteId),
    enabled: !!clienteId,
  });

  if (!data?.tiene_gestion_activa || !data?.activa) return null;
  const activa = data.activa;
  const color = MORA_ESTADO_COLOR[activa.estado_actual] || "default";

  return (
    <>
      <Box
        sx={{
          mx: 2,
          mt: 2,
          p: 1.5,
          border: "1px solid",
          borderColor: "divider",
          borderRadius: 1.5,
          bgcolor: "background.paper",
          display: "flex",
          alignItems: "center",
          gap: 1.5,
          flexWrap: "wrap",
        }}
      >
        <Icon icon="mdi:gavel" width={20} color="#dc2626" />
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <Stack direction="row" spacing={1} alignItems="center" flexWrap="wrap">
            <Typography variant="caption" fontWeight={700} color="text.secondary">
              Gestión de mora activa
            </Typography>
            <Chip
              size="small"
              label={activa.estado_actual}
              color={color}
              sx={{ fontSize: "0.65rem", height: 20, fontWeight: 700 }}
            />
          </Stack>
          <Typography variant="caption" color="text.secondary" display="block" sx={{ mt: 0.3 }}>
            Monto: <b>{Number(activa.monto_involucrado ?? 0).toLocaleString("es-PY")} Gs.</b>
            {" · "}
            Abierta el {fmtFechaCalendario(activa.fecha_ingreso)}
          </Typography>
        </Box>
        <Button
          size="small"
          variant="outlined"
          color="error"
          startIcon={<Icon icon="mdi:gavel" width={16} />}
          onClick={() => setDrawerOpen(true)}
          sx={{ textTransform: "none", fontWeight: 600 }}
        >
          Ver expediente
        </Button>
      </Box>

      <GestionMoraDetalleDrawer
        open={drawerOpen}
        gestionId={activa.id}
        onClose={() => setDrawerOpen(false)}
      />
    </>
  );
};

const fmtGs = (n) => Number(n ?? 0).toLocaleString("es-PY");

// Drawer con el timeline completo de gestiones del cliente.
// Reusa el endpoint del card para no duplicar fetch (mismo queryKey).
const GestionesTimelineDrawer = ({ clienteId, open, onClose }) => {
  const { data = [], isLoading } = useQuery({
    queryKey: ["gestiones-cliente-timeline", clienteId],
    queryFn: () => getTimelineGestionesCliente(clienteId),
    enabled: !!clienteId && open,
  });
  const items = Array.isArray(data) ? data : [];

  return (
    <Drawer anchor="right" open={open} onClose={onClose} PaperProps={{ sx: { width: { xs: "100%", sm: 460 } } }}>
      <Box sx={{ p: 2, borderBottom: "1px solid", borderColor: "divider", display: "flex", alignItems: "center", gap: 1 }}>
        <Icon icon="mdi:clipboard-check-multiple-outline" width={22} color="#1d4ed8" />
        <Box sx={{ flex: 1 }}>
          <Typography variant="subtitle1" fontWeight={700}>
            Gestiones de cobranza
          </Typography>
          <Typography variant="caption" color="text.secondary">
            Historial completo · {items.length} {items.length === 1 ? "registro" : "registros"}
          </Typography>
        </Box>
        <IconButton onClick={onClose} size="small">
          <Icon icon="mdi:close" width={20} />
        </IconButton>
      </Box>

      <Box sx={{ p: 2, overflowY: "auto" }}>
        {isLoading ? (
          <Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
            <CircularProgress size={24} />
          </Box>
        ) : items.length === 0 ? (
          <Typography variant="body2" color="text.secondary" sx={{ textAlign: "center", py: 4 }}>
            Sin gestiones registradas.
          </Typography>
        ) : (
          <Stack spacing={1.25}>
            {items.map((g) => {
              const tipo = getCobGestionTipoChip(g.tipo_gestion);
              const res = getCobGestionResultadoChip(g.resultado);
              const facturaNumero = g.factura_cab
                ? `${g.factura_cab.dest}-${g.factura_cab.dpunexp}-${g.factura_cab.dnumdoc}`
                : null;
              const geoUrl = g.geo_lat && g.geo_lng
                ? `https://www.google.com/maps?q=${g.geo_lat},${g.geo_lng}`
                : null;
              return (
                <Paper
                  key={g.id}
                  variant="outlined"
                  sx={{ p: 1.25, borderRadius: 1.5, bgcolor: "background.paper" }}
                >
                  <Stack direction="row" spacing={1} alignItems="flex-start">
                    <Icon icon={tipo.icon || "mdi:clipboard-outline"} width={18} style={{ marginTop: 2 }} />
                    <Box sx={{ flex: 1, minWidth: 0 }}>
                      <Stack direction="row" spacing={0.5} alignItems="center" flexWrap="wrap">
                        <Typography variant="caption" color="text.secondary" fontWeight={600}>
                          {fmtFechaHora(g.fecha)}
                        </Typography>
                        <Chip size="small" label={tipo.label} color={tipo.color} sx={{ fontSize: "0.62rem", height: 18 }} />
                        <Chip size="small" label={res.label} color={res.color} sx={{ fontSize: "0.62rem", height: 18 }} />
                      </Stack>
                      {facturaNumero && (
                        <Typography variant="caption" sx={{ display: "block", color: "text.secondary", mt: 0.3 }}>
                          Factura: <b>{facturaNumero}</b>
                        </Typography>
                      )}
                      {g.observacion && (
                        <Typography variant="caption" sx={{ display: "block", color: "text.primary", fontStyle: "italic", mt: 0.5 }}>
                          "{g.observacion}"
                        </Typography>
                      )}
                      {g.proxima_accion && g.proxima_fecha && (
                        <Typography variant="caption" sx={{ display: "block", color: "primary.main", mt: 0.5 }}>
                          Próxima: {g.proxima_accion} — {fmtFechaCalendario(g.proxima_fecha)}
                        </Typography>
                      )}
                      {g.usuario_nombre && (
                        <Typography variant="caption" sx={{ display: "block", color: "text.disabled", mt: 0.25 }}>
                          <Icon icon="mdi:account" width={11} style={{ verticalAlign: "-2px", marginRight: 2 }} />
                          Registrado por {g.usuario_nombre}
                        </Typography>
                      )}
                      {geoUrl && (
                        <Button
                          size="small"
                          startIcon={<Icon icon="mdi:map-marker" width={14} />}
                          href={geoUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          sx={{ mt: 0.5, textTransform: "none", fontSize: "0.7rem", py: 0.2 }}
                        >
                          Ver ubicación
                        </Button>
                      )}
                    </Box>
                  </Stack>
                </Paper>
              );
            })}
          </Stack>
        )}
      </Box>
    </Drawer>
  );
};

// Timeline de gestiones de cobranza del cliente
const GestionesTimelineCard = ({ clienteId }) => {
  const [drawerOpen, setDrawerOpen] = useState(false);
  const { data = [], isLoading } = useQuery({
    queryKey: ["gestiones-cliente-timeline", clienteId],
    queryFn: () => getTimelineGestionesCliente(clienteId),
    enabled: !!clienteId,
  });
  const items = Array.isArray(data) ? data : [];
  if (!isLoading && items.length === 0) return null;
  const hayMas = items.length > 8;

  return (
    <>
      <Box sx={{ mx: 2, mt: 2, p: 1.5, border: "1px solid", borderColor: "divider", borderRadius: 1.5, bgcolor: "background.paper" }}>
        <Stack
          direction="row"
          alignItems="center"
          spacing={1}
          sx={{
            mb: 1,
            cursor: "pointer",
            borderRadius: 1,
            mx: -0.5,
            px: 0.5,
            "&:hover": { bgcolor: "action.hover" },
          }}
          onClick={() => setDrawerOpen(true)}
          role="button"
        >
          <Icon icon="mdi:clipboard-check-multiple-outline" width={18} color="#1d4ed8" />
          <Typography variant="caption" fontWeight={700} color="text.secondary" sx={{ flex: 1 }}>
            Gestiones de cobranza
          </Typography>
          <Chip
            size="small"
            label={items.length}
            color="primary"
            variant="outlined"
            sx={{ fontSize: "0.65rem", height: 20, fontWeight: 700 }}
          />
          <Icon icon="mdi:chevron-right" width={16} color="#94a3b8" />
        </Stack>
        {isLoading ? (
          <Box sx={{ display: "flex", justifyContent: "center", py: 1 }}>
            <CircularProgress size={16} />
          </Box>
        ) : (
          <Stack spacing={0.75}>
            {items.slice(0, 8).map((g) => {
              const tipo = getCobGestionTipoChip(g.tipo_gestion);
              const res = getCobGestionResultadoChip(g.resultado);
              return (
                <Box key={g.id} sx={{ display: "flex", alignItems: "flex-start", gap: 1 }}>
                  <Icon icon={tipo.icon || "mdi:clipboard-outline"} width={16} style={{ marginTop: 2 }} />
                  <Box sx={{ flex: 1, minWidth: 0 }}>
                    <Stack direction="row" spacing={0.5} alignItems="center" flexWrap="wrap">
                      <Typography variant="caption" color="text.secondary">
                        {fmtFechaHora(g.fecha)}
                      </Typography>
                      <Chip size="small" label={tipo.label} color={tipo.color} sx={{ fontSize: "0.62rem", height: 18 }} />
                      <Chip size="small" label={res.label} color={res.color} sx={{ fontSize: "0.62rem", height: 18 }} />
                    </Stack>
                    {g.observacion && (
                      <Typography variant="caption" sx={{ display: "block", color: "text.secondary", fontStyle: "italic" }}>
                        "{g.observacion}"
                      </Typography>
                    )}
                    {g.proxima_accion && g.proxima_fecha && (
                      <Typography variant="caption" sx={{ display: "block", color: "primary.main" }}>
                        Próxima: {g.proxima_accion} — {fmtFechaCalendario(g.proxima_fecha)}
                      </Typography>
                    )}
                    {g.usuario_nombre && (
                      <Typography variant="caption" sx={{ display: "block", color: "text.disabled" }}>
                        <Icon icon="mdi:account" width={11} style={{ verticalAlign: "-2px", marginRight: 2 }} />
                        Registrado por {g.usuario_nombre}
                      </Typography>
                    )}
                  </Box>
                </Box>
              );
            })}
            {hayMas && (
              <Button
                size="small"
                onClick={() => setDrawerOpen(true)}
                sx={{ alignSelf: "flex-start", textTransform: "none", fontSize: "0.72rem", mt: 0.5 }}
              >
                Ver todas ({items.length})
              </Button>
            )}
          </Stack>
        )}
      </Box>

      <GestionesTimelineDrawer
        clienteId={clienteId}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
      />
    </>
  );
};

// Sección de refinanciaciones recientes del cliente (últimas 5)
const RefinanciacionesCard = ({ clienteId }) => {
  const { data } = useQuery({
    queryKey: ["refinanciaciones-cliente", clienteId],
    queryFn: () => getRefinanciaciones({ cliente_id: clienteId, limit: 5 }),
    enabled: !!clienteId,
  });
  const items = data?.data ?? data?.rows ?? [];
  if (!items.length) return null;
  return (
    <Box sx={{ mx: 2, mt: 2, p: 1.5, border: "1px solid", borderColor: "divider", borderRadius: 1.5, bgcolor: "background.paper" }}>
      <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1 }}>
        <Icon icon="mdi:file-restore-outline" width={18} color="#1d4ed8" />
        <Typography variant="caption" fontWeight={700} color="text.secondary" sx={{ flex: 1 }}>
          Refinanciaciones
        </Typography>
        <Chip size="small" label={items.length} variant="outlined" sx={{ fontSize: "0.65rem", height: 20 }} />
      </Stack>
      <Stack spacing={0.75}>
        {items.map((r) => {
          const meta = getCobRefiEstadoChip(r.estado);
          return (
            <Box key={r.id} sx={{ display: "flex", alignItems: "center", gap: 1 }}>
              <Typography variant="caption" color="text.secondary" sx={{ minWidth: 70 }}>
                {fmtFechaCalendario(r.created_at ?? r.fecha)}
              </Typography>
              <Chip size="small" label={meta.label} color={meta.color} sx={{ fontSize: "0.62rem", height: 18 }} />
              <Typography variant="caption" sx={{ flex: 1 }}>
                {fmtGs(r.monto_capital_nuevo)} Gs. · {r.cantidad_cuotas} cuotas
              </Typography>
              <IconButton
                size="small"
                onClick={() => window.open(getRefinanciacionPdfUrl(r.id), "_blank")}
              >
                <Icon icon="mdi:file-pdf-box" width={16} />
              </IconButton>
            </Box>
          );
        })}
      </Stack>
    </Box>
  );
};

const fmtFecha = (d) => {
  if (!d) return "—";
  const dt = new Date(d);
  return isNaN(dt) ? String(d) : dt.toLocaleDateString("es-PY");
};

const ESTADO_COLOR = {
  pagada: "success", pagado: "success", aprobado: "success",
  pendiente: "warning", parcial: "info",
  anulada: "error", anulado: "error",
};

const getFacturaTotal = (f) => {
  if (f.factura_subtotales?.length) return Number(f.factura_subtotales[0]?.dtotgralope ?? 0);
  return Number(f.total_factura ?? f.total ?? 0);
};

const esCredito = (f) => f.condicion_operacion?.codigo === 2 || f.condicion_operacion?.codigo === "2";

// Pagos válidos (no anulados) de una cuota
const pagosValidos = (c) => (c.recibo_cobro_detalle ?? []).filter(
  (d) => d.recibos_cobro && d.recibos_cobro.estado !== "anulado",
);

// Fecha del último pago de una cuota (registro o emisión)
const ultimoPagoFechaCuota = (c) => {
  const pagos = pagosValidos(c);
  if (!pagos.length) return null;
  const fechas = pagos.map((p) => p.recibos_cobro?.fecha_registro ?? p.recibos_cobro?.fecha_emision).filter(Boolean);
  if (!fechas.length) return null;
  return new Date(Math.max(...fechas.map((d) => new Date(d).getTime())));
};

// Última fecha de pago de toda la factura
const ultimoPagoFechaFactura = (f) => {
  const fechas = (f.factura_cuotas ?? []).map(ultimoPagoFechaCuota).filter(Boolean);
  if (!fechas.length) return null;
  return new Date(Math.max(...fechas.map((d) => d.getTime())));
};

// Saldo pendiente de la factura
const saldoPendienteFactura = (f) => {
  const cuotas = f.factura_cuotas ?? [];
  if (cuotas.length === 0) return 0;
  return cuotas.reduce((s, c) => {
    if (c.estado === "pagado" || c.estado === "Pagado") return s;
    const saldo = Number(c.saldo_pendiente);
    if (Number.isFinite(saldo) && saldo > 0) return s + saldo;
    const pagado = pagosValidos(c).reduce((a, d) => a + Number(d.monto_pagado ?? 0), 0);
    return s + Math.max(0, Number(c.dmoncuota ?? 0) - pagado);
  }, 0);
};

// Periodicidad de pago inferida de la factura: política (cuentas_cobrar.intervalo_dias)
// primero, con fallback al promedio de días entre cuotas.
const getFrecuenciaFactura = (f) => {
  if (!esCredito(f)) return null;
  const cuentaPolitica = Array.isArray(f.cuentas_cobrar) ? f.cuentas_cobrar[0] : f.cuentas_cobrar;
  let intervalo = cuentaPolitica?.intervalo_dias ?? null;

  const cuotas = (f.factura_cuotas ?? [])
    .map((c) => c.dvenccuo)
    .filter(Boolean)
    .map((d) => new Date(d).getTime())
    .sort((a, b) => a - b);

  if (!intervalo && cuotas.length >= 2) {
    const diffs = [];
    for (let i = 1; i < cuotas.length; i++) {
      diffs.push(Math.round((cuotas[i] - cuotas[i - 1]) / 86400000));
    }
    const avg = Math.round(diffs.reduce((a, b) => a + b, 0) / diffs.length);
    if (Math.abs(avg - 7) <= 1) intervalo = 7;
    else if (Math.abs(avg - 15) <= 2) intervalo = 15;
    else if (Math.abs(avg - 30) <= 3) intervalo = 30;
    else intervalo = avg;
  }

  if (intervalo === 7) return { label: "Semanal", kind: "semanal" };
  if (intervalo === 15) return { label: "Quincenal", kind: "quincenal" };
  if (intervalo === 30) return { label: "Mensual", kind: "mensual" };
  if (intervalo) return { label: `Cada ${intervalo}d`, kind: "plazos" };
  const totalCuotas = f.factura_cuotas?.length ?? 0;
  return { label: totalCuotas > 0 ? `${totalCuotas} cuotas` : "Plazos", kind: "plazos" };
};

// Agrega la periodicidad para todas las facturas de un cliente. Si todas las
// facturas de crédito comparten misma frecuencia, devuelve esa; si son mixtas,
// "Mixto"; si no hay facturas de crédito, "Contado".
const getFrecuenciaAggregada = (facturas) => {
  const creditos = facturas.filter(esCredito);
  if (!creditos.length) return { label: "Contado", kind: "contado" };
  const freqs = creditos.map(getFrecuenciaFactura).filter(Boolean);
  if (!freqs.length) return { label: "Plazos", kind: "plazos" };
  const uniqueKinds = new Set(freqs.map((f) => f.kind));
  if (uniqueKinds.size === 1) return freqs[0];
  return { label: "Mixto", kind: "mixto" };
};

const FRECUENCIA_COLOR = {
  contado: "success.main",
  semanal: "info.main",
  quincenal: "info.main",
  mensual: "info.main",
  plazos: "warning.main",
  mixto: "text.secondary",
};

// Atraso promedio (días) calculado sobre cuotas pagadas con fecha de pago conocida
const atrasoPromedioDias = (facturas) => {
  const diffs = [];
  for (const f of facturas) {
    for (const c of f.factura_cuotas ?? []) {
      if (!(c.estado === "pagado" || c.estado === "Pagado")) continue;
      const fp = ultimoPagoFechaCuota(c);
      if (!fp || !c.dvenccuo) continue;
      const venc = new Date(c.dvenccuo);
      const diff = Math.round((fp.setHours(0,0,0,0) - venc.setHours(0,0,0,0)) / 86400000);
      diffs.push(diff);
    }
  }
  if (!diffs.length) return null;
  return Math.round(diffs.reduce((a, b) => a + b, 0) / diffs.length);
};

// ── Detalle expandido de crédito ──────────────────────────────────────────────
const CreditoDetalle = ({ f }) => {
  const cuotas = (f.factura_cuotas ?? []).slice().sort((a, b) => (a.nro_cuota ?? 0) - (b.nro_cuota ?? 0));
  const hoy = new Date(); hoy.setHours(0, 0, 0, 0);

  const esPagada = (c) => c.estado === "pagado" || c.estado === "Pagado";
  const esVencidaCuota = (c) => !esPagada(c) && new Date(c.dvenccuo) < hoy;

  const totalCuotas = cuotas.length;
  const cuotasPagadas = cuotas.filter(esPagada);
  const cuotasVencidas = cuotas.filter(esVencidaCuota);
  const cuotasPendientes = cuotas.filter((c) => !esPagada(c) && !esVencidaCuota(c));
  const totalVencido = cuotasVencidas.reduce((s, c) => s + (Number(c.saldo_pendiente) || Number(c.dmoncuota)), 0);
  const totalPendiente = cuotasPendientes.reduce((s, c) => s + (Number(c.saldo_pendiente) || Number(c.dmoncuota)), 0);
  const alDia = totalVencido === 0 && cuotasPagadas.length < totalCuotas;

  const [filtroCuota, setFiltroCuota] = useState(cuotasVencidas.length > 0 ? "vencidas" : "todas");

  // Interés cargado a mano desde Cuentas por Cobrar. Sin permiso para verlo,
  // el bloque simplemente no aparece.
  const { data: interesesData } = useQuery({
    queryKey: ["intereses-manuales", f.id],
    queryFn: () => getInteresesManuales(f.id),
    enabled: !!f.id && esCredito(f),
    retry: false,
    staleTime: 30000,
  });
  const intereses = Array.isArray(interesesData) ? interesesData : interesesData?.data ?? [];
  const pendienteInteres = (i) =>
    i.estado === "pendiente" ? Math.max(0, Number(i.monto ?? 0) - Number(i.monto_cobrado ?? 0)) : 0;
  const interesPendienteTotal = intereses.reduce((s, i) => s + pendienteInteres(i), 0);
  const interesPendientePorCuota = intereses.reduce((acc, i) => {
    if (i.factura_cuota_id) acc[i.factura_cuota_id] = (acc[i.factura_cuota_id] ?? 0) + pendienteInteres(i);
    return acc;
  }, {});

  const cuotasFiltradas = (() => {
    if (filtroCuota === "vencidas") return cuotasVencidas;
    if (filtroCuota === "pendientes") return cuotasPendientes;
    if (filtroCuota === "pagadas") return cuotasPagadas;
    return cuotas;
  })();

  // Política de cobranza acordada (viene de cuentas_cobrar, propagada desde solicitud_credito)
  const cuentaPolitica = Array.isArray(f.cuentas_cobrar) ? f.cuentas_cobrar[0] : f.cuentas_cobrar;
  const politica = cuentaPolitica
    ? {
        intervalo_dias: cuentaPolitica.intervalo_dias,
        dia_fijo_pago_1: cuentaPolitica.dia_fijo_pago_1,
        dia_fijo_pago_2: cuentaPolitica.dia_fijo_pago_2,
        dia_cobro_semana: cuentaPolitica.dia_cobro_semana,
        dias_gracia_override: cuentaPolitica.dias_gracia_override,
      }
    : null;
  const politicaTieneAlgo =
    politica &&
    (politica.intervalo_dias != null ||
      politica.dia_fijo_pago_1 != null ||
      politica.dia_fijo_pago_2 != null ||
      politica.dia_cobro_semana != null ||
      politica.dias_gracia_override != null);
  const frecuenciaLabel = politica?.intervalo_dias === 7
    ? "Semanal"
    : politica?.intervalo_dias === 15
      ? "Quincenal"
      : politica?.intervalo_dias === 30
        ? "Mensual"
        : politica?.intervalo_dias
          ? `Cada ${politica.intervalo_dias}d`
          : null;
  const diaLabel = politica?.dia_fijo_pago_1
    ? politica.dia_fijo_pago_2
      ? `Días ${politica.dia_fijo_pago_1} y ${politica.dia_fijo_pago_2} de cada mes`
      : `Día ${politica.dia_fijo_pago_1} de cada mes`
    : politica?.dia_cobro_semana
      ? `${["", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"][politica.dia_cobro_semana]} de cada semana`
      : null;

  return (
    <Box sx={{ bgcolor: "action.hover", px: 2, py: 1.5 }}>
      {/* Política de cobranza acordada */}
      {politicaTieneAlgo && (
        <Stack direction="row" spacing={0.5} sx={{ mb: 1, flexWrap: "wrap", rowGap: 0.5, alignItems: "center" }}>
          <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 600, mr: 0.5 }}>
            <Icon icon="mdi:calendar-check" width={12} style={{ verticalAlign: "middle", marginRight: 3 }} />
            Política:
          </Typography>
          {frecuenciaLabel && (
            <Chip size="small" variant="outlined" label={frecuenciaLabel} sx={{ fontSize: "0.68rem", height: 22 }} />
          )}
          {diaLabel && (
            <Chip
              size="small"
              variant="outlined"
              color="primary"
              icon={<Icon icon="mdi:calendar-clock" width={12} />}
              label={diaLabel}
              sx={{ fontSize: "0.68rem", height: 22 }}
            />
          )}
          {politica.dias_gracia_override != null && (
            <Chip
              size="small"
              color="warning"
              variant="outlined"
              icon={<Icon icon="mdi:clock-alert-outline" width={12} />}
              label={`Gracia ${politica.dias_gracia_override}d`}
              sx={{ fontSize: "0.68rem", height: 22 }}
            />
          )}
        </Stack>
      )}

      {/* Resumen crédito */}
      <Stack direction="row" spacing={1} sx={{ mb: 1.5, flexWrap: "wrap", rowGap: 1 }}>
        {totalVencido > 0 && (
          <Paper variant="outlined" sx={{ px: 1.25, py: 0.6, textAlign: "center", borderColor: "error.main", flex: "1 1 22%", minWidth: 110 }}>
            <Typography variant="caption" color="error.main" display="block" sx={{ lineHeight: 1.1 }}>Vencido</Typography>
            <Typography variant="body2" fontWeight={700} color="error.main">{fmtGs(totalVencido)} Gs.</Typography>
            <Typography variant="caption" color="error.main" sx={{ fontSize: "0.65rem" }}>{cuotasVencidas.length} cuotas</Typography>
          </Paper>
        )}
        {cuotasPendientes.length > 0 && (
          <Paper variant="outlined" sx={{ px: 1.25, py: 0.6, textAlign: "center", borderColor: "warning.main", flex: "1 1 22%", minWidth: 110 }}>
            <Typography variant="caption" color="warning.main" display="block" sx={{ lineHeight: 1.1 }}>Por vencer</Typography>
            <Typography variant="body2" fontWeight={700} color="warning.main">{fmtGs(totalPendiente)} Gs.</Typography>
            <Typography variant="caption" color="warning.main" sx={{ fontSize: "0.65rem" }}>{cuotasPendientes.length} cuotas</Typography>
          </Paper>
        )}
        <Paper variant="outlined" sx={{ px: 1.25, py: 0.6, textAlign: "center", flex: "1 1 22%", minWidth: 110 }}>
          <Typography variant="caption" color="text.secondary" display="block" sx={{ lineHeight: 1.1 }}>Pagadas</Typography>
          <Typography variant="body2" fontWeight={700} color="success.main">{cuotasPagadas.length} / {totalCuotas}</Typography>
          <Typography variant="caption" color="text.secondary" sx={{ fontSize: "0.65rem" }}>
            {totalCuotas > 0 ? Math.round((cuotasPagadas.length / totalCuotas) * 100) : 0}%
          </Typography>
        </Paper>
        {interesPendienteTotal > 0 && (
          <Paper variant="outlined" sx={{ px: 1.25, py: 0.6, textAlign: "center", borderColor: "secondary.main", flex: "1 1 22%", minWidth: 110 }}>
            <Typography variant="caption" color="secondary.main" display="block" sx={{ lineHeight: 1.1 }}>Interés manual pendiente</Typography>
            <Typography variant="body2" fontWeight={700} color="secondary.main">{fmtGs(interesPendienteTotal)} Gs.</Typography>
            <Typography variant="caption" color="secondary.main" sx={{ fontSize: "0.65rem" }}>
              {cuotasPagadas.length === totalCuotas ? "capital saldado" : "se cobra después del capital"}
            </Typography>
          </Paper>
        )}
        {alDia && totalVencido === 0 && (
          <Paper variant="outlined" sx={{ px: 1.25, py: 0.6, display: "flex", alignItems: "center", gap: 0.5, borderColor: "success.main" }}>
            <Icon icon="mdi:check-circle" color="#22c55e" width={14} />
            <Typography variant="caption" color="success.main" fontWeight={600}>Al día</Typography>
          </Paper>
        )}
      </Stack>

      {/* Filtros */}
      <Stack direction="row" spacing={0.5} sx={{ mb: 1, flexWrap: "wrap", rowGap: 0.5 }}>
        <Chip
          size="small"
          label={`Todas (${totalCuotas})`}
          color={filtroCuota === "todas" ? "primary" : "default"}
          variant={filtroCuota === "todas" ? "filled" : "outlined"}
          onClick={() => setFiltroCuota("todas")}
          sx={{ fontSize: "0.7rem", height: 22 }}
        />
        {cuotasVencidas.length > 0 && (
          <Chip
            size="small"
            label={`Vencidas (${cuotasVencidas.length})`}
            color={filtroCuota === "vencidas" ? "error" : "default"}
            variant={filtroCuota === "vencidas" ? "filled" : "outlined"}
            onClick={() => setFiltroCuota("vencidas")}
            sx={{ fontSize: "0.7rem", height: 22 }}
          />
        )}
        {cuotasPendientes.length > 0 && (
          <Chip
            size="small"
            label={`Por vencer (${cuotasPendientes.length})`}
            color={filtroCuota === "pendientes" ? "warning" : "default"}
            variant={filtroCuota === "pendientes" ? "filled" : "outlined"}
            onClick={() => setFiltroCuota("pendientes")}
            sx={{ fontSize: "0.7rem", height: 22 }}
          />
        )}
        {cuotasPagadas.length > 0 && (
          <Chip
            size="small"
            label={`Pagadas (${cuotasPagadas.length})`}
            color={filtroCuota === "pagadas" ? "success" : "default"}
            variant={filtroCuota === "pagadas" ? "filled" : "outlined"}
            onClick={() => setFiltroCuota("pagadas")}
            sx={{ fontSize: "0.7rem", height: 22 }}
          />
        )}
      </Stack>

      {/* Cuotas con scroll cuando son muchas */}
      <Box sx={{ maxHeight: 320, overflowY: "auto", border: "1px solid", borderColor: "divider", borderRadius: 1, bgcolor: "background.paper" }}>
        <Table size="small" stickyHeader>
          <TableHead>
            <TableRow>
              <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }}>Cuota</TableCell>
              <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }}>Vencimiento</TableCell>
              <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="right">Monto</TableCell>
              <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="right">Saldo</TableCell>
              <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="center">Estado</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {cuotasFiltradas.length === 0 ? (
              <TableRow>
                <TableCell colSpan={5} align="center" sx={{ py: 2, fontSize: "0.75rem", color: "text.disabled" }}>
                  Sin cuotas en este filtro
                </TableCell>
              </TableRow>
            ) : cuotasFiltradas.map((c, i) => {
              const pagada = esPagada(c);
              const vencida = esVencidaCuota(c);
              const saldo = Number(c.saldo_pendiente ?? 0) || Number(c.dmoncuota ?? 0);
              const estadoLabel = pagada ? "Pagada" : vencida ? "Vencida" : "Pendiente";
              const estadoColor = pagada ? "success" : vencida ? "error" : "warning";
              const fechaPagoCuota = pagada ? ultimoPagoFechaCuota(c) : null;
              return (
                <TableRow key={c.id ?? i} hover>
                  <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }}>{c.nro_cuota ?? i + 1}</TableCell>
                  <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }}>
                    {fmtFecha(c.dvenccuo)}
                    {vencida && (
                      <Typography variant="caption" color="error.main" display="block" sx={{ lineHeight: 1 }}>
                        {Math.floor((new Date().setHours(0,0,0,0) - new Date(c.dvenccuo).setHours(0,0,0,0)) / 86400000)} días
                      </Typography>
                    )}
                    {fechaPagoCuota && (
                      <Typography variant="caption" color="success.main" display="block" sx={{ lineHeight: 1 }}>
                        Pagada {fmtFecha(fechaPagoCuota)}
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }} align="right">{fmtGs(c.dmoncuota)}</TableCell>
                  <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }} align="right">
                    {pagada ? "—" : fmtGs(saldo)}
                    {interesPendientePorCuota[c.id] > 0 && (
                      <Typography variant="caption" color="secondary.main" display="block" sx={{ lineHeight: 1 }}>
                        + {fmtGs(interesPendientePorCuota[c.id])} interés
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell sx={{ py: 0.3 }} align="center">
                    <Chip size="small" label={estadoLabel} color={estadoColor} variant="outlined" sx={{ fontSize: "0.62rem", height: 18 }} />
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </Box>

      {intereses.length > 0 && (
        <Box sx={{ mt: 1.5 }}>
          <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 600, display: "block", mb: 0.5 }}>
            <Icon icon="mdi:percent-outline" width={12} style={{ verticalAlign: "middle", marginRight: 3 }} />
            Intereses manuales
          </Typography>
          <Box sx={{ border: "1px solid", borderColor: "divider", borderRadius: 1, bgcolor: "background.paper" }}>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }}>Sobre</TableCell>
                  <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }}>Motivo</TableCell>
                  <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="right">Monto</TableCell>
                  <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="right">Cobrado</TableCell>
                  <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="center">Estado</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {intereses.map((i) => {
                  const cobrado = i.estado === "cobrado";
                  const parcial = !cobrado && Number(i.monto_cobrado ?? 0) > 0;
                  return (
                    <TableRow key={i.id}>
                      <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }}>
                        {i.factura_cuota ? `Cuota ${i.factura_cuota.nro_cuota}` : "Cuenta"}
                        <Typography variant="caption" color="text.secondary" display="block" sx={{ lineHeight: 1 }}>
                          {fmtFechaHoraSoloFecha(i.created_at)}
                        </Typography>
                      </TableCell>
                      <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }}>{i.motivo || "—"}</TableCell>
                      <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }} align="right">{fmtGs(i.monto)}</TableCell>
                      <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }} align="right">{fmtGs(i.monto_cobrado)}</TableCell>
                      <TableCell sx={{ py: 0.3 }} align="center">
                        <Chip
                          size="small"
                          variant="outlined"
                          label={cobrado ? "Cobrado" : parcial ? "Parcial" : "Pendiente"}
                          color={cobrado ? "success" : "warning"}
                          sx={{ fontSize: "0.62rem", height: 18 }}
                        />
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </Box>
        </Box>
      )}
    </Box>
  );
};

// ── Items de factura ──────────────────────────────────────────────────────────
const ItemsDetalle = ({ items }) => (
  <Box sx={{ bgcolor: "action.hover", px: 2, py: 1 }}>
    <Table size="small">
      <TableHead>
        <TableRow>
          <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }}>Descripción</TableCell>
          <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="right">Cant.</TableCell>
          <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="right">P. Unit.</TableCell>
          <TableCell sx={{ py: 0.3, fontSize: "0.7rem", fontWeight: 600 }} align="right">Subtotal</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {items.map((d, i) => (
          <TableRow key={d.id ?? i}>
            <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }}>
              {d.ddesproser ?? d.descripcion ?? d.productos?.descripcion ?? "—"}
            </TableCell>
            <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }} align="right">
              {Number(d.dcantproser ?? d.cantidad ?? 0)}
            </TableCell>
            <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }} align="right">
              {fmtGs(d.duniproser ?? d.precio_unitario)}
            </TableCell>
            <TableCell sx={{ py: 0.3, fontSize: "0.75rem" }} align="right">
              {fmtGs(d.dtotbruopeitem ?? d.subtotal)}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  </Box>
);

// ── Fila de factura ───────────────────────────────────────────────────────────
const FacturaRow = ({ f }) => {
  const [open, setOpen] = useState(false);
  const items = f.factura_det ?? f.items ?? [];
  const credito = esCredito(f);
  const numFactura = f.numero_factura ?? ([f.dest, f.dpunexp, f.dnumdoc].filter(Boolean).join("-") || "—");
  const fecha = f.fecha_emision ?? f.dfeemide;
  const total = getFacturaTotal(f);
  const saldo = saldoPendienteFactura(f);

  const cuotas = f.factura_cuotas ?? [];
  const cuotasPagadas = cuotas.filter((c) => c.estado === "pagado" || c.estado === "Pagado").length;
  const cuotasTotal = cuotas.length;
  const tieneVencidas = cuotas.some((c) => {
    if (c.estado === "pagado" || c.estado === "Pagado") return false;
    return new Date(c.dvenccuo) < new Date();
  });
  const anulada = ["anulada", "anulado"].includes((f.estado_sifen ?? f.estado ?? "").toLowerCase());

  let estadoLabel, estadoColor;
  if (anulada) {
    estadoLabel = "Anulada"; estadoColor = "error";
  } else if (!credito) {
    estadoLabel = "Pagada"; estadoColor = "success";
  } else if (cuotasTotal === 0) {
    estadoLabel = "Pendiente"; estadoColor = "warning";
  } else if (cuotasPagadas === cuotasTotal) {
    estadoLabel = "Pagada"; estadoColor = "success";
  } else if (tieneVencidas) {
    estadoLabel = "Vencida"; estadoColor = "error";
  } else if (cuotasPagadas > 0) {
    estadoLabel = "Parcial"; estadoColor = "info";
  } else {
    estadoLabel = "Pendiente"; estadoColor = "warning";
  }

  const hasContent = items.length > 0 || credito;

  return (
    <>
      <TableRow
        hover
        sx={{ cursor: hasContent ? "pointer" : "default" }}
        onClick={() => hasContent && setOpen((v) => !v)}
      >
        <TableCell sx={{ pr: 0, width: 24 }}>
          {hasContent && <Icon icon={open ? "mdi:chevron-up" : "mdi:chevron-down"} width={16} />}
        </TableCell>
        <TableCell>
          <Stack direction="row" spacing={0.8} alignItems="center" flexWrap="wrap">
            <Typography variant="body2" fontFamily="monospace">{numFactura}</Typography>
            {credito && (
              <Chip size="small" label="Crédito" color="info" variant="outlined" sx={{ fontSize: "0.6rem", height: 18 }} />
            )}
            {credito && cuotasTotal > 0 && (
              <Chip
                size="small"
                label={`${cuotasPagadas}/${cuotasTotal} cuotas`}
                color={tieneVencidas ? "error" : cuotasPagadas === cuotasTotal ? "success" : "default"}
                variant="outlined"
                sx={{ fontSize: "0.6rem", height: 18 }}
              />
            )}
            {credito && (() => {
              const freq = getFrecuenciaFactura(f);
              return freq ? (
                <Chip
                  size="small"
                  label={freq.label}
                  variant="outlined"
                  sx={{ fontSize: "0.6rem", height: 18 }}
                />
              ) : null;
            })()}
          </Stack>
          <Typography variant="caption" color="text.secondary">{fmtFecha(fecha)}</Typography>
          {(() => {
            const ult = ultimoPagoFechaFactura(f);
            return ult ? (
              <Typography variant="caption" color="success.main" display="block" sx={{ lineHeight: 1.2 }}>
                <Icon icon="mdi:cash-check" width={11} style={{ verticalAlign: "middle", marginRight: 2 }} />
                Último pago: {fmtFecha(ult)}
              </Typography>
            ) : null;
          })()}
        </TableCell>
        <TableCell align="center">
          <Chip size="small" label={estadoLabel} color={estadoColor} variant="outlined" sx={{ fontSize: "0.68rem" }} />
        </TableCell>
        <TableCell align="right">
          <Typography variant="body2" fontWeight={600}>{fmtGs(total)} Gs.</Typography>
        </TableCell>
        <TableCell align="right">
          <Typography
            variant="body2"
            fontWeight={700}
            color={saldo > 0 ? "error.main" : "success.main"}
          >
            {fmtGs(saldo)} Gs.
          </Typography>
        </TableCell>
      </TableRow>

      {hasContent && (
        <TableRow>
          <TableCell colSpan={5} sx={{ p: 0, border: 0 }}>
            <Collapse in={open} unmountOnExit>
              {credito && <CreditoDetalle f={f} />}
              {items.length > 0 && (
                <>
                  {credito && <Divider />}
                  <ItemsDetalle items={items} />
                </>
              )}
            </Collapse>
          </TableCell>
        </TableRow>
      )}
    </>
  );
};

// ── Panel principal ───────────────────────────────────────────────────────────
const FacturasPanel = ({ clienteId }) => {
  const { data, isLoading, error } = useQuery({
    queryKey: ["cliente-facturas", clienteId],
    queryFn: () => getFacturas({ clienteId, limit: 50 }),
    enabled: !!clienteId,
  });

  const facturas = data?.items ?? data?.data ?? (Array.isArray(data) ? data : []);

  if (isLoading) return (
    <Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
      <CircularProgress size={32} />
    </Box>
  );
  if (error) return <Alert severity="error" sx={{ m: 2 }}>Error cargando facturas</Alert>;
  if (facturas.length === 0) return (
    <Box sx={{ textAlign: "center", py: 4 }}>
      <Icon icon="mdi:receipt-text-outline" width={40} color="#94a3b8" />
      <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>Sin facturas registradas</Typography>
    </Box>
  );

  const totalFacturado = facturas.reduce((s, f) => s + getFacturaTotal(f), 0);
  const conDeuda = facturas.filter((f) => esCredito(f) && (f.factura_cuotas ?? []).some(
    (c) => c.estado !== "pagado" && c.estado !== "Pagado"
  ));
  const saldoTotal = facturas.reduce((s, f) => s + saldoPendienteFactura(f), 0);
  const atraso = atrasoPromedioDias(facturas);
  const atrasoColor = atraso == null ? "text.secondary" : atraso <= 0 ? "success.main" : atraso <= 7 ? "info.main" : atraso <= 30 ? "warning.main" : "error.main";
  const atrasoLabel = atraso == null
    ? "Sin pagos"
    : atraso <= 0 ? `Puntual (${-atraso}d antes)` : `+${atraso}d atraso`;
  const frecuencia = getFrecuenciaAggregada(facturas);
  const frecuenciaColor = FRECUENCIA_COLOR[frecuencia.kind] ?? "text.primary";

  return (
    <Box>
      <Stack direction="row" spacing={1.5} sx={{ p: 2, bgcolor: "background.default", flexWrap: "wrap", rowGap: 1.5 }}>
        <Paper variant="outlined" sx={{ flex: "1 1 30%", minWidth: 110, p: 1.25, textAlign: "center" }}>
          <Typography variant="caption" color="text.secondary" display="block">Facturas</Typography>
          <Typography variant="h6" fontWeight={700}>{facturas.length}</Typography>
        </Paper>
        <Paper variant="outlined" sx={{ flex: "1 1 30%", minWidth: 110, p: 1.25, textAlign: "center" }}>
          <Typography variant="caption" color="text.secondary" display="block">Total facturado</Typography>
          <Typography variant="body2" fontWeight={700}>{fmtGs(totalFacturado)} Gs.</Typography>
        </Paper>
        <Paper variant="outlined" sx={{ flex: "1 1 30%", minWidth: 110, p: 1.25, textAlign: "center", borderColor: saldoTotal > 0 ? "warning.main" : undefined }}>
          <Typography variant="caption" color={saldoTotal > 0 ? "warning.main" : "text.secondary"} display="block">Saldo pendiente</Typography>
          <Typography variant="body2" fontWeight={700} color={saldoTotal > 0 ? "warning.main" : "text.primary"}>
            {fmtGs(saldoTotal)} Gs.
          </Typography>
        </Paper>
        {conDeuda.length > 0 && (
          <Paper variant="outlined" sx={{ flex: "1 1 30%", minWidth: 110, p: 1.25, textAlign: "center", borderColor: "warning.main" }}>
            <Typography variant="caption" color="warning.main" display="block">Facturas con deuda</Typography>
            <Typography variant="body2" fontWeight={700} color="warning.main">{conDeuda.length}</Typography>
          </Paper>
        )}
        <Paper variant="outlined" sx={{ flex: "1 1 30%", minWidth: 110, p: 1.25, textAlign: "center" }}>
          <Typography variant="caption" color="text.secondary" display="block">Comportamiento</Typography>
          <Typography variant="body2" fontWeight={700} sx={{ color: atrasoColor }}>{atrasoLabel}</Typography>
        </Paper>
        <Paper variant="outlined" sx={{ flex: "1 1 30%", minWidth: 110, p: 1.25, textAlign: "center" }}>
          <Typography variant="caption" color="text.secondary" display="block">Periodicidad</Typography>
          <Typography variant="body2" fontWeight={700} sx={{ color: frecuenciaColor }}>{frecuencia.label}</Typography>
        </Paper>
      </Stack>
      <Divider />
      <Table size="small">
        <TableHead>
          <TableRow sx={{ bgcolor: "action.hover" }}>
            <TableCell sx={{ width: 24 }} />
            <TableCell sx={{ fontWeight: 600, fontSize: "0.78rem" }}>Factura / Fecha</TableCell>
            <TableCell sx={{ fontWeight: 600, fontSize: "0.78rem" }} align="center">Estado</TableCell>
            <TableCell sx={{ fontWeight: 600, fontSize: "0.78rem" }} align="right">Total</TableCell>
            <TableCell sx={{ fontWeight: 600, fontSize: "0.78rem" }} align="right">Saldo</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {facturas.map((f) => <FacturaRow key={f.id} f={f} />)}
        </TableBody>
      </Table>
    </Box>
  );
};

// ── Drawer ────────────────────────────────────────────────────────────────────
export const ClienteHistorialDrawer = ({ cliente, onClose }) => {
  const [pdfOpen, setPdfOpen] = useState(false);

  const clienteId = cliente?.id;
  const nombre = cliente?.personas?.razon_social ?? "Cliente";
  const doc = cliente?.personas?.ruc
    ? `${cliente.personas.ruc}-${cliente.personas.dv ?? 0}`
    : cliente?.personas?.nro_documento ?? "";

  if (!cliente) return null;

  const handleOpenPdf = () => setPdfOpen(true);

  // Stack ARRIBA de Dialogs (default modal = 1300) para poder abrirlo desde adentro
  // de un diálogo sin que el click en su backdrop cierre el diálogo subyacente.
  // Se eleva vía theme (y no con sx en este Drawer) para que el expediente de mora,
  // el timeline de gestiones y sus diálogos internos hereden la misma elevación.
  return (
    <ElevarModales por={10}>
    <Drawer
      anchor="right"
      open={!!cliente}
      onClose={onClose}
      PaperProps={{ sx: { width: { xs: "100vw", sm: 560 }, display: "flex", flexDirection: "column" } }}
    >
      <Box sx={{ px: 2.5, py: 2, display: "flex", alignItems: "center", gap: 1.5, bgcolor: "background.default", borderBottom: "1px solid", borderColor: "divider", flexShrink: 0 }}>
        <Icon icon="mdi:account-details-outline" width={22} color="#60a5fa" />
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <Typography variant="subtitle1" fontWeight={700} noWrap>{nombre}</Typography>
          {doc && <Typography variant="caption" color="text.secondary">{doc}</Typography>}
        </Box>
        <Button
          size="small"
          variant="outlined"
          color="primary"
          startIcon={<Icon icon="mdi:printer-outline" width={16} />}
          onClick={handleOpenPdf}
          sx={{ textTransform: "none", fontWeight: 600 }}
        >
          Estado de cuenta
        </Button>
        <IconButton size="small" onClick={onClose}>
          <Icon icon="mdi:close" width={18} />
        </IconButton>
      </Box>
      <Box sx={{ flex: 1, overflow: "auto" }}>
        <MoraGestionActivaCard clienteId={cliente.id} />
        <RefinanciacionesCard clienteId={cliente.id} />
        <GestionesTimelineCard clienteId={cliente.id} />
        <FacturasPanel clienteId={cliente.id} />
      </Box>

      <EstadoCuentaPdfModal
        open={pdfOpen}
        clienteId={clienteId}
        nombre={nombre}
        onClose={() => setPdfOpen(false)}
      />
    </Drawer>
    </ElevarModales>
  );
};
