// ─── Inventario · Alquilables · Historial de alquileres ───────────────────
// InventarioHistorialAlquileresScreen: TODOS los movimientos de alquiler de los
// equipos VAC (Salida/Entrada/Depo) — una fila por movimiento, columnas 1:1 con
// el sheet de Fran (Fecha, Interno, N° Serie, Tamaño, Movimiento, Motivo, OS/
// Prepaga, Paciente, Doctor, Transporte, Lugar entrega, Observación). P23
// (03/07/2026): pantalla NUEVA, "sección aparte" del historial de CONSUMIBLES
// (ver header de historial.jsx — NO conviven en la misma tabla: son dos temas
// con columnas completamente distintas). Reusa EntityListScreen (la casa):
// búsqueda de texto, chips de tipo de movimiento (filterChips), chips de
// tamaño (topChips), rango de fechas (dateField='fecha', fecha de negocio),
// export a Excel. Expone a window: InventarioHistorialAlquileresScreen.
// Consume window.INVENTARIO_ALQUILERES (core/colecciones.js, hidratada por
// store.js), VAC_ESTADO_CFG/VAC_MOVIMIENTO_CFG (compartido.jsx), EntityListScreen
// (ui/entity-list.jsx), TablePill (ui/primitives.jsx), formatDate (dominio/formato.js).

