// ─── Documentos · Facturas ───────────────────────────────────────────────
// FacturasScreen: lista navegable de facturas (envoltura delgada de
// EntityListScreen). Extraído de screens-documentos.jsx (P10, split junto con
// las otras 5 listas — ver compartido.jsx). Expone a window: FacturasScreen.
// Consume window.FACTURAS/ENTIDADES (core/colecciones.js), EntityListScreen/
// useEntityStats (ui/entity-list.jsx), IdDateCell (ui/primitives.jsx),
// _docExpCol/_docExpPid/_docEntidadNombre/_docMoney/_docMoneyShort/_docDate
// (compartido.jsx).
//
// FIX ESTRELLA (baseline, hallazgo dominante de §inv-dash): el 100% de las 855
// facturas migradas NO tiene `expedienteId` (verificado en vivo, docker exec
// psql: `select count(*) from facturas where expediente_id is null` = 855 =
// total) — son standalone por diseño (facturación directa, no del pipeline de
// un expediente). Antes, `onOpen` (core/app.jsx, route 'facturas') llamaba
// `openExpedienteFor(d.expedienteId, 'facturas')` incondicionalmente:
// `openExpedienteFor` con `expedienteId` null hace `setRoute(fallbackRoute)`
// — el fallback es LA MISMA ruta en la que ya está ('facturas') — un
// no-op silencioso. Clickear CUALQUIER fila de esta lista no hacía nada. El
// fix real vive en core/app.jsx: si `d.expedienteId` existe, abre el
// expediente (como antes); si no, abre el visor standalone fusionado de P8
// (`FacturaScreen` con prop `facturaId`, ruta `finanzas-doc-detail`) — MISMO
// componente que ya maneja bien el caso standalone (screens/finanzas/
// factura.jsx, `esStandalone = !expediente`). Recibos ídem (recibos.jsx).
//
// FIX (mapa-comprension.md §inv-dash, bug severidad media — búsqueda por
// cliente prometida): mismo fix que ordenes-compra.jsx — `searchFilter` ahora
// incluye `_docEntidadNombre(f.entidadId)`.

function FacturasScreen({ onOpen }) {
  const rows = window.FACTURAS || [];
  const total = rows.reduce((s, f) => s + (f.total || 0), 0);
  const countA = _docCount(rows, (f) => f.tipoFactura === 'A');

  // v_facturas_stats: {total, sumTotal, byTipoFactura} — facturas no tiene columna
  // estado real (el front la fabrica por hash en Finanzas), la dimensión real es
  // tipo_factura (A/B/C).
  const srvStats = window.useEntityStats('facturas');
  const kTotal = srvStats ? srvStats.total : rows.length;
  const kSumTotal = srvStats ? srvStats.sumTotal : total;
  const kByTipo = srvStats ? (srvStats.byTipoFactura || {}) : null;
  const kCountA = kByTipo ? (kByTipo.A || 0) : countA;
  const kCountB = kByTipo ? (kByTipo.B || 0) : (rows.length - countA);

  return (
    <EntityListScreen
      eyebrow="Documentos · Facturas"
      title="Facturas"
      description="Facturas emitidas a clientes. También visibles en Finanzas."
      secondaryAction={{ label: 'Exportar', icon: IconDownload }}
      kpis={[
        { label: 'Total', value: String(kTotal), deltaTone: 'neutral', icon: IconFileText },
        { label: 'Tipo A', value: String(kCountA), deltaTone: 'neutral', icon: IconClipboardCheck },
        { label: 'Facturado', value: _docMoneyShort(kSumTotal), deltaTone: 'neutral', icon: IconDollar },
        { label: 'Promedio', value: _docMoneyShort(kTotal ? Math.round(kSumTotal / kTotal) : 0), deltaTone: 'neutral', icon: IconTrendingUp },
      ]}
      filterChips={{
        options: [
          { label: 'Tipo A', value: 'A', count: kCountA },
          { label: 'Tipo B', value: 'B', count: kCountB },
        ].filter((o) => o.count > 0),
        applyFilter: (f, v) => f.tipoFactura === v,
      }}
      columns={[
        { key: 'publicId', label: 'Factura', width: '180px', render: (f) => <IdDateCell id={`FAC-${f.tipoFactura} ${String(f.puntoVenta).padStart(4, '0')}-${f.numero}`} date={f.fechaEmision} /> },
        { key: 'expedienteId', label: 'Expediente', width: '150px', render: (f) => _docExpCol(f.expedienteId) },
        { key: 'entidadId', label: 'Cliente', width: '1.2fr', render: (f) => { const nombre = _docEntidadNombre(f.entidadId); return <span className="text-[13px] font-bold truncate" style={{ color: nombre ? 'var(--foreground)' : 'var(--muted-foreground)' }}>{nombre || '—'}</span>; } },
        { key: 'vto', label: 'Vto. pago', width: '130px', render: (f) => <span className="text-[12px] font-mono tabular-nums" style={{ color: 'var(--muted-foreground)' }}>{_docDate(f.fechaVencPago)}</span> },
        { key: 'total', label: 'Total', width: '160px', render: (f) => <span className="text-[14px] font-extrabold tabular-nums" style={{ color: 'var(--foreground)' }}>{_docMoney(f.total)}</span> },
      ]}
      rows={rows}
      collection="facturas"
      searchPlaceholder="Buscar por N°, expediente o cliente…"
      searchFilter={(f, q) => (f.numero || '').toLowerCase().includes(q) || _docExpPid(f.expedienteId).toLowerCase().includes(q) || _docEntidadNombre(f.entidadId).toLowerCase().includes(q)}
      onRowClick={(f) => onOpen && onOpen(f)}
      dateField="fechaEmision"
      // Orden por defecto: más nuevo → más viejo por fecha de emisión, desempata
      // por publicId — el id INTERNO (L-FAC-.../FAC-..., P15), no el fiscal
      // numero/puntoVenta/tipoFactura que se muestra en la columna "Factura"
      // (mismo molde que screens/expedientes/lista.jsx).
      sortRows={(a, b) =>
        (b.fechaEmision || '').localeCompare(a.fechaEmision || '') ||
        (b.publicId || '').localeCompare(a.publicId || '')
      }
      exportFilename="Facturas"
      exportConfig={[
        { label: 'Factura', value: (f) => `FAC-${f.tipoFactura} ${String(f.puntoVenta).padStart(4, '0')}-${f.numero}` },
        { label: 'Fecha', value: (f) => f.fechaEmision },
        { label: 'Expediente', value: (f) => _docExpPid(f.expedienteId) },
        { label: 'Cliente', value: (f) => _docEntidadNombre(f.entidadId) },
        { label: 'Vto. pago', value: (f) => f.fechaVencPago || '' },
        { label: 'Tipo', value: (f) => f.tipoFactura },
        { label: 'Total', value: (f) => f.total },
      ]}
    />
  );
}

Object.assign(window, { FacturasScreen });
