import { jsx } from 'react/jsx-runtime';
import React__default, { createContext, useContext } from 'react';
import { cn } from '../../../utils/cn.js';
import { useAccordionContext } from './Accordion.js';

// Create context for AccordionItem
const AccordionItemContext = createContext(undefined);
// Hook to use AccordionItem context
const useAccordionItemContext = () => {
    const ctx = useContext(AccordionItemContext);
    if (!ctx)
        throw new Error("Accordion.Trigger and Accordion.Body must be used within Accordion.Item");
    return ctx;
};
const AccordionItem = React__default.forwardRef(({ children, className, value, ...props }, ref) => {
    const { value: selectedValue, onValueChange, type, variant, collapsible, theme } = useAccordionContext();
    // Determine if this item is open
    const isOpen = type === "single"
        ? selectedValue === value
        : Array.isArray(selectedValue) && selectedValue.includes(value);
    // Toggle handler for this specific item
    const toggle = () => {
        if (type === "single") {
            // For single type, either select this item or clear selection if collapsible
            onValueChange(isOpen && collapsible ? "" : value);
        }
        else {
            // For multiple type, add or remove from array
            if (Array.isArray(selectedValue)) {
                const newValue = isOpen
                    ? selectedValue.filter(v => v !== value)
                    : [...selectedValue, value];
                onValueChange(newValue);
            }
            else {
                onValueChange([value]);
            }
        }
    };
    // Generate IDs for ARIA linkage
    const triggerId = `accordion-item-${value}-trigger`;
    const contentId = `accordion-item-${value}-content`;
    // Context value for Trigger and Content
    const contextValue = {
        value,
        isOpen,
        toggle,
        triggerId,
        contentId,
    };
    // Select item style based on variant
    const itemStyleClass = variant === "stacked" ? theme === null || theme === void 0 ? void 0 : theme.itemStyleStacked : theme === null || theme === void 0 ? void 0 : theme.itemStyle;
    return (jsx(AccordionItemContext.Provider, { value: contextValue, children: jsx("div", { ref: ref, className: cn(itemStyleClass, className), "data-state": isOpen ? "open" : "closed", "data-variant": variant, "data-value": value, ...props, children: children }) }));
});
AccordionItem.displayName = "Accordion.Item";

export { AccordionItem, useAccordionItemContext };
