import { Icon } from "@iconify/react";
import { Alert, Autocomplete, Button, Chip, Collapse, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControl, IconButton, InputLabel, ListItemIcon, ListItemText, Menu, MenuItem, Popover, Select, TextField, Tooltip, Typography } from "@mui/material";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import styled from "styled-components";
import { usePermission } from "../../hooks/usePermission";
import { MonedaInput } from "../common/MonedaInput";
import { PorQueEstaCuenta } from "./PorQueEstaCuenta";
import { TablePaginationBar } from "../_standards";
import { hoyISO } from "../../utils/fecha";
import {
  useAsientosQuery,
  useConfirmarAsientoMutation,
  useCorregirAsientoMutation,
  useCrearAsientoMutation,
  useEditarAsientoMutation,
  useEjerciciosQuery,
  useEliminarAsientoMutation,
  usePeriodosQuery,
  usePlanCuentasQuery,
  useRevertirAsientoMutation,
  useCentrosCostoQuery,
  useTiposCambioQuery,
} from "../../tanstack/ContabilidadStack";

const MONEDAS_EXTRA = ["USD", "BRL", "ARS", "EUR"];

const fmtGs = (v) => `Gs. ${Number(v || 0).toLocaleString("es-PY", { maximumFractionDigits: 0 })}`;
const fmtDate = (d) => {
  if (!d) return "—";
  const s = (typeof d === "string" ? d : new Date(d).toISOString()).substring(0, 10);
  const [y, m, day] = s.split("-");
  return `${+day}/${+m}/${y}`;
};
const today = () => hoyISO();

const ESTADO_STYLE = {
  BORRADOR: { bg: "#f59e0b22", color: "#f59e0b" },
  CONFIRMADO: { bg: "#22c55e22", color: "#22c55e" },
  REVERTIDO: { bg: "#ef444422", color: "#ef4444" },
};

const MESES = ["", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];

function EstadoChip({ estado }) {
  const s = ESTADO_STYLE[estado] || { bg: "#64748b22", color: "#94a3b8" };
  return <Chip label={estado} size="small" sx={{ background: s.bg, color: s.color, fontWeight: 700, fontSize: 10 }} />;
}

function LineaRow({ linea, index, cuentas, centros, moneda, onUpdate, onRemove }) {
  const cuentasMovimiento = cuentas.filter((c) => c.acepta_movimientos);
  const cuentaSeleccionada = cuentasMovimiento.find((c) => c.id === linea.cuenta_id) || null;
  const simbolo = moneda === "PYG" ? "Gs" : moneda;

  return (
    <LinRow>
      <LineaNum>{index + 1}</LineaNum>
      <Autocomplete
        size="small"
        options={cuentasMovimiento}
        value={cuentaSeleccionada}
        getOptionLabel={(c) => `${c.codigo} — ${c.descripcion}`}
        onChange={(_, val) => onUpdate(index, "cuenta_id", val?.id || "")}
        renderOption={(props, c) => (
          <li {...props} key={c.id}>
            <span style={{ color: "#f88533", fontWeight: 700, marginRight: 10, minWidth: 72, fontFamily: "monospace", fontSize: 12 }}>{c.codigo}</span>
            <span style={{ fontSize: 13 }}>{c.descripcion}</span>
          </li>
        )}
        renderInput={(params) => <TextField {...params} label="Cuenta *" placeholder="Buscar por código o nombre…" sx={{ "& .MuiOutlinedInput-root": { borderRadius: "8px" } }} />}
        noOptionsText="Sin resultados"
        sx={{ flex: 2, minWidth: 220 }}
        filterOptions={(opts, { inputValue }) => {
          const q = inputValue.toLowerCase();
          return opts.filter((c) => c.codigo.toLowerCase().includes(q) || c.descripcion.toLowerCase().includes(q));
        }}
      />
      <TextField size="small" label="Descripción" sx={{ flex: 1.5 }} value={linea.descripcion} onChange={(e) => onUpdate(index, "descripcion", e.target.value)} />
      <MonedaInput label={`Debe (${simbolo})`} sx={{ flex: 1 }} value={linea.debe_moneda} onChange={(v) => onUpdate(index, "debe_moneda", v)} moneda={moneda} disabled={linea.haber_moneda > 0} />
      <MonedaInput label={`Haber (${simbolo})`} sx={{ flex: 1 }} value={linea.haber_moneda} onChange={(v) => onUpdate(index, "haber_moneda", v)} moneda={moneda} disabled={linea.debe_moneda > 0} />
      {centros.length > 0 && (
        <FormControl size="small" sx={{ minWidth: 140, flex: 1 }}>
          <InputLabel sx={{ fontSize: 12 }}>C. Costo</InputLabel>
          <Select label="C. Costo" value={linea.centro_costo_id || ""} onChange={(e) => onUpdate(index, "centro_costo_id", e.target.value || null)} sx={{ fontSize: 12 }}>
            <MenuItem value="">
              <em>Ninguno</em>
            </MenuItem>
            {centros
              .filter((c) => c.activo)
              .map((c) => (
                <MenuItem key={c.id} value={c.id} sx={{ fontSize: 12 }}>
                  {c.codigo} — {c.descripcion}
                </MenuItem>
              ))}
          </Select>
        </FormControl>
      )}
      <Tooltip title="Eliminar línea">
        <RemoveBtn onClick={() => onRemove(index)}>
          <Icon icon="lucide:trash-2" />
        </RemoveBtn>
      </Tooltip>
    </LinRow>
  );
}

const COL_DEFAULTS = [60, 90, 280, 110, 120, 140, 140, 150];

function useResizableColumns(defaults) {
  const [widths, setWidths] = useState(defaults);
  const drag = useRef(null);

  const onMouseDown = useCallback(
    (colIdx, e) => {
      e.preventDefault();
      drag.current = { colIdx, startX: e.clientX, startW: widths[colIdx] };
    },
    [widths],
  );

  useEffect(() => {
    const onMove = (e) => {
      if (!drag.current) return;
      const { colIdx, startX, startW } = drag.current;
      setWidths((w) => {
        const n = [...w];
        n[colIdx] = Math.max(40, startW + e.clientX - startX);
        return n;
      });
    };
    const onUp = () => {
      drag.current = null;
    };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
    };
  }, []);

  return { widths, onMouseDown };
}

