import { useEffect, useMemo, useState } from 'react';

const PAGE_SIZES = [15, 25, 50, 100];

/**
 * Hook de pagination côté client.
 * @param {Array}  items       - Liste complète filtrée (exports visent cette liste)
 * @param {string} storageKey  - Clé localStorage pour la taille de page (ex: 'cl_pagesize_inv')
 * @param {Array}  resetDeps   - Dépendances qui remettent la page à 1 (filtres actifs)
 */
export function usePagination(items, storageKey, resetDeps = []) {
  const [pageSize, setPageSizeState] = useState(() => {
    const saved = localStorage.getItem(storageKey);
    const n = parseInt(saved, 10);
    return PAGE_SIZES.includes(n) ? n : 15;
  });
  const [page, setPage] = useState(1);

  // Reset page à 1 dès que les filtres changent
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => { setPage(1); }, resetDeps);

  const totalItems = items.length;
  const totalPages = Math.max(1, Math.ceil(totalItems / pageSize));

  // Clamp si la liste rétrécit sous la page courante
  const safePage = Math.min(page, totalPages);

  const pagedItems = useMemo(() => {
    const start = (safePage - 1) * pageSize;
    return items.slice(start, start + pageSize);
  }, [items, safePage, pageSize]);

  function setPageSize(n) {
    setPageSizeState(n);
    localStorage.setItem(storageKey, String(n));
    setPage(1);
  }

  return {
    pagedItems,
    page: safePage,
    setPage,
    pageSize,
    setPageSize,
    totalPages,
    totalItems,
    PAGE_SIZES,
  };
}
