import { jsx } from 'react/jsx-runtime';
import { useContext, createContext, useState, useCallback } from 'react';
import { cn } from '../../../utils/cn.js';
import { accordionTheme } from './Accordion.theme.js';
import { AccordionTrigger } from './AccordionTrigger.js';
import { AccordionBody } from './AccordionBody.js';
import { AccordionItem } from './AccordionItem.js';

// Create context for the main Accordion component
const AccordionContext = createContext(undefined);
const useAccordionContext = () => {
    const ctx = useContext(AccordionContext);
    if (!ctx)
        throw new Error("Accordion compound components must be used within <Accordion>");
    return ctx;
};
const AccordionRoot = ({ children, className, type = "single", variant = "separated", collapsible = false, defaultValue, value, onValueChange, theme: themeOverrides, darkMode = false, ...props }) => {
    // State for uncontrolled component
    const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue || (type === "single" ? "" : []));
    // Determine if component is controlled
    const isControlled = value !== undefined;
    const currentValue = isControlled ? value : uncontrolledValue;
    // Handler for value changes
    const handleValueChange = useCallback((newValue) => {
        if (!isControlled) {
            setUncontrolledValue(newValue);
        }
        onValueChange === null || onValueChange === void 0 ? void 0 : onValueChange(newValue);
    }, [isControlled, onValueChange]);
    // Merge theme with any overrides
    const theme = {
        ...accordionTheme,
        ...(themeOverrides || {}),
    };
    // Context value to be provided to children
    const contextValue = {
        type,
        variant,
        collapsible,
        value: currentValue,
        onValueChange: handleValueChange,
        theme,
    };
    // Select base style based on variant
    const baseStyleClass = variant === "stacked" ? theme.baseStyleStacked : theme.baseStyle;
    return (jsx(AccordionContext.Provider, { value: contextValue, children: jsx("div", { className: cn(baseStyleClass, darkMode && "dark", className), "data-variant": variant, ...props, children: children }) }));
};
AccordionRoot.displayName = "Accordion";
// Attach compound subcomponents
const Accordion = Object.assign(AccordionRoot, {
    Item: AccordionItem,
    Trigger: AccordionTrigger,
    Body: AccordionBody,
});

export { Accordion, useAccordionContext };