function InventarioHistorialAlquileresScreen({ onBack, onOpenActivo }) {
  const EntityListScreen = window.EntityListScreen;
  const TablePill = window.TablePill;

  const rows = window.INVENTARIO_ALQUILERES || [];

  const columns = [
    { key: 'fecha', label: 'Fecha', width: '110px',
      render: (r) => (
        <span className="text-[12px] font-mono tabular-nums" style={{ color: 'var(--muted-foreground)' }}>
          {window.formatDate(r.fecha)}
        </span>
      ),
    },
    { key: 'codigoInterno', label: 'Interno · Tamaño', width: 'minmax(130px, 1fr)',
      render: (r) => (
        <div className="min-w-0">
          <p className="font-mono text-[13px] font-extrabold" style={{ color: 'var(--foreground)' }}>{r.codigoInterno || '—'}</p>
          <p className="text-[11px] mt-0.5" style={{ color: 'var(--muted-foreground)' }}>{r.tamano || '—'}</p>
        </div>
      ),
    },
    { key: 'numeroSerie', label: 'N° Serie', width: '120px',
      render: (r) => <span className="font-mono text-[11.5px] font-semibold" style={{ color: 'var(--muted-foreground)' }}>{r.numeroSerie || '—'}</span>,
    },
    { key: 'tipo', label: 'Movimiento', width: '120px',
      render: (r) => {
        const cfg = window.VAC_MOVIMIENTO_CFG[r.tipo] || { label: r.tipo, tone: 'neutral' };
        return <TablePill label={cfg.label} tone={cfg.tone} />;
      },
    },
    { key: 'motivo', label: 'Motivo', width: 'minmax(140px, 1fr)',
      render: (r) => <span className="text-[12.5px] font-semibold truncate block" style={{ color: 'var(--foreground)' }}>{r.motivo || '—'}</span>,
    },
    { key: 'osNombre', label: 'OS / Prepaga', width: '110px',
      render: (r) => <span className="text-[12px] font-bold uppercase truncate block" style={{ color: 'var(--muted-foreground)' }}>{r.osNombre || '—'}</span>,
    },
    { key: 'pacienteNombre', label: 'Paciente', width: 'minmax(140px, 1fr)',
      render: (r) => <span className="text-[12.5px] font-semibold truncate block" style={{ color: 'var(--foreground)' }}>{r.pacienteNombre || '—'}</span>,
    },
    { key: 'medicoNombre', label: 'Doctor', width: 'minmax(130px, 1fr)',
      render: (r) => <span className="text-[12.5px] truncate block" style={{ color: 'var(--muted-foreground)' }}>{r.medicoNombre || '—'}</span>,
    },
    { key: 'transporte', label: 'Transporte', width: '120px',
      render: (r) => <span className="text-[12px] truncate block" style={{ color: 'var(--muted-foreground)' }}>{r.transporte || '—'}</span>,
    },
    { key: 'lugarEntrega', label: 'Lugar entrega', width: 'minmax(130px, 1fr)',
      render: (r) => <span className="text-[12px] truncate block" style={{ color: 'var(--muted-foreground)' }}>{r.lugarEntrega || '—'}</span>,
    },
    { key: 'observacion', label: 'Observación', width: 'minmax(200px, 1.6fr)',
      render: (r) => <span className="text-[12px] truncate block" style={{ color: 'var(--muted-foreground)' }} title={r.observacion || ''}>{r.observacion || '—'}</span>,
    },
  ];

  const exportConfig = [
    { label: 'Fecha', value: (r) => r.fecha },
    { label: 'Interno', value: (r) => r.codigoInterno },
    { label: 'N° Serie', value: (r) => r.numeroSerie },
    { label: 'Tamaño', value: (r) => r.tamano },
    { label: 'Movimiento', value: (r) => (window.VAC_MOVIMIENTO_CFG[r.tipo] || {}).label || r.tipo },
    { label: 'Motivo', value: (r) => r.motivo },
    { label: 'OS o Prepaga', value: (r) => r.osNombre },
    { label: 'Paciente', value: (r) => r.pacienteNombre },
    { label: 'Doctor', value: (r) => r.medicoNombre },
    { label: 'Transporte', value: (r) => r.transporte },
    { label: 'Lugar entrega', value: (r) => r.lugarEntrega },
    { label: 'Observación', value: (r) => r.observacion },
  ];

  // Chips de tamaño (arriba de las KPIs) — solo los que de verdad aparecen en los datos.
  const tamanos = ['Chica', 'Mediana', 'Grande'].filter((t) => rows.some((r) => r.tamano === t));
  const topChips = {
    allLabel: 'Todos',
    options: tamanos.map((t) => ({ label: t, value: t })),
    applyFilter: (row, v) => row.tamano === v,
  };

  // Chips de tipo de movimiento (debajo de las KPIs, filtran la tabla actual).
  const filterChips = {
    allLabel: 'Todos',
    options: [
      { label: 'Salidas', value: 'SALIDA', tone: 'neg' },
      { label: 'Entradas', value: 'ENTRADA', tone: 'pos' },
      { label: 'Depósito', value: 'DEPO', tone: 'neutral' },
    ],
    applyFilter: (row, v) => row.tipo === v,
  };

  return (
    <div className="space-y-5 animate-fade-in-up">
      <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>

      <EntityListScreen
        eyebrow="Operaciones · Inventario"
        title="Historial de alquileres"
        description="Movimientos de los equipos VAC (alquiler) — salidas, entradas y depósito."
        topChips={topChips}
        filterChips={filterChips}
        columns={columns}
        rows={rows}
        searchPlaceholder="Buscar por interno, serie, paciente, doctor, motivo u observación…"
        searchFilter={(row, q) => {
          const hay = [
            row.codigoInterno, row.numeroSerie, row.tamano, row.motivo, row.osNombre,
            row.pacienteNombre, row.medicoNombre, row.transporte, row.lugarEntrega, row.observacion,
          ].filter(Boolean).join(' ').toLowerCase();
          return hay.includes(q);
        }}
        dateField="fecha"
        exportConfig={exportConfig}
        exportFilename="historial-alquileres-vac"
        secondaryAction={{ label: 'Exportar', icon: IconDownload }}
        onRowClick={onOpenActivo ? (row) => { if (row.activoId) onOpenActivo(row.activoId); } : undefined}
        rowChevron={!!onOpenActivo}
        emptyText="Sin movimientos de alquiler registrados."
      />
    </div>
  );
}

Object.assign(window, { InventarioHistorialAlquileresScreen });
