import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useMemo } from 'react';
import { cn } from '../../../utils/cn.js';
import { breadcrumbsVariants, breadcrumbsTheme, defaultSeparator } from './Breadcrumbs.theme.js';
import { Dropdown } from '../Dropdown/Dropdown.js';

/**
 * Breadcrumbs component for displaying navigation hierarchy
 *
 * Features:
 * - Smart collapse with ellipsis when items exceed maxItems
 * - Customizable separators
 * - Dropdown menu for collapsed items with keyboard navigation
 * - shadcn-style className overrides
 * - Full accessibility support with ARIA semantics
 */
const Breadcrumbs = ({ items, separator, maxItems = 4, variant = "default", className, theme: themeOverrides, showIcons = true, ...props }) => {
    const [isEllipsisOpen, setIsEllipsisOpen] = useState(false);
    // Use default separator if none provided
    const SeparatorComponent = separator || defaultSeparator;
    // Merge theme with overrides
    const theme = useMemo(() => ({
        ...breadcrumbsTheme,
        ...breadcrumbsVariants[variant],
        ...(themeOverrides || {}),
    }), [variant, themeOverrides]);
    // Determine if we need to collapse items
    const shouldCollapse = items.length > maxItems;
    // Calculate visible items when collapsed
    const getVisibleItems = () => {
        if (!shouldCollapse) {
            return { visibleItems: items, hiddenItems: [] };
        }
        // Show first item + last 2 items, hide middle items
        const firstItem = items[0];
        const lastTwoItems = items.slice(-2);
        const hiddenItems = items.slice(1, -2);
        const visibleItems = [firstItem, ...lastTwoItems];
        return { visibleItems, hiddenItems };
    };
    const { visibleItems, hiddenItems } = getVisibleItems();
    // Render individual breadcrumb item
    const renderItem = (item, index, isLast) => {
        const isCurrentPage = isLast || !item.href;
        const itemContent = (jsxs(Fragment, { children: [showIcons && item.iconStart && (jsx("span", { className: "mr-1.5 flex-shrink-0", children: item.iconStart })), typeof item.label === 'string'
                    ? jsx("span", { children: item.label })
                    : item.label] }));
        return (jsx("span", { className: "flex items-center text-base", children: isCurrentPage ? (jsx("span", { className: cn("flex items-center", theme.current), "aria-current": "page", children: itemContent })) : (jsx("a", { href: item.href, className: cn("flex items-center", theme.link), "aria-label": typeof item.label === 'string' ? `Navigate to ${item.label}` : undefined, children: itemContent })) }, `breadcrumb-${index}`));
    };
    // Render separator
    const renderSeparator = (index) => {
        return (jsx("span", { className: cn("flex items-center", theme.separator), "aria-hidden": "true", children: SeparatorComponent }, `separator-${index}`));
    };
    // Render ellipsis with dropdown
    const renderEllipsis = () => {
        if (hiddenItems.length === 0)
            return null;
        const handleEllipsisAction = (itemKey) => {
            const index = parseInt(itemKey.replace("hidden-", ""));
            const selectedItem = hiddenItems[index];
            if (selectedItem.href) {
                window.location.href = selectedItem.href;
            }
        };
        return (jsxs(Dropdown, { isOpen: isEllipsisOpen, onOpenChange: setIsEllipsisOpen, onAction: handleEllipsisAction, placement: "bottom-start", offset: 8, children: [jsx(Dropdown.Trigger, { children: jsx("button", { type: "button", className: cn(theme.ellipsis), "aria-label": `Navigate to one of ${hiddenItems.length} hidden breadcrumbs`, children: "..." }) }), jsx(Dropdown.Menu, { "aria-label": "Hidden breadcrumb items", children: hiddenItems.map((item, index) => (jsx(Dropdown.Item, { itemKey: `hidden-${index}`, startContent: showIcons && item.iconStart, children: typeof item.label === 'string'
                            ? jsx("span", { children: item.label })
                            : item.label }, `hidden-${index}`))) })] }, "ellipsis"));
    };
    // Build the breadcrumb elements
    const breadcrumbElements = [];
    let separatorIndex = 0; // Unique separator counter
    if (shouldCollapse) {
        // Add first item
        breadcrumbElements.push(renderItem(visibleItems[0], 0, false));
        breadcrumbElements.push(renderSeparator(separatorIndex++));
        // Add ellipsis
        breadcrumbElements.push(renderEllipsis());
        breadcrumbElements.push(renderSeparator(separatorIndex++));
        // Add last two items
        const lastTwoItems = visibleItems.slice(1);
        lastTwoItems.forEach((item, index) => {
            const actualIndex = index + 1;
            const isLast = actualIndex === lastTwoItems.length;
            breadcrumbElements.push(renderItem(item, actualIndex, isLast));
            if (!isLast) {
                breadcrumbElements.push(renderSeparator(separatorIndex++));
            }
        });
    }
    else {
        // Render all items normally
        visibleItems.forEach((item, index) => {
            const isLast = index === visibleItems.length - 1;
            breadcrumbElements.push(renderItem(item, index, isLast));
            if (!isLast) {
                breadcrumbElements.push(renderSeparator(separatorIndex++));
            }
        });
    }
    return (jsx("nav", { "aria-label": "Breadcrumb", className: cn("flex items-center", className), ...props, children: jsx("ol", { className: "flex items-center gap-1", children: jsx("li", { className: "contents", children: breadcrumbElements }) }) }));
};
Breadcrumbs.displayName = "Breadcrumbs";

export { Breadcrumbs };