export function AsientosTab() {
  const { can } = usePermission("CONTABILIDAD");
  const { widths, onMouseDown } = useResizableColumns(COL_DEFAULTS);
  const { data: ejercicios = [] } = useEjerciciosQuery();
  const [ejFiltro, setEjFiltro] = useState("");
  const [perFiltro, setPerFiltro] = useState("");
  const [estadoFiltro, setEstadoFiltro] = useState("");
  const [desde, setDesde] = useState("");
  const [hasta, setHasta] = useState("");
  // Paginación: antes se pedían 50 fijos y un mes con más asientos solo mostraba
  // los últimos días (el listado viene ordenado por fecha descendente).
  const [page, setPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState(50);
  const [expanded, setExpanded] = useState({});
  const [revertirConfirm, setRevertirConfirm] = useState(null);
  const [eliminarConfirm, setEliminarConfirm] = useState(null);
  const [menuState, setMenuState] = useState({ anchor: null, asiento: null });
  const [helpAnchor, setHelpAnchor] = useState(null);
  const [openNew, setOpenNew] = useState(false);
  // Asiento a editar: BORRADOR (Editar) o CONFIRMADO (Corregir, en el lugar).
  const [editTarget, setEditTarget] = useState(null);
  const [editForm, setEditForm] = useState({ glosa: "", fecha: "", lineas: [] });

  const { data: periodos = [] } = usePeriodosQuery(ejFiltro || undefined);
  const { data: planCuentas = [] } = usePlanCuentasQuery();

  const anioActual = new Date().getFullYear();
  const mesActual = new Date().getMonth() + 1; // 1-12
  const autoInitDone = useRef(false);

  // Auto-seleccionar ejercicio del año actual (solo en la primera carga)
  useEffect(() => {
    if (autoInitDone.current || ejercicios.length === 0) return;
    const ejActual = ejercicios.find((e) => e.anio === anioActual);
    if (ejActual) setEjFiltro(ejActual.id);
  }, [ejercicios]);

  // Auto-seleccionar período del mes actual una vez cargados los períodos del ejercicio actual
  useEffect(() => {
    if (autoInitDone.current || periodos.length === 0) return;
    const perActual = periodos.find((p) => p.mes === mesActual);
    if (perActual) {
      setPerFiltro(perActual.id);
      autoInitDone.current = true;
    }
  }, [periodos]);

  const filters = useMemo(
    () => ({
      periodoId: perFiltro || undefined,
      estado: estadoFiltro || undefined,
      desde: desde || undefined,
      hasta: hasta || undefined,
      skip: (page - 1) * rowsPerPage,
      take: rowsPerPage,
    }),
    [perFiltro, estadoFiltro, desde, hasta, page, rowsPerPage],
  );

  // Cualquier cambio de filtro vuelve a la primera página.
  useEffect(() => {
    setPage(1);
  }, [perFiltro, estadoFiltro, desde, hasta]);

  const { data: asientosData, isLoading, refetch } = useAsientosQuery(filters);
  const asientos = asientosData?.data || [];
  const total = asientosData?.total || 0;

  const confirmarMutation = useConfirmarAsientoMutation();
  const revertirMutation = useRevertirAsientoMutation();
  const eliminarMutation = useEliminarAsientoMutation();
  const crearMutation = useCrearAsientoMutation();
  const editarMutation = useEditarAsientoMutation();

  const closeMenu = () => setMenuState({ anchor: null, asiento: null });

  const corregirMutation = useCorregirAsientoMutation();
  const { data: centros = [] } = useCentrosCostoQuery();

  const LINEA_VACIA = { cuenta_id: "", descripcion: "", debe_moneda: 0, haber_moneda: 0, centro_costo_id: null };

  // Form nuevo asiento
  const [form, setForm] = useState({
    fecha: today(),
    periodo_id: "",
    glosa: "",
    moneda_origen: "PYG",
    lineas: [{ ...LINEA_VACIA }, { ...LINEA_VACIA }],
  });

  const { data: tiposCambio = [] } = useTiposCambioQuery(form.moneda_origen !== "PYG" ? form.moneda_origen : undefined);
  const tasaHoy = useMemo(() => {
    if (form.moneda_origen === "PYG") return null;
    return tiposCambio.find((t) => t.moneda === form.moneda_origen) ?? null;
  }, [tiposCambio, form.moneda_origen]);

  const totalDebe = form.lineas.reduce((s, l) => s + (Number(l.debe_moneda) || 0), 0);
  const totalHaber = form.lineas.reduce((s, l) => s + (Number(l.haber_moneda) || 0), 0);
  const tolerancia = form.moneda_origen === "PYG" ? 1 : 0.01;
  const balanceado = Math.abs(totalDebe - totalHaber) <= tolerancia && totalDebe > 0;

  const periodosAbiertos = periodos.filter((p) => p.estado === "ABIERTO" || p.estado === "AJUSTE");

  const updateLinea = (i, key, val) =>
    setForm((f) => {
      const lineas = [...f.lineas];
      lineas[i] = { ...lineas[i], [key]: val };
      // Clear the opposite field
      if (key === "debe_moneda" && val > 0) lineas[i].haber_moneda = 0;
      if (key === "haber_moneda" && val > 0) lineas[i].debe_moneda = 0;
      return { ...f, lineas };
    });

  const addLinea = () => setForm((f) => ({ ...f, lineas: [...f.lineas, { ...LINEA_VACIA }] }));
  const removeLinea = (i) => setForm((f) => ({ ...f, lineas: f.lineas.filter((_, idx) => idx !== i) }));

  const handleOpenEdit = (asiento) => {
    setEditTarget(asiento);
    setEditForm({
      glosa: asiento.glosa || "",
      fecha: typeof asiento.fecha === "string" ? asiento.fecha.substring(0, 10) : new Date(asiento.fecha).toISOString().substring(0, 10),
      lineas: (asiento.lineas || []).map((l) => ({
        cuenta_id: l.cuenta_id,
        descripcion: l.descripcion || "",
        debe_moneda: Number(l.debe_moneda) || 0,
        haber_moneda: Number(l.haber_moneda) || 0,
        centro_costo_id: l.centro_costo_id || null,
      })),
    });
  };

  const updateEditLinea = (i, key, val) =>
    setEditForm((f) => {
      const lineas = [...f.lineas];
      lineas[i] = { ...lineas[i], [key]: val };
      if (key === "debe_moneda" && val > 0) lineas[i].haber_moneda = 0;
      if (key === "haber_moneda" && val > 0) lineas[i].debe_moneda = 0;
      return { ...f, lineas };
    });

  const handleGuardarEdit = () => {
    if (!editTarget) return;
    const payload = { ...editForm, lineas: editForm.lineas.filter((l) => l.cuenta_id) };
    const mutation = editTarget.estado === "CONFIRMADO" ? corregirMutation : editarMutation;
    mutation.mutate({ id: editTarget.id, data: payload }, { onSuccess: () => setEditTarget(null) });
  };

  const handleCrear = (confirmar = false) => {
    const payload = { ...form, lineas: form.lineas.filter((l) => l.cuenta_id) };
    crearMutation.mutate(payload, {
      onSuccess: (data) => {
        if (confirmar && data?.id) confirmarMutation.mutate(data.id);
        setOpenNew(false);
        resetForm();
      },
    });
  };

  const resetForm = () =>
    setForm({
      fecha: today(),
      periodo_id: "",
      glosa: "",
      moneda_origen: "PYG",
      lineas: [{ ...LINEA_VACIA }, { ...LINEA_VACIA }],
    });

  return (
    <Wrapper>
      <TopBar>
        <PageTitle>
          <Icon icon="lucide:book-open-text" /> Asientos Contables
          <Tooltip title="Ayuda sobre flujo de asientos">
            <IconButton size="small" onClick={(e) => setHelpAnchor(e.currentTarget)} sx={{ ml: 0.5, color: "#94a3b8", "&:hover": { color: "#f88533" } }}>
              <Icon icon="lucide:info" width={16} />
            </IconButton>
          </Tooltip>
        </PageTitle>

        <Popover
          open={Boolean(helpAnchor)}
          anchorEl={helpAnchor}
          onClose={() => setHelpAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
          transformOrigin={{ vertical: "top", horizontal: "left" }}
          PaperProps={{ sx: { p: 2.5, maxWidth: 420, borderRadius: "12px", background: "#1e293b", border: "1px solid #334155" } }}
        >
          <Typography variant="subtitle2" sx={{ color: "#f88533", mb: 1.5, display: "flex", alignItems: "center", gap: 1 }}>
            <Icon icon="lucide:book-open-text" width={15} /> Flujo de asientos contables
          </Typography>
          <Typography variant="body2" sx={{ color: "#cbd5e1", mb: 1.5, lineHeight: 1.7 }}>
            Los asientos pasan por tres estados: <strong style={{ color: "#f59e0b" }}>Borrador</strong> →{" "}
            <strong style={{ color: "#22c55e" }}>Confirmado</strong> →{" "}
            <strong style={{ color: "#ef4444" }}>Revertido</strong>.
          </Typography>
          <Typography variant="body2" sx={{ color: "#94a3b8", mb: 1, lineHeight: 1.7 }}>
            <strong style={{ color: "#e2e8f0" }}>Revertir</strong> — genera un asiento de reversión con los montos invertidos en el período activo actual, neutralizando el asiento original. El original queda marcado como <em>Revertido</em>.
          </Typography>
          <Typography variant="body2" sx={{ color: "#94a3b8", mb: 1, lineHeight: 1.7 }}>
            <strong style={{ color: "#3b82f6" }}>Corregir asiento</strong> — abre el asiento confirmado para editar sus cuentas, montos, fecha o glosa. Los cambios quedan en el mismo asiento (mismo número, sigue confirmado), sin asiento espejo. Cómo estaba antes queda en la auditoría. Solo se puede si su período está abierto; si está cerrado, usá Revertir.
          </Typography>
          <Typography variant="body2" sx={{ color: "#64748b", lineHeight: 1.7, borderTop: "1px solid #334155", pt: 1, mt: 0.5 }}>
            ⚠ Las reversiones siempre se asignan al <strong style={{ color: "#64748b" }}>período abierto actual</strong>. Si no hay período abierto, la operación será bloqueada.
          </Typography>
        </Popover>

        {can("CONT_ASI_ASIENTO_CREAR") && (
          <Button variant="contained" startIcon={<Icon icon="lucide:plus" />} onClick={() => setOpenNew(true)} sx={{ background: "#f88533", "&:hover": { background: "#e07320" } }}>
            Nuevo Asiento
          </Button>
        )}
      </TopBar>

      {/* Filtros */}
      <FiltersBar>
        <FormControl size="small" sx={{ minWidth: 120 }}>
          <InputLabel>Ejercicio</InputLabel>
          <Select
            label="Ejercicio"
            value={ejFiltro}
            onChange={(e) => {
              setEjFiltro(e.target.value);
              setPerFiltro("");
            }}
          >
            <MenuItem value="">Todos</MenuItem>
            {ejercicios.map((e) => (
              <MenuItem key={e.id} value={e.id}>
                {e.anio}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <FormControl size="small" sx={{ minWidth: 160 }}>
          <InputLabel>Período</InputLabel>
          <Select
            label="Período"
            value={perFiltro}
            onChange={(e) => {
              // Período y fechas se excluyen: elegir uno limpia el otro.
              setPerFiltro(e.target.value);
              setDesde("");
              setHasta("");
            }}
            disabled={!ejFiltro}
          >
            <MenuItem value="">Todos los períodos</MenuItem>
            {periodos.map((p) => (
              <MenuItem key={p.id} value={p.id}>
                {MESES[p.mes]} {p.anio}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <FormControl size="small" sx={{ minWidth: 140 }}>
          <InputLabel>Estado</InputLabel>
          <Select label="Estado" value={estadoFiltro} onChange={(e) => setEstadoFiltro(e.target.value)}>
            <MenuItem value="">Todos</MenuItem>
            <MenuItem value="BORRADOR">Borrador</MenuItem>
            <MenuItem value="CONFIRMADO">Confirmado</MenuItem>
            <MenuItem value="REVERTIDO">Revertido</MenuItem>
          </Select>
        </FormControl>
        {/* Cargar fechas limpia el período: si quedaban los dos, se aplicaban juntos
            y un rango fuera del período elegido devolvía la lista vacía. */}
        <TextField size="small" label="Desde" type="date" value={desde} onChange={(e) => { setDesde(e.target.value); setPerFiltro(""); }} InputLabelProps={{ shrink: true }} />
        <TextField size="small" label="Hasta" type="date" value={hasta} onChange={(e) => { setHasta(e.target.value); setPerFiltro(""); }} InputLabelProps={{ shrink: true }} />
        <Button variant="outlined" startIcon={<Icon icon="lucide:search" />} onClick={() => refetch()}>
          Buscar
        </Button>
        {(ejFiltro || perFiltro || estadoFiltro || desde || hasta) && (
          <Button
            size="small"
            onClick={() => {
              setEjFiltro("");
              setPerFiltro("");
              setEstadoFiltro("");
              setDesde("");
              setHasta("");
            }}
          >
            Limpiar
          </Button>
        )}
        <TotalCount>{total} asientos</TotalCount>
      </FiltersBar>

      {/* Tabla */}
      <TableWrap>
        {isLoading ? (
          <LoadRow>
            <Icon icon="lucide:loader-2" className="spin" /> Cargando asientos…
          </LoadRow>
        ) : asientos.length === 0 ? (
          <EmptyRow>
            <Icon icon="lucide:inbox" />
            <span>Sin asientos en el período seleccionado</span>
          </EmptyRow>
        ) : (
          <Table>
            <colgroup>
              {widths.map((w, i) => (
                <col key={i} style={{ width: w }} />
              ))}
            </colgroup>
            <thead>
              <tr>
                {["N°", "Fecha", "Glosa", "Período", "Estado", "Debe", "Haber", "Acciones"].map((label, i) => (
                  <Th key={i} align={i >= 5 && i <= 6 ? "right" : "left"}>
                    {label}
                    {i < 7 && <ResizeHandle onMouseDown={(e) => onMouseDown(i, e)} />}
                  </Th>
                ))}
              </tr>
            </thead>
            <tbody>
              {asientos.map((a) => (
                <>
                  <Tr key={a.id} $clickable onClick={() => setExpanded((p) => ({ ...p, [a.id]: !p[a.id] }))}>
                    <Td>
                      <strong>#{a.numero}</strong>
                    </Td>
                    <Td>{fmtDate(a.fecha)}</Td>
                    <Td>
                      <GlosaTxt>{a.glosa || "—"}</GlosaTxt>
                      {a.moneda_origen && a.moneda_origen !== "PYG" && <MonedaBadge>{a.moneda_origen}</MonedaBadge>}
                    </Td>
                    <Td style={{ fontSize: 12, color: "#64748b" }}>{a.periodo?.mes ? `${MESES[a.periodo.mes]} ${a.periodo.anio}` : "—"}</Td>
                    <Td>
                      <EstadoChip estado={a.estado} />
                    </Td>
                    <Td align="right">
                      <DebeAmt>{fmtGs(a.total_debe_pyg)}</DebeAmt>
                    </Td>
                    <Td align="right">
                      <HaberAmt>{fmtGs(a.total_haber_pyg)}</HaberAmt>
                    </Td>
                    <Td onClick={(e) => e.stopPropagation()}>
                      <RowActions>
                        {/* Expand toggle */}
                        <ExpandIconSm $open={!!expanded[a.id]}>
                          <Icon icon="lucide:chevron-down" />
                        </ExpandIconSm>

                        {/* Dropdown de acciones */}
                        <Tooltip title="Acciones">
                          <IconButton
                            size="small"
                            onClick={(e) => setMenuState({ anchor: e.currentTarget, asiento: a })}
                            sx={{ color: "text.secondary" }}
                          >
                            <Icon icon="lucide:more-vertical" width={16} />
                          </IconButton>
                        </Tooltip>
                      </RowActions>
                    </Td>
                  </Tr>
                  {expanded[a.id] && (
                    <tr key={`${a.id}-detail`}>
                      <Td colSpan={8} style={{ padding: 0 }}>
                        <Collapse in>
                          <LineasDetail>
                            <LineasTable>
                              <thead>
                                <tr>
                                  <LinTh>#</LinTh>
                                  <LinTh>Código</LinTh>
                                  <LinTh>Cuenta</LinTh>
                                  <LinTh>Descripción</LinTh>
                                  <LinTh>C. Costo</LinTh>
                                  <LinTh align="right">Debe</LinTh>
                                  <LinTh align="right">Haber</LinTh>
                                  {/* Solo los asientos automáticos tienen de dónde salió la cuenta. */}
                                  {a.documento && <LinTh aria-label="¿Por qué esta cuenta?" />}
                                </tr>
                              </thead>
                              <tbody>
                                {(a.lineas || []).map((l, i) => (
                                  <tr key={i}>
                                    <LinTd>{l.orden}</LinTd>
                                    <LinTd style={{ color: "#f88533", fontWeight: 700 }}>{l.cuenta?.codigo}</LinTd>
                                    <LinTd>{l.cuenta?.descripcion}</LinTd>
                                    <LinTd style={{ color: "#64748b" }}>{l.descripcion || "—"}</LinTd>
                                    <LinTd style={{ color: "#64748b", fontSize: 11 }}>{l.centro_costo ? `${l.centro_costo.codigo}` : "—"}</LinTd>
                                    <LinTd align="right">{l.debe_pyg > 0 ? fmtGs(l.debe_pyg) : ""}</LinTd>
                                    <LinTd align="right">{l.haber_pyg > 0 ? fmtGs(l.haber_pyg) : ""}</LinTd>
                                    {a.documento && (
                                      <LinTd align="right" style={{ width: 36 }}>
                                        <PorQueEstaCuenta asientoId={a.id} lineaId={l.id} />
                                      </LinTd>
                                    )}
                                  </tr>
                                ))}
                              </tbody>
                            </LineasTable>
                            {a.documento && (
                              <DocRef>
                                <Icon icon="lucide:link" />
                                {a.documento.tipo} — {a.documento.numero_documento}
                              </DocRef>
                            )}
                          </LineasDetail>
                        </Collapse>
                      </Td>
                    </tr>
                  )}
                </>
              ))}
            </tbody>
          </Table>
        )}
      </TableWrap>

      <TablePaginationBar
        page={page}
        totalPages={Math.max(1, Math.ceil(total / rowsPerPage))}
        onPageChange={setPage}
        total={total}
        shown={asientos.length}
        noun="asientos"
        rowsPerPage={rowsPerPage}
        onRowsPerPageChange={(n) => {
          setRowsPerPage(n);
          setPage(1);
        }}
        rowsPerPageOptions={[50, 100, 200]}
      />

      {/* ── Dropdown de acciones ───────────────────────────────────────────── */}
      <Menu
        anchorEl={menuState.anchor}
        open={Boolean(menuState.anchor)}
        onClose={closeMenu}
        PaperProps={{ sx: { minWidth: 200, borderRadius: "10px" } }}
      >
        {menuState.asiento?.estado === "BORRADOR" && (can("CONT_ASI_ASIENTO_EDITAR") || can("CONT_ASI_ASIENTO_CONFIRMAR") || can("CONT_ASI_ASIENTO_ELIMINAR")) && [
          can("CONT_ASI_ASIENTO_EDITAR") && (
            <MenuItem key="editar" onClick={() => { handleOpenEdit(menuState.asiento); closeMenu(); }}>
              <ListItemIcon><Icon icon="lucide:pencil" width={16} /></ListItemIcon>
              <ListItemText>Editar</ListItemText>
            </MenuItem>
          ),
          can("CONT_ASI_ASIENTO_CONFIRMAR") && (
            <MenuItem key="confirmar" onClick={() => { confirmarMutation.mutate(menuState.asiento.id); closeMenu(); }}>
              <ListItemIcon><Icon icon="lucide:check-circle" width={16} style={{ color: "#22c55e" }} /></ListItemIcon>
              <ListItemText>Confirmar</ListItemText>
            </MenuItem>
          ),
          can("CONT_ASI_ASIENTO_ELIMINAR") && <Divider key="div1" />,
          can("CONT_ASI_ASIENTO_ELIMINAR") && (
            <MenuItem key="eliminar" onClick={() => { setEliminarConfirm(menuState.asiento); closeMenu(); }} sx={{ color: "#ef4444" }}>
              <ListItemIcon><Icon icon="lucide:trash-2" width={16} style={{ color: "#ef4444" }} /></ListItemIcon>
              <ListItemText>Eliminar</ListItemText>
            </MenuItem>
          ),
        ]}

        {menuState.asiento?.estado === "CONFIRMADO" && can("CONT_ASI_ASIENTO_REVERTIR") && [
          <MenuItem key="revertir" onClick={() => { setRevertirConfirm(menuState.asiento); closeMenu(); }}>
            <ListItemIcon><Icon icon="lucide:undo-2" width={16} style={{ color: "#f59e0b" }} /></ListItemIcon>
            <ListItemText>Revertir</ListItemText>
          </MenuItem>,
          <MenuItem
            key="corregir"
            onClick={() => { handleOpenEdit(menuState.asiento); closeMenu(); }}
          >
            <ListItemIcon><Icon icon="lucide:pencil-line" width={16} style={{ color: "#3b82f6" }} /></ListItemIcon>
            <ListItemText
              primary="Corregir asiento"
              secondary="Modifica este mismo asiento"
              secondaryTypographyProps={{ fontSize: 11 }}
            />
          </MenuItem>,
        ]}

        {menuState.asiento?.estado === "REVERTIDO" && (
          <MenuItem disabled>
            <ListItemText secondary="Sin acciones disponibles" />
          </MenuItem>
        )}
      </Menu>

      {/* Dialog Nuevo Asiento */}
      <Dialog
        open={openNew}
        onClose={() => {
          setOpenNew(false);
          resetForm();
        }}
        maxWidth="lg"
        fullWidth
      >
        <DialogTitle>
          <span>Nuevo Asiento Manual</span>
          <span style={{ fontSize: 12, fontWeight: 400, color: "#64748b", marginLeft: 12 }}>Partida doble: Debe = Haber</span>
        </DialogTitle>
        <DialogContent sx={{ pt: "16px !important" }}>
          <FormRow>
            <TextField
              size="small"
              label="Fecha *"
              type="date"
              value={form.fecha}
              onChange={(e) => {
                const nuevaFecha = e.target.value;
                const periodoMatch = periodosAbiertos.find((p) => {
                  const f = new Date(nuevaFecha + "T00:00:00");
                  return f >= new Date(p.fecha_inicio) && f <= new Date(p.fecha_fin);
                });
                setForm((f) => ({ ...f, fecha: nuevaFecha, periodo_id: periodoMatch?.id || f.periodo_id }));
              }}
              InputLabelProps={{ shrink: true }}
            />
            <FormControl size="small" sx={{ minWidth: 200 }}>
              <InputLabel>Período *</InputLabel>
              <Select label="Período *" value={form.periodo_id} onChange={(e) => setForm((f) => ({ ...f, periodo_id: e.target.value }))}>
                {periodosAbiertos.map((p) => (
                  <MenuItem key={p.id} value={p.id}>
                    {MESES[p.mes]} {p.anio}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl size="small" sx={{ minWidth: 140 }}>
              <InputLabel>Moneda</InputLabel>
              <Select
                label="Moneda"
                value={form.moneda_origen}
                onChange={(e) =>
                  setForm((f) => ({
                    ...f,
                    moneda_origen: e.target.value,
                    lineas: f.lineas.map((l) => ({ ...l, debe_moneda: 0, haber_moneda: 0 })),
                  }))
                }
              >
                <MenuItem value="PYG">₲ Guaraní (PYG)</MenuItem>
                {MONEDAS_EXTRA.map((m) => (
                  <MenuItem key={m} value={m}>
                    {m}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <TextField
              size="small"
              label="Glosa / Concepto"
              sx={{ flex: 1 }}
              value={form.glosa}
              onChange={(e) => setForm((f) => ({ ...f, glosa: e.target.value }))}
              placeholder="ej. Pago alquiler oficina"
            />
          </FormRow>
          {(() => {
            if (!form.periodo_id || !form.fecha) return null;
            const per = periodosAbiertos.find((p) => p.id === form.periodo_id);
            if (!per) return null;
            const f = new Date(form.fecha + "T00:00:00");
            const dentro = f >= new Date(per.fecha_inicio) && f <= new Date(per.fecha_fin);
            if (dentro) return null;
            return (
              <Alert severity="warning" sx={{ mt: 1 }}>
                La fecha seleccionada no corresponde al período <strong>{MESES[per.mes]} {per.anio}</strong>. El asiento se registrará en ese período.
              </Alert>
            );
          })()}

          {form.moneda_origen !== "PYG" && (
            <MonedaAlert $hasRate={!!tasaHoy}>
              <Icon icon={tasaHoy ? "lucide:coins" : "lucide:alert-triangle"} />
              {tasaHoy ? (
                <>
                  Importes en <strong>{form.moneda_origen}</strong>. Se convierten a ₲ usando la tasa del {fmtDate(tasaHoy.fecha)}:{" "}
                  <strong>
                    1 {form.moneda_origen} = ₲ {Number(tasaHoy.tasa).toLocaleString("es-PY", { minimumFractionDigits: 2 })}
                  </strong>
                </>
              ) : (
                <>
                  Sin tasa registrada para <strong>{form.moneda_origen}</strong> en la fecha seleccionada. Registrá la tasa en el tab <strong>Tipo de Cambio</strong> antes de guardar.
                </>
              )}
            </MonedaAlert>
          )}

          <LineasHeader>
            <span>Líneas del asiento</span>
            <Button size="small" startIcon={<Icon icon="lucide:plus" />} onClick={addLinea}>
              Agregar línea
            </Button>
          </LineasHeader>

          <LineasWrap>
            {form.lineas.map((linea, i) => (
              <LineaRow key={i} index={i} linea={linea} cuentas={planCuentas} centros={centros} moneda={form.moneda_origen} onUpdate={updateLinea} onRemove={removeLinea} />
            ))}
          </LineasWrap>

          <BalanceBar $ok={balanceado}>
            <BalItem>
              <span>Total DEBE</span>
              <BalNum>{form.moneda_origen === "PYG" ? fmtGs(totalDebe) : `${form.moneda_origen} ${Number(totalDebe).toLocaleString("es-PY", { minimumFractionDigits: 2 })}`}</BalNum>
            </BalItem>
            <BalDivider />
            <BalItem>
              <span>Total HABER</span>
              <BalNum>{form.moneda_origen === "PYG" ? fmtGs(totalHaber) : `${form.moneda_origen} ${Number(totalHaber).toLocaleString("es-PY", { minimumFractionDigits: 2 })}`}</BalNum>
            </BalItem>
            <BalDivider />
            <BalStatus $ok={balanceado}>
              <Icon icon={balanceado ? "lucide:check-circle-2" : "lucide:alert-circle"} />
              {balanceado ? "Balanceado ✓" : `Diferencia: ${Math.abs(totalDebe - totalHaber).toLocaleString("es-PY", { maximumFractionDigits: 2 })} ${form.moneda_origen}`}
            </BalStatus>
          </BalanceBar>

          {!periodosAbiertos.length && (
            <div
              style={{
                marginTop: 12,
                padding: "10px 14px",
                background: "#ef444415",
                border: "1px solid #ef444433",
                borderRadius: 8,
                fontSize: 13,
                color: "#ef4444",
                display: "flex",
                alignItems: "center",
                gap: 8,
              }}
            >
              <Icon icon="lucide:alert-triangle" style={{ width: 16, height: 16, flexShrink: 0 }} />
              No hay períodos abiertos. Creá un ejercicio con períodos para poder registrar asientos.
            </div>
          )}
        </DialogContent>
        <DialogActions sx={{ p: 2, gap: 1 }}>
          <Button
            onClick={() => {
              setOpenNew(false);
              resetForm();
            }}
          >
            Cancelar
          </Button>
          <Button variant="outlined" onClick={() => handleCrear(false)} disabled={!balanceado || !form.periodo_id || crearMutation.isPending || (form.moneda_origen !== "PYG" && !tasaHoy)}>
            Guardar borrador
          </Button>
          <Button
            variant="contained"
            onClick={() => handleCrear(true)}
            disabled={!balanceado || !form.periodo_id || crearMutation.isPending || (form.moneda_origen !== "PYG" && !tasaHoy)}
            sx={{ background: "#f88533", "&:hover": { background: "#e07320" } }}
          >
            {crearMutation.isPending ? "Guardando…" : "Crear y Confirmar"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Editar asiento BORRADOR */}
      {editTarget && (() => {
        const moneda = editTarget.moneda_origen || "PYG";
        const editDebe = editForm.lineas.reduce((s, l) => s + (Number(l.debe_moneda) || 0), 0);
        const editHaber = editForm.lineas.reduce((s, l) => s + (Number(l.haber_moneda) || 0), 0);
        const tol = moneda === "PYG" ? 1 : 0.01;
        const editBalanceado = Math.abs(editDebe - editHaber) <= tol && editDebe > 0;
        return (
          <Dialog open onClose={() => setEditTarget(null)} maxWidth="lg" fullWidth>
            <DialogTitle>
              <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <Icon icon="lucide:pencil" />
                {editTarget.estado === "CONFIRMADO" ? "Corregir" : "Editar"} asiento #{editTarget.numero} — {editTarget.estado}
                {moneda !== "PYG" && <span style={{ fontSize: 11, background: "#f8853322", color: "#f88533", padding: "2px 8px", borderRadius: 4 }}>{moneda}</span>}
              </span>
            </DialogTitle>
            <DialogContent sx={{ pt: "16px !important", display: "flex", flexDirection: "column", gap: 2 }}>
              {editTarget.estado === "CONFIRMADO" && (
                <Alert severity="info" sx={{ py: 0 }}>
                  Los cambios se guardan en este mismo asiento, sin asiento espejo. La fecha tiene que quedar dentro de su período.
                </Alert>
              )}
              <FormRow>
                <TextField size="small" label="Fecha" type="date" value={editForm.fecha}
                  onChange={(e) => setEditForm((f) => ({ ...f, fecha: e.target.value }))}
                  InputLabelProps={{ shrink: true }} sx={{ minWidth: 160 }} />
                <TextField size="small" label="Glosa / Concepto" sx={{ flex: 1 }} value={editForm.glosa}
                  onChange={(e) => setEditForm((f) => ({ ...f, glosa: e.target.value }))} />
              </FormRow>
              <LineasHeader>
                <span>Líneas del asiento</span>
                <Button size="small" startIcon={<Icon icon="lucide:plus" />}
                  onClick={() => setEditForm((f) => ({ ...f, lineas: [...f.lineas, { ...LINEA_VACIA }] }))}>
                  Agregar línea
                </Button>
              </LineasHeader>
              <LineasWrap>
                {editForm.lineas.map((l, i) => (
                  <LineaRow key={i} linea={l} index={i} cuentas={planCuentas} centros={centros} moneda={moneda}
                    onUpdate={updateEditLinea}
                    onRemove={(idx) => setEditForm((f) => ({ ...f, lineas: f.lineas.filter((_, ii) => ii !== idx) }))} />
                ))}
              </LineasWrap>
              <BalanceBar $ok={editBalanceado}>
                <BalItem>
                  <span>Total DEBE</span>
                  <BalNum>{moneda === "PYG" ? fmtGs(editDebe) : `${moneda} ${editDebe.toLocaleString("es-PY", { minimumFractionDigits: 2 })}`}</BalNum>
                </BalItem>
                <BalDivider />
                <BalItem>
                  <span>Total HABER</span>
                  <BalNum>{moneda === "PYG" ? fmtGs(editHaber) : `${moneda} ${editHaber.toLocaleString("es-PY", { minimumFractionDigits: 2 })}`}</BalNum>
                </BalItem>
                <BalDivider />
                <BalStatus $ok={editBalanceado}>
                  <Icon icon={editBalanceado ? "lucide:check-circle-2" : "lucide:alert-circle"} />
                  {editBalanceado ? "Balanceado ✓" : `Diferencia: ${Math.abs(editDebe - editHaber).toLocaleString("es-PY", { maximumFractionDigits: 2 })} ${moneda}`}
                </BalStatus>
              </BalanceBar>
            </DialogContent>
            <DialogActions sx={{ p: 2, gap: 1 }}>
              <Button onClick={() => setEditTarget(null)}>Cancelar</Button>
              <Button variant="contained" onClick={handleGuardarEdit}
                disabled={!editBalanceado || editarMutation.isPending || corregirMutation.isPending}
                sx={{ background: "#f88533", "&:hover": { background: "#e07320" } }}>
                {editarMutation.isPending || corregirMutation.isPending ? "Guardando…" : "Guardar cambios"}
              </Button>
            </DialogActions>
          </Dialog>
        );
      })()}

      {/* Confirm revertir */}
      <Dialog open={!!revertirConfirm} onClose={() => setRevertirConfirm(null)} maxWidth="xs" fullWidth>
        <DialogTitle>¿Revertir asiento #{revertirConfirm?.numero}?</DialogTitle>
        <DialogContent>
          <p style={{ margin: 0, fontSize: 14, lineHeight: 1.5 }}>
            Se creará un <strong>asiento espejo</strong> con los débitos y créditos invertidos. El asiento original quedará marcado como REVERTIDO. Esta operación no se puede deshacer.
          </p>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRevertirConfirm(null)}>Cancelar</Button>
          <Button variant="contained" color="error" disabled={revertirMutation.isPending} onClick={() => revertirMutation.mutate(revertirConfirm.id, { onSuccess: () => setRevertirConfirm(null) })}>
            {revertirMutation.isPending ? "Revirtiendo…" : "Revertir asiento"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Confirm eliminar */}
      <Dialog open={!!eliminarConfirm} onClose={() => setEliminarConfirm(null)} maxWidth="xs" fullWidth>
        <DialogTitle style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Icon icon="lucide:trash-2" style={{ color: "#ef4444", width: 20, height: 20 }} />
          ¿Eliminar asiento #{eliminarConfirm?.numero}?
        </DialogTitle>
        <DialogContent>
          <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6 }}>
            Se eliminarán permanentemente el asiento y todas sus líneas. <strong>Esta acción no se puede deshacer.</strong>
          </p>
          {eliminarConfirm?.glosa && (
            <p style={{ margin: "10px 0 0", fontSize: 13, color: "#64748b" }}>
              Concepto: <em>{eliminarConfirm.glosa}</em>
            </p>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEliminarConfirm(null)}>Cancelar</Button>
          <Button
            variant="contained"
            color="error"
            disabled={eliminarMutation.isPending}
            onClick={() => eliminarMutation.mutate(eliminarConfirm.id, { onSuccess: () => setEliminarConfirm(null) })}
          >
            {eliminarMutation.isPending ? "Eliminando…" : "Eliminar definitivamente"}
          </Button>
        </DialogActions>
      </Dialog>
    </Wrapper>
  );
}

// ── Styles ────────────────────────────────────────────────────────────────────
const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  gap: 16px;
`;
const TopBar = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
`;
const PageTitle = styled.h2`
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  display: flex;
  align-items: center;
  gap: 10px;
  svg {
    width: 22px;
    height: 22px;
    color: #f88533;
  }
`;
const FiltersBar = styled.div`
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
  padding: 14px;
  background: ${({ theme }) => theme.bg2};
  border-radius: 10px;
  border: 1px solid ${({ theme }) => theme.color2};
`;
const TotalCount = styled.span`
  margin-left: auto;
  font-size: 12px;
  color: ${({ theme }) => theme.text}88;
`;
const TableWrap = styled.div`
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 10px;
  overflow-x: auto;
  background: ${({ theme }) => theme.bg2};
`;
const Table = styled.table`
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
  table-layout: fixed;
`;
const Th = styled.th`
  position: relative;
  padding: 11px 14px;
  text-align: ${({ align }) => align || "left"};
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: ${({ theme }) => theme.text}88;
  background: ${({ theme }) => theme.bg1};
  border-bottom: 1px solid ${({ theme }) => theme.color2};
  white-space: nowrap;
  overflow: hidden;
  user-select: none;
`;
const ResizeHandle = styled.div`
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 5px;
  cursor: col-resize;
  z-index: 1;
  &:hover,
  &:active {
    background: #f8853380;
  }
`;
const Tr = styled.tr`
  cursor: ${({ $clickable }) => ($clickable ? "pointer" : "default")};
  &:hover {
    background: ${({ theme }) => theme.bg3}25;
  }
`;
const Td = styled.td`
  padding: 10px 14px;
  text-align: ${({ align }) => align || "left"};
  color: ${({ theme }) => theme.text};
  border-bottom: 1px solid ${({ theme }) => theme.color2}30;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
`;
const GlosaTxt = styled.span`
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: block;
`;
const MonedaBadge = styled.span`
  font-size: 10px;
  font-weight: 700;
  padding: 1px 6px;
  border-radius: 4px;
  background: #3b82f618;
  color: #60a5fa;
  border: 1px solid #3b82f622;
  margin-top: 2px;
  display: inline-block;
`;
const DebeAmt = styled.span`
  color: #60a5fa;
  font-weight: 600;
`;
const HaberAmt = styled.span`
  color: #4ade80;
  font-weight: 600;
`;
const RowActions = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
`;
const ActionBtn = styled.button`
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 6px;
  border: 1px solid ${({ $green, $red }) => ($green ? "#16a34a44" : $red ? "#ef444444" : "#64748b44")};
  background: transparent;
  cursor: pointer;
  font-size: 11px;
  font-weight: 600;
  color: ${({ $green, $red }) => ($green ? "#16a34a" : $red ? "#ef4444" : "#64748b")};
  transition: background 0.12s;
  &:hover:not(:disabled) {
    background: ${({ $green, $red }) => ($green ? "#22c55e18" : $red ? "#ef444418" : "#64748b18")};
  }
  &:disabled {
    opacity: 0.5;
    cursor: default;
  }
  svg {
    width: 12px;
    height: 12px;
  }
`;
const ExpandIconSm = styled.div`
  transition: transform 0.2s;
  transform: ${({ $open }) => ($open ? "rotate(180deg)" : "rotate(0)")};
  color: ${({ theme }) => theme.text}66;
  svg {
    width: 16px;
    height: 16px;
  }
`;
const LineasDetail = styled.div`
  padding: 0 0 8px;
  background: ${({ theme }) => theme.bg1};
`;
const LineasTable = styled.table`
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
`;
const LinTh = styled.th`
  padding: 7px 14px;
  text-align: ${({ align }) => align || "left"};
  font-size: 10px;
  font-weight: 700;
  text-transform: uppercase;
  color: ${({ theme }) => theme.text}66;
  background: ${({ theme }) => theme.bg2};
  border-bottom: 1px solid ${({ theme }) => theme.color2}50;
`;
const LinTd = styled.td`
  padding: 7px 14px;
  text-align: ${({ align }) => align || "left"};
  color: ${({ theme }) => theme.text};
  border-bottom: 1px solid ${({ theme }) => theme.color2}20;
`;
const DocRef = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 14px;
  font-size: 11px;
  color: #64748b;
  svg {
    width: 12px;
    height: 12px;
  }
`;
const EmptyRow = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 48px;
  color: ${({ theme }) => theme.text}55;
  font-size: 14px;
  svg {
    width: 24px;
    height: 24px;
  }
`;
const LoadRow = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 40px;
  color: ${({ theme }) => theme.text}88;
  font-size: 14px;
  .spin {
    animation: spin 1s linear infinite;
  }
  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
`;
const FormRow = styled.div`
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-bottom: 20px;
`;
const LineasHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 13px;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
`;
const LineasWrap = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
`;
const LinRow = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 8px;
  background: ${({ theme }) => theme.bg1};
`;
const LineaNum = styled.span`
  width: 20px;
  text-align: center;
  font-size: 11px;
  color: ${({ theme }) => theme.text}55;
  flex-shrink: 0;
`;
const RemoveBtn = styled.button`
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 6px;
  color: #ef4444;
  &:hover {
    background: #ef444418;
  }
  svg {
    width: 14px;
    height: 14px;
  }
`;
const BalanceBar = styled.div`
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 14px 18px;
  border-radius: 10px;
  border: 1.5px solid ${({ $ok }) => ($ok ? "#22c55e44" : "#ef444444")};
  background: ${({ $ok, theme }) => ($ok ? "#22c55e0d" : "#ef44440d")};
`;
const BalItem = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 3px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: ${({ theme }) => theme.text}66;
`;
const BalNum = styled.span`
  font-size: 16px;
  font-weight: 800;
  color: ${({ theme }) => theme.text};
`;
const BalDivider = styled.div`
  width: 1px;
  height: 36px;
  background: ${({ theme }) => theme.color2};
`;
const BalStatus = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 700;
  color: ${({ $ok }) => ($ok ? "#22c55e" : "#ef4444")};
  margin-left: auto;
  svg {
    width: 20px;
    height: 20px;
  }
`;
const MonedaAlert = styled.div`
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 10px 14px;
  border-radius: 8px;
  margin-bottom: 16px;
  font-size: 12px;
  line-height: 1.5;
  background: ${({ $hasRate }) => ($hasRate ? "#3b82f611" : "#f59e0b11")};
  color: ${({ $hasRate }) => ($hasRate ? "#60a5fa" : "#f59e0b")};
  border: 1px solid ${({ $hasRate }) => ($hasRate ? "#3b82f622" : "#f59e0b33")};
  svg {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
    margin-top: 1px;
  }
  strong {
    font-weight: 700;
  }
`;
