import { forwardRef } from "react";

/**
 * Pagination
 *
 * currentPage:  number - 1-based active page
 * totalPages:   number
 * onPageChange: (page: number) => void
 * renderItem:   (page, { currentPage, go }) => ReactNode - custom page item renderer
 */
const Pagination = forwardRef(function Pagination(
  { currentPage = 1, totalPages = 1, onPageChange, renderItem, className = "", ...props },
  ref
) {
  const go = (page) => {
    if (page < 1 || page > totalPages) return;
    onPageChange?.(page);
  };

  const defaultItem = (page) => (
    <a
      href="#"
      aria-label={currentPage === page ? `Current Page, Page ${page}` : `Go to Page ${page}`}
      aria-current={currentPage === page ? "true" : undefined}
      onClick={(e) => { e.preventDefault(); go(page); }}
    >
      {page}
    </a>
  );

  return (
    <nav
      ref={ref}
      className={["prs-pagination", className].filter(Boolean).join(" ")}
      role="navigation"
      aria-label="Pagination"
      {...props}
    >
      <ul>
        <li className={`prs-pagination-pager${currentPage === 1 ? " prs-pagination-pager_disabled" : ""}`}>
          <a href="#" aria-label="Previous Page" onClick={(e) => { e.preventDefault(); go(currentPage - 1); }}>
            <ChevronLeft />
          </a>
        </li>

        {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
          <li key={page}>
            {renderItem ? renderItem(page, { currentPage, go }) : defaultItem(page)}
          </li>
        ))}

        <li className={`prs-pagination-pager${currentPage === totalPages ? " prs-pagination-pager_disabled" : ""}`}>
          <a href="#" aria-label="Next Page" onClick={(e) => { e.preventDefault(); go(currentPage + 1); }}>
            <ChevronRight />
          </a>
        </li>
      </ul>
    </nav>
  );
});

export default Pagination;

const ChevronLeft = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" role="img" aria-hidden="true">
    <use href="/_assets/prs-icons.svg#chevron-left" />
  </svg>
);

const ChevronRight = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" role="img" aria-hidden="true">
    <use href="/_assets/prs-icons.svg#chevron-right" />
  </svg>
);
