// ─── Navegación cruzada del Directorio ──────────────────────────────
// Extraído de app.jsx (P3, split del monolito): los saltos entre módulos que disparan
// las tarjetas "Registros asociados" de Entidades/Médicos/Particulares/Proveedores
// (ej. "ver expedientes de esta entidad") — filtran la lista destino con un prefilter
// en vez de navegar a una URL con query params, así que viven en memoria de React, no
// en la URL (a diferencia del router).
// Expone a window: useDirectorioNav (hook). Consume ENTIDADES/MEDICOS/PARTICULARES/
// EXPEDIENTES (globals hidratados por store.js). Lo usa core/app.jsx; se carga junto
// con core/router.jsx y core/breadcrumbs.jsx, justo antes de core/app.jsx.

// ─── useDirectorioNav ────────────────────────────────────────────────────────────
// Recibe route/listPrefilter (para el efecto de limpieza) + setRoute/setListPrefilter +
// los setters de selección del directorio; devuelve { directorioNav, buildPrefilter }.
function useDirectorioNav({
  route, listPrefilter, setListPrefilter, setRoute,
  setSelectedEntidadId, setSelectedMedicoId, setSelectedParticularId, setSelectedProveedorId,
}) {
  // Cross-navigation helper for directorio detail screens.
  // For "Registros asociados" cards: set a list prefilter (banner shown
  // at the top of the destination list) and route to that module.
  const buildPrefilter = ({ module, label, sublabel, predicate }) => ({
    module, label, sublabel, predicate,
    onClear: () => setListPrefilter(null),
  });

  const directorioNav = {
    toEntidad:     (id) => { setSelectedEntidadId(id);     setRoute('entidades-detail'); },
    toMedico:      (id) => { setSelectedMedicoId(id);      setRoute('medicos-detail'); },
    toParticular:  (id) => { setSelectedParticularId(id);  setRoute('particulares-detail'); },
    toProveedor:   (id) => { setSelectedProveedorId(id);   setRoute('proveedores-detail'); },

    // Entidades-driven jumps
    toExpedientes: (ctx) => {
      // Filtramos por el id REAL que cada fila ya trae (row.entidadId/medicoId/particularId,
      // el *_id de la tabla `expedientes` camelizado por /api/expedientes), no por
      // apellido/razonSocial: comparar por nombre mezclaba expedientes de homónimos
      // (BUGS-caza-01-07-2026.md #11/M4 — ej. 8 médicos "Garcia" distintos, 13 expedientes).
      if (ctx && typeof ctx === 'object') {
        if (ctx.entidadId) {
          const ent = ENTIDADES.find(e => e.id === ctx.entidadId);
          if (ent) {
            setListPrefilter(buildPrefilter({
              module: 'expedientes',
              label: `Expedientes de ${ent.razonSocial}`,
              sublabel: ent.publicId,
              predicate: (row) => row.entidadId === ent.id,
            }));
          }
        } else if (ctx.medicoId) {
          const med = MEDICOS.find(m => m.id === ctx.medicoId);
          if (med) {
            setListPrefilter(buildPrefilter({
              module: 'expedientes',
              label: `Expedientes de ${med.titulo ? med.titulo + ' ' : ''}${med.nombre} ${med.apellido}`.trim(),
              sublabel: med.publicId,
              predicate: (row) => row.medicoId === med.id,
            }));
          }
        } else if (ctx.particularId) {
          const par = PARTICULARES.find(p => p.id === ctx.particularId);
          if (par) {
            setListPrefilter(buildPrefilter({
              module: 'expedientes',
              label: `Expedientes de ${par.nombre} ${par.apellido}`,
              sublabel: par.publicId,
              predicate: (row) => row.particularId === par.id,
            }));
          }
        } else {
          setListPrefilter(null);
        }
      } else {
        setListPrefilter(null);
      }
      setRoute('expedientes-list');
    },

    toCompras: (entidadId) => {
      if (entidadId) {
        const ent = ENTIDADES.find(e => e.id === entidadId);
        if (ent) {
          // Match compras cuyo expediente pertenece a esta entidad, por id real (no por
          // razonSocial — mismo fix que toExpedientes, BUGS-caza-01-07-2026.md #11/M4).
          const expedienteIds = new Set(
            EXPEDIENTES.filter(e => e.entidadId === ent.id).map(e => e.id)
          );
          setListPrefilter(buildPrefilter({
            module: 'compras',
            label: `Compras vinculadas a ${ent.razonSocial}`,
            sublabel: `${expedienteIds.size} expediente${expedienteIds.size === 1 ? '' : 's'}`,
            predicate: (row) => expedienteIds.has(row.expedienteId),
          }));
        }
      } else {
        setListPrefilter(null);
      }
      setRoute('compras');
    },

    // Proveedor-driven jump (Compras "Registros asociados" del detalle de Proveedor):
    // filtra directo por `row.proveedorId` (FK real que ya embebe /api/compras), sin el
    // rodeo por expediente que necesita toCompras(entidadId) — un proveedor no pasa por
    // un expediente/entidad, factura directo a Micos.
    toComprasProveedor: (proveedorId) => {
      if (proveedorId) {
        const prov = (window.PROVEEDORES || []).find(x => x.id === proveedorId);
        if (prov) {
          setListPrefilter(buildPrefilter({
            module: 'compras',
            label: `Compras a ${prov.razonSocial}`,
            sublabel: prov.publicId,
            predicate: (row) => row.proveedorId === proveedorId,
          }));
        }
      } else {
        setListPrefilter(null);
      }
      setRoute('compras');
    },

    toCobros: (entidadId) => {
      if (entidadId) {
        const ent = ENTIDADES.find(e => e.id === entidadId);
        if (ent) {
          setListPrefilter(buildPrefilter({
            module: 'finanzas',
            label: `Cobros de ${ent.razonSocial}`,
            sublabel: ent.publicId,
            predicate: (row) => row.entidadId === entidadId,
          }));
        }
      } else {
        setListPrefilter(null);
      }
      setRoute('finanzas');
    },

    // FIX AUDITORIA-ui-decorativa-05-07-2026.md MEDIA "tarjeta stat Pagos navega a Finanzas
    // sin filtrar" (Directorio → Detalle de Proveedor → tarjeta 'Pagos'): antes ignoraba
    // CUALQUIER argumento y navegaba a Finanzas sin filtro — dead-click disfrazado de
    // drill-down (la tarjeta hermana "Compras" sí filtra, ver toComprasProveedor). Pagos son
    // egresos a PROVEEDORES (pagos.proveedor_id, no hay entidad_id en la tabla) — mismo
    // criterio de toComprasProveedor: recibe proveedorId, filtra `row.proveedorId ===
    // proveedorId` (columna real que ya embebe /api/pagos, ver serializers/pagos.ts).
    // La tarjeta "Pagos" del detalle de ENTIDAD se sacó (screens/directorio/entidades.jsx)
    // porque una entidad no tiene esa relación — este helper ya no recibe un entidadId.
    toPagos: (proveedorId) => {
      if (proveedorId) {
        const prov = (window.PROVEEDORES || []).find(x => x.id === proveedorId);
        if (prov) {
          setListPrefilter(buildPrefilter({
            module: 'finanzas',
            label: `Pagos a ${prov.razonSocial}`,
            sublabel: prov.publicId,
            predicate: (row) => row.proveedorId === proveedorId,
          }));
        }
      } else {
        setListPrefilter(null);
      }
      setRoute('finanzas');
    },

    toParticulares: (ctx) => {
      if (ctx && ctx.medicoId) {
        const med = MEDICOS.find(m => m.id === ctx.medicoId);
        if (med) {
          setListPrefilter(buildPrefilter({
            module: 'particulares',
            label: `Pacientes derivados por ${med.titulo ? med.titulo + ' ' : ''}${med.nombre} ${med.apellido}`.trim(),
            sublabel: med.publicId,
            predicate: (row) => (row.medicosAtendieron || []).includes(med.id),
          }));
        }
      } else {
        setListPrefilter(null);
      }
      setRoute('particulares');
    },
  };

  // Clear prefilter when route changes away from the target module
  React.useEffect(() => {
    if (!listPrefilter) return;
    if (route !== listPrefilter.module &&
        route !== `${listPrefilter.module}-list` &&
        !(listPrefilter.module === 'expedientes' && route === 'expedientes-list')) {
      // Don't clear immediately — user may navigate back. Only clear if going
      // to an unrelated module's list, not detail of the same module.
      if (!route.startsWith(listPrefilter.module)) {
        setListPrefilter(null);
      }
    }
  }, [route]);

  return { directorioNav, buildPrefilter };
}

Object.assign(window, { useDirectorioNav });
