"use client";

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

export function usePagination<T>(items: T[], pageSize: number = 20) {
  const [page, setPage] = useState(1);

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

  useEffect(() => {
    if (page > totalPages) {
      setPage(totalPages);
    }
  }, [page, totalPages]);

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

  const rangeStart = pagedItems.length === 0 ? 0 : (safePage - 1) * pageSize + 1;
  const rangeEnd = (safePage - 1) * pageSize + pagedItems.length;

  return {
    page: safePage,
    setPage,
    totalPages,
    pagedItems,
    rangeStart,
    rangeEnd,
    totalItems: items.length
  };
}
