/**
 * Pagination Component
 *
 * Displays pagination controls for search results.
 * Supports three display variants: numbered, load-more, and simple.
 *
 * CSS Variables (applied to the container element):
 *   --seekora-pagination-bg
 *   --seekora-pagination-color
 *   --seekora-pagination-active-bg
 *   --seekora-pagination-active-color
 *   --seekora-pagination-border
 *   --seekora-pagination-radius
 */
import React from 'react';
import { useSearchContext } from './SearchProvider';
import { useSearchState } from '../hooks/useSearchState';
import { clsx } from 'clsx';
import { useIsMobile } from '../utils/responsive';
/** Size-specific style tokens (responsive) */
const getSizeTokens = (size, isMobile) => {
    if (isMobile) {
        // Larger touch targets on mobile
        return {
            small: { paddingKey: 'small', fontSizeKey: 'small', minWidth: '40px', minHeight: '40px' },
            medium: { paddingKey: 'small', fontSizeKey: 'medium', minWidth: '44px', minHeight: '44px' },
            large: { paddingKey: 'medium', fontSizeKey: 'large', minWidth: '48px', minHeight: '48px' },
        }[size];
    }
    return {
        small: { paddingKey: 'small', fontSizeKey: 'small', minWidth: '32px', minHeight: '32px' },
        medium: { paddingKey: 'small', fontSizeKey: 'medium', minWidth: '40px', minHeight: '40px' },
        large: { paddingKey: 'medium', fontSizeKey: 'large', minWidth: '48px', minHeight: '48px' },
    }[size];
};
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', }) => {
    const { theme } = useSearchContext();
    const { results: stateResults, currentPage: stateCurrentPage, 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';
    // Size tokens (responsive)
    const sizeTokens = getSizeTokens(size, isMobile);
    // CSS variable aware helpers — allow overrides via custom properties
    const cssVarBg = 'var(--seekora-pagination-bg, ' + theme.colors.background + ')';
    const cssVarColor = 'var(--seekora-pagination-color, ' + theme.colors.text + ')';
    const cssVarActiveBg = 'var(--seekora-pagination-active-bg, ' + theme.colors.primary + ')';
    const cssVarActiveColor = 'var(--seekora-pagination-active-color, #fff)';
    const cssVarBorder = 'var(--seekora-pagination-border, ' + theme.colors.border + ')';
    const cssVarRadius = 'var(--seekora-pagination-radius, ' + (typeof theme.borderRadius === 'string' ? theme.borderRadius : theme.borderRadius.medium) + ')';
    const handlePageChange = (page) => {
        if (page < 1 || page > totalPages || page === currentPage)
            return;
        // Update state manager (automatically triggers search)
        setPage(page);
        // 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), "aria-current": isActive ? 'page' : undefined, "aria-label": `Page ${page}`, className: clsx(paginationTheme.item, isActive && paginationTheme.itemActive, isDisabled && paginationTheme.itemDisabled), style: {
            padding: theme.spacing[sizeTokens.paddingKey],
            margin: isMobile ? `0 4px` : `0 ${theme.spacing.small}`,
            border: `1px solid ${cssVarBorder}`,
            borderRadius: cssVarRadius,
            backgroundColor: isActive ? cssVarActiveBg : cssVarBg,
            color: isActive ? cssVarActiveColor : cssVarColor,
            cursor: isDisabled ? 'not-allowed' : 'pointer',
            opacity: isDisabled ? 0.5 : 1,
            fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
            minWidth: sizeTokens.minWidth,
            minHeight: sizeTokens.minHeight,
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            ...(isActive && {
                fontWeight: 'bold',
            }),
        } }, page));
    if (totalPages <= 1 && 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(paginationTheme.pageInfo), style: {
            fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
            color: cssVarColor,
            padding: `0 ${theme.spacing.small}`,
            whiteSpace: 'nowrap',
        }, "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(paginationTheme.container, className), style: {
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: theme.spacing.small,
                ...style,
            }, "aria-label": "Pagination" },
            React.createElement("button", { type: "button", onClick: () => handlePageChange(currentPage + 1), className: clsx(paginationTheme.loadMoreButton), style: {
                    padding: `${theme.spacing[sizeTokens.paddingKey]} ${theme.spacing.large}`,
                    border: 'none',
                    borderRadius: cssVarRadius,
                    backgroundColor: cssVarActiveBg,
                    color: cssVarActiveColor,
                    cursor: 'pointer',
                    fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
                    fontWeight: theme.typography.fontWeight?.medium ?? 500,
                    transition: theme.transitions?.fast ?? '150ms ease-in-out',
                    minWidth: sizeTokens.minWidth,
                }, "aria-label": remaining > 0 ? `${loadMoreText} (${remaining} remaining)` : loadMoreText },
                loadMoreText,
                remaining > 0 && (React.createElement("span", { className: clsx(paginationTheme.loadMoreText), style: {
                        marginLeft: theme.spacing.small,
                        opacity: 0.85,
                        fontSize: theme.typography.fontSize.small,
                    } },
                    "(",
                    remaining,
                    " remaining)"))),
            pageInfoElement));
    }
    // ── Simple variant ─────────────────────────────────────────────────
    if (variant === 'simple') {
        return (React.createElement("nav", { className: clsx(paginationTheme.container, paginationTheme.simpleContainer, className), style: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: theme.spacing.medium,
                ...style,
            }, "aria-label": "Pagination" },
            React.createElement("button", { type: "button", disabled: currentPage === 1, onClick: () => handlePageChange(currentPage - 1), className: clsx(paginationTheme.simpleButton, currentPage === 1 && paginationTheme.itemDisabled), style: {
                    padding: `${theme.spacing[sizeTokens.paddingKey]} ${theme.spacing.medium}`,
                    border: `1px solid ${cssVarBorder}`,
                    borderRadius: cssVarRadius,
                    backgroundColor: cssVarBg,
                    color: cssVarColor,
                    cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
                    opacity: currentPage === 1 ? 0.5 : 1,
                    fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
                    minWidth: sizeTokens.minWidth,
                    transition: theme.transitions?.fast ?? '150ms ease-in-out',
                }, "aria-label": "Previous page" }, previousLabel),
            React.createElement("span", { className: clsx(paginationTheme.simpleText, paginationTheme.pageInfo), style: {
                    fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
                    color: cssVarColor,
                    whiteSpace: 'nowrap',
                }, "aria-live": "polite" },
                "Page ",
                currentPage,
                " of ",
                totalPages),
            React.createElement("button", { type: "button", disabled: currentPage === totalPages, onClick: () => handlePageChange(currentPage + 1), className: clsx(paginationTheme.simpleButton, currentPage === totalPages && paginationTheme.itemDisabled), style: {
                    padding: `${theme.spacing[sizeTokens.paddingKey]} ${theme.spacing.medium}`,
                    border: `1px solid ${cssVarBorder}`,
                    borderRadius: cssVarRadius,
                    backgroundColor: cssVarBg,
                    color: cssVarColor,
                    cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',
                    opacity: currentPage === totalPages ? 0.5 : 1,
                    fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
                    minWidth: sizeTokens.minWidth,
                    transition: theme.transitions?.fast ?? '150ms ease-in-out',
                }, "aria-label": "Next page" }, nextLabel)));
    }
    // ── Numbered variant (default — original behavior) ─────────────────
    const pageNumbers = getPageNumbers();
    return (React.createElement("nav", { className: clsx(paginationTheme.container, className), style: style, "aria-label": "Pagination" },
        React.createElement("ul", { className: paginationTheme.list, style: {
                listStyle: 'none',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: 0,
                margin: 0,
                flexWrap: 'wrap',
            }, tabIndex: 0, onKeyDown: (e) => {
                if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    handlePageChange(currentPage - 1);
                }
                else if (e.key === 'ArrowRight') {
                    e.preventDefault();
                    handlePageChange(currentPage + 1);
                }
                else if (e.key === 'Home') {
                    e.preventDefault();
                    handlePageChange(1);
                }
                else if (e.key === 'End') {
                    e.preventDefault();
                    handlePageChange(totalPages);
                }
            } },
            showPrevNext && (React.createElement("li", null,
                React.createElement("button", { type: "button", disabled: currentPage === 1, onClick: () => handlePageChange(currentPage - 1), className: clsx(paginationTheme.item, currentPage === 1 && paginationTheme.itemDisabled), style: {
                        padding: theme.spacing[sizeTokens.paddingKey],
                        margin: `0 ${theme.spacing.small}`,
                        border: `1px solid ${cssVarBorder}`,
                        borderRadius: cssVarRadius,
                        backgroundColor: cssVarBg,
                        color: cssVarColor,
                        cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
                        opacity: currentPage === 1 ? 0.5 : 1,
                        fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
                    }, "aria-label": "Previous page" }, previousLabel))),
            pageNumbers.map((page, index) => {
                if (page === 'ellipsis') {
                    return (React.createElement("li", { key: `ellipsis-${index}` },
                        React.createElement("span", { className: paginationTheme.ellipsis, style: {
                                padding: theme.spacing[sizeTokens.paddingKey],
                                margin: `0 ${theme.spacing.small}`,
                                color: cssVarColor,
                                fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
                            } }, "...")));
                }
                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), className: clsx(paginationTheme.item, currentPage === totalPages && paginationTheme.itemDisabled), style: {
                        padding: theme.spacing[sizeTokens.paddingKey],
                        margin: `0 ${theme.spacing.small}`,
                        border: `1px solid ${cssVarBorder}`,
                        borderRadius: cssVarRadius,
                        backgroundColor: cssVarBg,
                        color: cssVarColor,
                        cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',
                        opacity: currentPage === totalPages ? 0.5 : 1,
                        fontSize: theme.typography.fontSize[sizeTokens.fontSizeKey],
                    }, "aria-label": "Next page" }, nextLabel))),
            resolvedShowPageInfo && (React.createElement("li", { style: { marginLeft: theme.spacing.small } }, pageInfoElement)))));
};
