/**
 * Pagination Component
 *
 * Displays pagination controls for search results.
 * Supports three display variants: numbered, load-more, and simple.
 *
 * Styling is handled via BEM CSS classes + CSS custom properties.
 * Component-scoped overrides:
 *   --seekora-pagination-bg
 *   --seekora-pagination-color
 *   --seekora-pagination-active-bg
 *   --seekora-pagination-active-color
 *   --seekora-pagination-border
 *   --seekora-pagination-radius
 *   --seekora-pagination-alignment
 */
import React, { useEffect } from "react";
import { useSearchContext } from "./SearchProvider";
import { useSearchState } from "../hooks/useSearchState";
import { clsx } from "clsx";
import { useIsMobile } from "../utils/responsive";
import { ensureSeekoraStyles } from "../styles/inject";
export const Pagination = ({ results: resultsProp, currentPage: currentPageProp, itemsPerPage: itemsPerPageProp, totalPages: totalPagesProp, onPageChange, maxPages: maxPagesProp = 7, showFirstLast = true, showPrevNext = true, renderPageButton, className, style, theme: customTheme, variant = "numbered", loadMoreText = "Load More", size = "medium", showPageInfo, previousLabel = "Previous", nextLabel = "Next", }) => {
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    const { client, enableAnalytics } = useSearchContext();
    const { results: stateResults, currentPage: stateCurrentPage, loading, setPage, } = useSearchState();
    const paginationTheme = customTheme || {};
    const isMobile = useIsMobile();
    // Responsive maxPages - show fewer pages on mobile
    const maxPages = isMobile ? Math.min(maxPagesProp, 5) : maxPagesProp;
    // Use results from prop if provided, otherwise from state manager
    const results = resultsProp || stateResults;
    // Use currentPage from prop if provided, otherwise from state manager
    const currentPage = currentPageProp || stateCurrentPage;
    const res = results;
    const itemsPerPage = itemsPerPageProp ||
        res?.perPage ||
        res?.data?.per_page ||
        res?.data?.data?.per_page ||
        20;
    const totalResults = res?.totalResults ||
        res?.data?.total_results ||
        res?.data?.data?.total_results ||
        0;
    const totalPages = totalPagesProp ||
        res?.totalPages ||
        res?.data?.total_pages ||
        res?.data?.data?.total_pages ||
        Math.ceil(totalResults / itemsPerPage);
    // Resolve whether to show page info text
    const resolvedShowPageInfo = showPageInfo !== undefined ? showPageInfo : variant === "simple";
    const handlePageChange = (page) => {
        if (page < 1 || page > totalPages || page === currentPage)
            return;
        // Update state manager (automatically triggers search)
        setPage(page);
        // Fire analytics event (B.2 — SCRUM-259)
        if (enableAnalytics && client.trackEvent) {
            Promise.resolve(client.trackEvent({
                event_name: "Products List Filtered",
                metadata: { page, page_size: itemsPerPage },
            })).catch((err) => {
                const error = err instanceof Error ? err : new Error(String(err));
                // eslint-disable-next-line no-console
                console.error("Pagination: Error tracking Products List Filtered event", error.message);
            });
        }
        // Call callback for backwards compatibility
        if (onPageChange) {
            onPageChange(page);
        }
    };
    const defaultRenderPageButton = (page, isActive, isDisabled) => (React.createElement("button", { type: "button", disabled: isDisabled, onClick: () => !isDisabled && handlePageChange(page), onKeyDown: (e) => {
            if (e.key === "ArrowLeft") {
                e.preventDefault();
                handlePageChange(currentPage - 1);
            }
            else if (e.key === "ArrowRight") {
                e.preventDefault();
                handlePageChange(currentPage + 1);
            }
        }, "aria-current": isActive ? "page" : undefined, "aria-label": `Page ${page}`, className: clsx("seekora-pagination__item", isActive && "seekora-pagination__item--active", isDisabled && "seekora-pagination__item--disabled", paginationTheme.item, isActive && paginationTheme.itemActive, isDisabled && paginationTheme.itemDisabled) }, page));
    if ((totalPages <= 1 || loading) && variant !== "load-more") {
        return null;
    }
    // For load-more, hide when there are no more pages to load
    if (variant === "load-more" && currentPage >= totalPages) {
        return null;
    }
    // Calculate page range to display
    const getPageNumbers = () => {
        const pages = [];
        const halfRange = Math.floor(maxPages / 2);
        let startPage = Math.max(1, currentPage - halfRange);
        let endPage = Math.min(totalPages, currentPage + halfRange);
        // Adjust if we're near the beginning or end
        if (currentPage <= halfRange) {
            endPage = Math.min(maxPages, totalPages);
        }
        if (currentPage >= totalPages - halfRange) {
            startPage = Math.max(1, totalPages - maxPages + 1);
        }
        if (showFirstLast && startPage > 1) {
            pages.push(1);
            if (startPage > 2) {
                pages.push("ellipsis");
            }
        }
        for (let i = startPage; i <= endPage; i++) {
            pages.push(i);
        }
        if (showFirstLast && endPage < totalPages) {
            if (endPage < totalPages - 1) {
                pages.push("ellipsis");
            }
            pages.push(totalPages);
        }
        return pages;
    };
    // ── Page info element ──────────────────────────────────────────────
    const pageInfoElement = resolvedShowPageInfo ? (React.createElement("span", { className: clsx("seekora-pagination__page-info", paginationTheme.pageInfo), "aria-live": "polite" },
        "Page ",
        currentPage,
        " of ",
        totalPages)) : null;
    // ── Load More variant ──────────────────────────────────────────────
    if (variant === "load-more") {
        const remaining = Math.max(0, totalResults - currentPage * itemsPerPage);
        return (React.createElement("nav", { className: clsx("seekora-pagination", paginationTheme.container, className), "data-variant": "load-more", "data-size": size, style: style, "aria-label": "Pagination" },
            React.createElement("button", { type: "button", onClick: () => handlePageChange(currentPage + 1), className: clsx("seekora-pagination__load-more-btn", paginationTheme.loadMoreButton), "aria-label": remaining > 0
                    ? `${loadMoreText} (${remaining} remaining)`
                    : loadMoreText },
                loadMoreText,
                remaining > 0 && (React.createElement("span", { className: clsx("seekora-pagination__load-more-text", paginationTheme.loadMoreText) },
                    "(",
                    remaining,
                    " remaining)"))),
            pageInfoElement));
    }
    // ── Simple variant ─────────────────────────────────────────────────
    if (variant === "simple") {
        return (React.createElement("nav", { className: clsx("seekora-pagination", paginationTheme.container, paginationTheme.simpleContainer, className), "data-variant": "simple", "data-size": size, style: style, "aria-label": "Pagination" },
            React.createElement("button", { type: "button", disabled: currentPage === 1, onClick: () => handlePageChange(currentPage - 1), className: clsx("seekora-pagination__simple-btn", currentPage === 1 && "seekora-pagination__simple-btn--disabled", paginationTheme.simpleButton, currentPage === 1 && paginationTheme.itemDisabled), "aria-label": "Previous page" }, previousLabel),
            React.createElement("span", { className: clsx("seekora-pagination__page-info", paginationTheme.simpleText, paginationTheme.pageInfo), "aria-live": "polite" },
                "Page ",
                currentPage,
                " of ",
                totalPages),
            React.createElement("button", { type: "button", disabled: currentPage === totalPages, onClick: () => handlePageChange(currentPage + 1), className: clsx("seekora-pagination__simple-btn", currentPage === totalPages &&
                    "seekora-pagination__simple-btn--disabled", paginationTheme.simpleButton, currentPage === totalPages && paginationTheme.itemDisabled), "aria-label": "Next page" }, nextLabel)));
    }
    // ── Numbered variant (default — original behavior) ─────────────────
    const pageNumbers = getPageNumbers();
    return (React.createElement("nav", { className: clsx("seekora-pagination", paginationTheme.container, className), "data-variant": "numbered", "data-size": size, style: style, "aria-label": "Pagination" },
        React.createElement("ul", { className: clsx("seekora-pagination__list", paginationTheme.list), tabIndex: -1 },
            showPrevNext && (React.createElement("li", null,
                React.createElement("button", { type: "button", disabled: currentPage === 1, onClick: () => handlePageChange(currentPage - 1), onKeyDown: (e) => {
                        if (e.key === "ArrowLeft") {
                            e.preventDefault();
                            handlePageChange(currentPage - 1);
                        }
                        else if (e.key === "ArrowRight") {
                            e.preventDefault();
                            handlePageChange(currentPage + 1);
                        }
                    }, className: clsx("seekora-pagination__item", currentPage === 1 && "seekora-pagination__item--disabled", paginationTheme.item, currentPage === 1 && paginationTheme.itemDisabled), "aria-label": "Previous page" }, previousLabel))),
            pageNumbers.map((page, index) => {
                if (page === "ellipsis") {
                    return (React.createElement("li", { key: `ellipsis-${index}` },
                        React.createElement("span", { className: clsx("seekora-pagination__ellipsis", paginationTheme.ellipsis) }, "...")));
                }
                const isActive = page === currentPage;
                const isDisabled = false;
                return (React.createElement("li", { key: page }, renderPageButton
                    ? renderPageButton(page, isActive, isDisabled)
                    : defaultRenderPageButton(page, isActive, isDisabled)));
            }),
            showPrevNext && (React.createElement("li", null,
                React.createElement("button", { type: "button", disabled: currentPage === totalPages, onClick: () => handlePageChange(currentPage + 1), onKeyDown: (e) => {
                        if (e.key === "ArrowLeft") {
                            e.preventDefault();
                            handlePageChange(currentPage - 1);
                        }
                        else if (e.key === "ArrowRight") {
                            e.preventDefault();
                            handlePageChange(currentPage + 1);
                        }
                    }, className: clsx("seekora-pagination__item", currentPage === totalPages &&
                        "seekora-pagination__item--disabled", paginationTheme.item, currentPage === totalPages && paginationTheme.itemDisabled), "aria-label": "Next page" }, nextLabel))),
            resolvedShowPageInfo && (React.createElement("li", { className: "seekora-pagination__page-info-item" }, pageInfoElement)))));
};
