// ─── Documentos · Recibos ────────────────────────────────────────────────
// RecibosScreen: lista navegable de recibos (envoltura delgada de
// EntityListScreen). Extraído de screens-documentos.jsx (P10, split junto con
// las otras 5 listas — ver compartido.jsx). Expone a window: RecibosScreen.
// Consume window.RECIBOS (core/colecciones.js), EntityListScreen/
// useEntityStats (ui/entity-list.jsx), IdDateCell (ui/primitives.jsx),
// _docExpCol/_docExpPid/_docMoney/_docMoneyShort (compartido.jsx).
//
// FIX ESTRELLA (mismo hallazgo que facturas.jsx — ver su header): el 100% de
// los 41 recibos migrados tampoco tiene `expedienteId` (docker exec psql:
// `select count(*) from recibos where expediente_id is null` = 41 = total).
// El fix vive en core/app.jsx (route 'recibos'): con expedienteId abre el
// expediente; sin él, abre el visor standalone fusionado de P8 (ReciboScreen
// con prop `reciboId`) en vez del no-op anterior (`openExpedienteFor` con
// `expedienteId` null caía a la MISMA ruta 'recibos', sin hacer nada).

function RecibosScreen({ onOpen }) {
  const rows = window.RECIBOS || [];
  const total = rows.reduce((s, r) => s + (r.total || 0), 0);

  // v_recibos_stats: {total, sumTotal}. "Instrumentos" (suma de instrumentos[])
  // no está en la vista — queda en el cálculo local (fallback, solo lo cargado).
  const srvStats = window.useEntityStats('recibos');
  const kTotal = srvStats ? srvStats.total : rows.length;
  const kSumTotal = srvStats ? srvStats.sumTotal : total;

  return (
    <EntityListScreen
      eyebrow="Documentos · Recibos"
      title="Recibos"
      description="Recibos de cobro a clientes. También visibles en Finanzas."
      secondaryAction={{ label: 'Exportar', icon: IconDownload }}
      kpis={[
        { label: 'Total', value: String(kTotal), deltaTone: 'neutral', icon: IconFileText },
        { label: 'Cobrado', value: _docMoneyShort(kSumTotal), deltaTone: 'pos', icon: IconDollar },
        { label: 'Instrumentos', value: String(rows.reduce((s, r) => s + (r.instrumentos || []).length, 0)), deltaTone: 'neutral', icon: IconWallet },
        { label: 'Promedio', value: _docMoneyShort(kTotal ? Math.round(kSumTotal / kTotal) : 0), deltaTone: 'neutral', icon: IconTrendingUp },
      ]}
      columns={[
        { key: 'publicId', label: 'Recibo', width: '180px', render: (r) => <IdDateCell id={r.publicId} date={r.fechaCobro} /> },
        { key: 'expedienteId', label: 'Expediente', width: '160px', render: (r) => _docExpCol(r.expedienteId) },
        { key: 'instrumentos', label: 'Instrumentos', width: '1fr', render: (r) => <span className="text-[12.5px]" style={{ color: 'var(--muted-foreground)' }}>{(r.instrumentos || []).map((i) => i.tipo[0] + i.tipo.slice(1).toLowerCase()).join(' · ') || '—'}</span> },
        { key: 'total', label: 'Total', width: '160px', render: (r) => <span className="text-[14px] font-extrabold tabular-nums" style={{ color: 'var(--foreground)' }}>{_docMoney(r.total)}</span> },
      ]}
      rows={rows}
      collection="recibos"
      searchPlaceholder="Buscar por N° o expediente…"
      searchFilter={(r, q) => r.publicId.toLowerCase().includes(q) || _docExpPid(r.expedienteId).toLowerCase().includes(q)}
      onRowClick={(r) => onOpen && onOpen(r)}
      dateField="fechaCobro"
      // Orden por defecto: más nuevo → más viejo por fecha de cobro, desempata
      // por publicId (P15 — mismo molde que screens/expedientes/lista.jsx).
      sortRows={(a, b) =>
        (b.fechaCobro || '').localeCompare(a.fechaCobro || '') ||
        (b.publicId || '').localeCompare(a.publicId || '')
      }
      exportFilename="Recibos"
      exportConfig={[
        { label: 'Recibo', value: (r) => r.publicId },
        { label: 'Fecha', value: (r) => r.fechaCobro },
        { label: 'Expediente', value: (r) => _docExpPid(r.expedienteId) },
        { label: 'Instrumentos', value: (r) => (r.instrumentos || []).map((i) => i.tipo).join(', ') },
        { label: 'Total', value: (r) => r.total },
      ]}
    />
  );
}

Object.assign(window, { RecibosScreen });
