// ─── Inventario · Historial de movimientos de STOCK (consumibles) ──────────
// Página que agrega los movimientos de ingreso/egreso/ajuste de STOCK de los ítems
// CONSUMIBLES del inventario (inventario_movimiento). Se llega desde el botón
// "Ver todo el historial" del detalle de un producto.
//
// ARBITRAJE P23 (03/07/2026, VACs): esta pantalla ANTES tenía tabs Todos/
// Consumibles/Alquilables (alquilables = categoría 'Equipos VAC') — pero
// `inventario_movimiento` NUNCA tuvo (ni va a tener) filas de equipos VAC: esos
// se registran en `inventario_alquiler`, una tabla y un modelo completamente
// distintos (movimientos de un EQUIPO físico —codigo_interno/serie—, no de
// STOCK de un producto —cantidad/lote—). El tab "Alquilables" de acá SIEMPRE
// mostraba 0 filas (root cause de "el historial no muestra nada" que reportó
// Fran) y las columnas (Cantidad/Lote/Referencia) no tienen sentido para un
// alquiler (Paciente/Doctor/Transporte). Se saca ESE tab (dead weight, cero
// filas posibles) y la pantalla queda explícitamente scoped a CONSUMIBLES —
// el historial de alquiler de VACs vive en su propia pantalla
// (screens/inventario/historial-alquileres.jsx, InventarioHistorialAlquileresScreen),
// "sección aparte" en vez de tab (columnas/dominio demasiado distintos para
// convivir en una sola tabla — ver su propio header).
//
// P24 (03/07/2026 — libro de movimientos): ANTES esta pantalla aplanaba
// `window.INVENTARIO` (el catálogo hidratado al boot con `?limit=BIG_LIMIT=500` —
// core/store.js) para armar las filas — con 601 productos reales, los ~100 fuera de
// esa ventana quedaban invisibles acá aunque tuvieran movimientos (gap silencioso,
// hallazgo del diagnóstico de este paquete). Ahora hace `fetch` directo a
// GET /api/inventario-movimientos (el ledger COMPLETO, paginado server-side, sin ese
// techo) — mismo criterio que cualquier pantalla que no puede depender del catálogo
// parcial hidratado al boot. También suma la columna Motivo (antes no existía: los
// AJUSTE que ahora deja el ledger —edición manual de stock, aprobación de ajustes de
// entrega— sí tienen uno real, a diferencia de ENTRADA/SALIDA de logística).
//
// Reutiliza EntityListScreen → mismo estilo de las listas con tablas, SIN KPIs.

