import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "../libs/utils";
import { VSelectBox } from "./selectBox";
const TabsContext = React.createContext({
    size: undefined,
    tabs: undefined,
    current: undefined,
    setTab: undefined,
    responsive: false,
    variant: "tabs",
    updateHash: true
});
const VTabs = ({ tabs, defaultValue, current, className, fullWidth, children, onTabChange, responsive = false, variant = "tabs", updateHash = true }) => {
    // Initialize value
    const [value, setValue] = React.useState(() => {
        // First check if current is provided
        const currentValue = typeof current === 'function' ? current() : current;
        if (currentValue) {
            return currentValue;
        }
        // Then check hash
        const hash = window.location.hash;
        const currentTab = hash ? hash.substring(1) : undefined;
        // Check if the tab from hash exists in tabs
        if (currentTab && tabs.some(tab => tab.name === currentTab)) {
            return currentTab;
        }
        // Fall back to default or first tab
        return defaultValue || tabs[0]?.name;
    });
    // Update when current prop changes (but don't create a loop)
    React.useEffect(() => {
        const currentValue = typeof current === 'function' ? current() : current;
        if (currentValue && currentValue !== value) {
            setValue(currentValue);
        }
    }, [current]);
    // Listen to hash changes only when there's no current prop being controlled externally
    React.useEffect(() => {
        if (current)
            return; // Skip hash handling if controlled by parent
        const handleHashChange = () => {
            const hash = window.location.hash;
            const currentTab = hash ? hash.substring(1) : undefined;
            // Only update if the tab exists in tabs
            if (currentTab && tabs.some(tab => tab.name === currentTab)) {
                setValue(currentTab);
            }
            else if (!hash && defaultValue) {
                // If no hash, fall back to default
                setValue(defaultValue);
            }
        };
        // Check initial hash
        handleHashChange();
        window.addEventListener('hashchange', handleHashChange);
        return () => window.removeEventListener('hashchange', handleHashChange);
    }, [current, tabs, defaultValue]);
    const handleValueChange = (newValue) => {
        setValue(newValue);
        // Update the URL hash when tab changes (only if updateHash is true and not controlled by parent)
        if (updateHash && !current) {
            // Preserve existing history state when changing hash
            const currentState = window.history.state;
            const newUrl = window.location.pathname + window.location.search + '#' + newValue;
            window.history.pushState(currentState, '', newUrl);
        }
        if (onTabChange) {
            onTabChange(newValue);
        }
    };
    const setTab = React.useCallback((tabName) => {
        handleValueChange(tabName);
    }, [handleValueChange]);
    return (_jsx(TabsContext.Provider, { value: { tabs, size: fullWidth ? tabs.length : 0, current: value, setTab, responsive: responsive, variant, updateHash }, children: _jsx(TabsPrimitive.Root, { defaultValue: value || tabs[0]?.name, value: value, onValueChange: handleValueChange, className: className, children: children }) }));
};
const VTabsBar = ({ className }) => {
    const { tabs, size, current, setTab, responsive, variant, updateHash } = React.useContext(TabsContext);
    const fullWidth = size !== 0;
    const handleTabChange = React.useCallback((tabName) => {
        if (!tabs || !setTab)
            return;
        const tab = tabs.find(t => t.name === tabName);
        if (tab?.href && updateHash) {
            // Preserve existing history state when changing tabs
            const currentState = window.history.state;
            window.history.pushState(currentState, '', tab.href);
        }
        setTab(tabName);
    }, [tabs, setTab, updateHash]);
    if (!tabs || !setTab) {
        console.warn("TabsBar: No tabs provided or setTab not available");
        return null;
    }
    return (_jsxs(_Fragment, { children: [responsive && (_jsx("div", { className: "px-2 block lg:hidden", children: _jsx(VSelectBox, { label: "Tab", className: (className), options: tabs, optionLabel: (tab) => typeof tab.label === 'string' ? tab.label : String(tab.label), value: tabs.find(tab => tab.name === current), onChange: (tab) => {
                        handleTabChange(tab.name);
                    } }) })), _jsx(TabsList, { size: size, variant: variant, className: cn((fullWidth ? "w-full" : ""), className, (responsive ? "hidden lg:flex" : "")), children: tabs.map((tab) => (_jsx(TabsTrigger, { value: tab.name, disabled: tab.disabled, href: tab.href, variant: variant, onClick: () => handleTabChange(tab.name), children: tab.label }, tab.name))) })] }));
};
const VTabsPanel = () => {
    const { tabs } = React.useContext(TabsContext);
    if (!tabs)
        return null;
    return (_jsx(_Fragment, { children: tabs.map((tab) => (_jsx(TabsContent, { value: tab.name, children: tab.content }, tab.name))) }));
};
const TabsList = React.forwardRef(({ className, size, variant = "tabs", ...props }, ref) => (_jsx(TabsContext.Provider, { value: { size, variant }, children: _jsx(TabsPrimitive.List, { ref: ref, className: cn(variant === "tabs"
            ? "border-b -mb-px flex space-x-4"
            : "flex space-x-2 p-1 rounded-md", className), ...props }) })));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef(({ className, href, variant = "tabs", ...props }, ref) => {
    const { size } = React.useContext(TabsContext);
    const handleClick = React.useCallback((event) => {
        if (href) {
            event.preventDefault();
            // Preserve existing history state when changing tabs
            const currentState = window.history.state;
            window.history.pushState(currentState, '', href);
        }
        if (props.onClick) {
            props.onClick(event);
        }
    }, [href, props.onClick]);
    return (_jsx(TabsPrimitive.Trigger, { ref: ref, className: cn(variant === "tabs"
            ? cn("border-b-2 px-2 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer", "border-transparent text-muted-foreground hover:border-border hover:text-foreground", "data-[state=active]:border-primary data-[state=active]:text-primary", "disabled:pointer-events-none disabled:opacity-50")
            : cn("px-3 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer rounded-sm transition-colors", "tborder border-input bg-muted shadow-xs hover:bg-muted ring-inset", "data-[state=active]:bg-primary data-[state=active]:text-white data-[state=active]:shadow-sm", "disabled:pointer-events-none disabled:opacity-50"), className, size ? `w-1/${size}` : ""), onClick: handleClick, ...props }));
});
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef(({ className, ...props }, ref) => (_jsx(TabsPrimitive.Content, { ref: ref, className: cn("focus-visible:outline-none", className), ...props })));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { VTabs, VTabsBar, VTabsPanel, TabsList, TabsTrigger, TabsContent };
//# sourceMappingURL=tabs.js.map