function InventarioHistorialScreen({ onBack, onOpenItem }) {
  const EntityListScreen = window.EntityListScreen;
  const TablePill = window.TablePill;

  const [rows, setRows] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [loadError, setLoadError] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;
    setLoading(true);
    // Límite generoso (2000): el ledger arranca el 03/07/2026, volumen bajo por ahora.
    // Cuando crezca de verdad, el mismo patrón de paginación server-side de
    // InventarioScreen (fetchPage + IntersectionObserver) es el próximo paso — no hace
    // falta anticiparlo hoy (YAGNI, un solo fetch cubre el uso real).
    fetch('/api/inventario-movimientos?limit=2000', { credentials: 'same-origin' })
      .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
      .then((data) => { if (!cancelled) setRows(Array.isArray(data) ? data : []); })
      .catch((e) => {
        console.warn('[InventarioHistorialScreen] fetch', e);
        if (!cancelled) setLoadError(true);
      })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, []);

  const columns = [
    { key: 'fecha', label: 'Fecha', width: '120px', mono: true,
      render: (r) => (
        <span className="text-[12px] font-mono tabular-nums" style={{ color: 'var(--muted-foreground)' }}>
          {window.formatDate(r.fecha)}
        </span>
      ),
    },
    { key: 'producto', label: 'Producto', width: 'minmax(220px, 1.4fr)',
      render: (r) => (
        <div className="min-w-0">
          <p className="text-[13px] font-bold truncate" style={{ color: 'var(--foreground)' }}>{r.descripcion}</p>
          <p className="text-[11.5px] mt-0.5 truncate" style={{ color: 'var(--muted-foreground)' }}>
            <span className="font-mono font-bold tracking-wide uppercase" style={{ color: 'var(--accent)' }}>{r.sku}</span>
            <span style={{ margin: '0 6px' }}>·</span>
            {r.categoria || 'Sin categoría'}
          </p>
        </div>
      ),
    },
    { key: 'tipo', label: 'Tipo', width: '110px',
      render: (r) => {
        const isIngreso = r.tipo === 'INGRESO';
        return <TablePill label={isIngreso ? 'Ingreso' : 'Egreso'} tone={isIngreso ? 'pos' : 'neg'} />;
      },
    },
    { key: 'cantidad', label: 'Cant.', width: '90px', align: 'right',
      render: (r) => {
        const isIngreso = r.tipo === 'INGRESO';
        return (
          <span className="text-[14px] font-extrabold tabular-nums" style={{ color: isIngreso ? 'var(--success)' : 'var(--danger)' }}>
            {isIngreso ? '+' : '−'}{r.cantidad}
          </span>
        );
      },
    },
    { key: 'lote', label: 'Lote', width: '150px',
      render: (r) => (
        <span className="font-mono text-[11px] font-bold tracking-wide uppercase truncate block" style={{ color: 'var(--muted-foreground)' }}>{r.lote || '—'}</span>
      ),
    },
    { key: 'referencia', label: 'Referencia', width: 'minmax(140px, 1fr)',
      render: (r) => (
        <span className="font-mono text-[11.5px] font-semibold tracking-wide truncate block" style={{ color: 'var(--foreground)' }}>{r.referencia || '—'}</span>
      ),
    },
    { key: 'motivo', label: 'Motivo', width: 'minmax(160px, 1.2fr)',
      render: (r) => (
        <span className="text-[12px] truncate block" style={{ color: r.motivo ? 'var(--foreground)' : 'var(--muted-foreground)' }}>{r.motivo || '—'}</span>
      ),
    },
    { key: 'usuario', label: 'Usuario', width: '130px',
      render: (r) => (
        <span className="text-[12.5px] font-semibold truncate block" style={{ color: 'var(--foreground)' }}>{r.usuario || 'Sin usuario'}</span>
      ),
    },
  ];

  const exportConfig = [
    { label: 'Fecha', value: (r) => r.fecha },
    { label: 'SKU', value: (r) => r.sku },
    { label: 'Producto', value: (r) => r.descripcion },
    { label: 'Categoría', value: (r) => r.categoria },
    { label: 'Tipo', value: (r) => (r.tipo === 'INGRESO' ? 'Ingreso' : 'Egreso') },
    { label: 'Cantidad', value: (r) => (r.tipo === 'INGRESO' ? r.cantidad : -r.cantidad) },
    { label: 'Lote', value: (r) => r.lote },
    { label: 'Referencia', value: (r) => r.referencia },
    { label: 'Motivo', value: (r) => r.motivo },
    { label: 'Usuario', value: (r) => r.usuario },
  ];

  return (
    <div className="space-y-5 animate-fade-in-up">
      {/* Back link (mismo patrón que los detalles) */}
      <button onClick={onBack}
        className="back-link flex items-center gap-2 text-[11px] font-bold uppercase tracking-[0.12em] cursor-pointer transition-colors"
        style={{ color: 'var(--muted-foreground)' }}
        onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--accent)')}
        onMouseLeave={(e) => (e.currentTarget.style.color = 'var(--muted-foreground)')}>
        <IconArrowLeft size={13} />
        Volver a Inventario
      </button>

      {loading ? (
        <div className="px-6 py-20 text-center">
          <p className="text-[14px] font-semibold" style={{ color: 'var(--muted-foreground)' }}>Cargando historial…</p>
        </div>
      ) : (
        <EntityListScreen
          eyebrow="Operaciones · Inventario"
          title="Historial de movimientos"
          description={loadError
            ? 'No se pudo cargar el historial real — reintentá en un momento.'
            : 'Movimientos de stock de los ítems consumibles — ingresos, egresos y ajustes de cada producto.'}
          columns={columns}
          rows={rows}
          searchPlaceholder="Buscar por producto, SKU, lote, referencia, motivo o usuario…"
          searchFilter={(row, q) => {
            const hay = [row.sku, row.descripcion, row.categoria, row.lote, row.referencia, row.motivo, row.usuario]
              .filter(Boolean).join(' ').toLowerCase();
            return hay.includes(q);
          }}
          dateField="fecha"
          exportConfig={exportConfig}
          exportFilename="historial-inventario"
          secondaryAction={{ label: 'Exportar', icon: IconDownload }}
          onRowClick={onOpenItem ? (row) => onOpenItem(row.itemId) : undefined}
          rowChevron={!!onOpenItem}
          emptyText={HISTORIAL_EMPTY_TEXT}
        />
      )}
    </div>
  );
}

Object.assign(window, { InventarioHistorialScreen });
