import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState, } from "react";
import { usePathname, useSearchParams } from "../client/navigation";
import { useEditContext } from "../client/editContext";
import { SimpleMenu } from "../ui/SimpleMenu";
import { Splitter } from "../ui/Splitter";
import { StatusSummary } from "./StatusSummary";
import { SettingsBreadcrumb } from "./SettingsBreadcrumb";
import { SettingsBreadcrumbItemsContext, SettingsHeaderActionsContext, SettingsMainContentRefContext, } from "./SettingsHeaderActionsContext";
import { Info } from "lucide-react";
import { cn } from "../../lib/utils";
import { localStorageService } from "../services/localStorageService";
import { SETTINGS_NAVIGATION_COLLAPSED_KEY, resetSettingsNavigationState, setSettingsNavigationState, } from "./settingsNavigationStore";
export function SettingsView() {
    const editContext = useEditContext();
    const config = editContext?.configuration;
    const groups = config?.settings.groups;
    const searchParams = useSearchParams();
    // Read ccpanel from searchParams, but also fallback to window.location for cases
    // where URL was updated via pushState (bypassing Next.js router)
    const [urlActiveItemKey, setUrlActiveItemKey] = useState(searchParams.get("ccpanel") ||
        (typeof window !== "undefined"
            ? new URLSearchParams(window.location.search).get("ccpanel")
            : null));
    const getIsDesktop = () => typeof window !== "undefined" &&
        window.matchMedia("(min-width: 768px)").matches;
    // Sync urlActiveItemKey when searchParams change or on mount
    useEffect(() => {
        const key = searchParams.get("ccpanel") ||
            (typeof window !== "undefined"
                ? new URLSearchParams(window.location.search).get("ccpanel")
                : null);
        setUrlActiveItemKey(key);
    }, [searchParams]);
    // Listen for pushState/popstate changes to catch programmatic updates from EditorShell
    useEffect(() => {
        if (typeof window === "undefined")
            return;
        const handleLocationChange = () => {
            const key = new URLSearchParams(window.location.search).get("ccpanel");
            if (key !== urlActiveItemKey) {
                setUrlActiveItemKey(key);
            }
        };
        window.addEventListener("popstate", handleLocationChange);
        // The patched history.pushState in editor/client/navigation.tsx fires a
        // "parhelia:navigation" event. Listening for it lets us pick up programmatic
        // URL changes (e.g. the "View Index Status" button calling switchWorkspace
        // while we're already in the settings workspace), since popstate doesn't
        // fire for pushState and the Next.js-backed useSearchParams doesn't update
        // from manual history mutations.
        window.addEventListener("parhelia:navigation", handleLocationChange);
        return () => {
            window.removeEventListener("popstate", handleLocationChange);
            window.removeEventListener("parhelia:navigation", handleLocationChange);
        };
    }, [urlActiveItemKey]);
    // Get the first available panel as default
    const defaultActiveItemKey = groups?.flatMap((x) => x.panels)?.[0]?.id;
    const [activeItemKey, setActiveItemKey] = useState(urlActiveItemKey || defaultActiveItemKey || null);
    const pathname = usePathname();
    const updateUrl = (key) => {
        if (urlActiveItemKey === key)
            return;
        const current = new URLSearchParams(searchParams.toString());
        if (key) {
            current.set("ccpanel", key);
            // Ensure workspace=settings is set when navigating within Settings.
            if (!current.has("workspace")) {
                current.set("workspace", "settings");
            }
        }
        else {
            current.delete("ccpanel");
        }
        // Use window.history.pushState directly to avoid page reloads in static export mode
        // This matches the pattern used in EditorShell.tsx
        // Use the actual browser pathname (including any basePath like /parhelia)
        // so we don't accidentally drop the base segment when updating the URL
        const actualPathname = typeof window !== "undefined" ? window.location.pathname : pathname;
        const newUrl = `${actualPathname}?${current.toString()}`;
        window.history.pushState(null, "", newUrl);
    };
    // Keep active item in sync with URL param changes (e.g., programmatic navigation)
    useEffect(() => {
        const nextActiveItemKey = urlActiveItemKey || defaultActiveItemKey || null;
        if (nextActiveItemKey !== activeItemKey) {
            setActiveItemKey(nextActiveItemKey);
        }
    }, [urlActiveItemKey, defaultActiveItemKey, activeItemKey]);
    // Set default active item when config loads and no active item is set
    useEffect(() => {
        if (!activeItemKey && defaultActiveItemKey) {
            setActiveItemKey(defaultActiveItemKey);
        }
    }, [defaultActiveItemKey, activeItemKey]);
    const [isDesktop, setIsDesktop] = useState(() => getIsDesktop());
    useEffect(() => {
        if (typeof window === "undefined")
            return;
        const mediaQuery = window.matchMedia("(min-width: 768px)");
        const update = () => setIsDesktop(mediaQuery.matches);
        update();
        mediaQuery.addEventListener("change", update);
        return () => mediaQuery.removeEventListener("change", update);
    }, []);
    const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
    const [desktopNavigationCollapsed, setDesktopNavigationCollapsed] = useState(() => localStorageService.getItem(SETTINGS_NAVIGATION_COLLAPSED_KEY) ?? false);
    const [headerActions, setHeaderActions] = useState(null);
    const [breadcrumbItems, setBreadcrumbItems] = useState(null);
    const settingsMainContentRef = useRef(null);
    useEffect(() => {
        localStorageService.setItem(SETTINGS_NAVIGATION_COLLAPSED_KEY, desktopNavigationCollapsed);
    }, [desktopNavigationCollapsed]);
    const toggleSettingsNavigation = useCallback(() => {
        if (isDesktop) {
            setDesktopNavigationCollapsed((collapsed) => !collapsed);
            return;
        }
        setMobileSidebarOpen((open) => !open);
    }, [isDesktop]);
    useEffect(() => {
        return () => resetSettingsNavigationState();
    }, []);
    useEffect(() => {
        setSettingsNavigationState({
            isDesktop,
            mobileSidebarOpen,
            desktopNavigationCollapsed,
            onToggleNavigation: toggleSettingsNavigation,
        });
    }, [
        desktopNavigationCollapsed,
        isDesktop,
        mobileSidebarOpen,
        toggleSettingsNavigation,
    ]);
    const items = groups?.map((group) => {
        return {
            id: group.title,
            label: group.title,
            items: group.panels.map((panel) => ({
                id: panel.id,
                label: panel.title,
                icon: panel.icon,
            })) || [],
        };
    });
    // Find the currently selected panel content
    const selectedPanel = groups
        ?.flatMap((x) => x.panels)
        ?.find((item) => item.id === activeItemKey);
    if (!groups || !items) {
        return (_jsx("div", { className: "flex h-full flex-col items-center justify-center", children: "Loading..." }));
    }
    const handleNavigateToStatus = () => {
        setActiveItemKey("status");
        updateUrl("status");
        if (!isDesktop) {
            setMobileSidebarOpen(false);
        }
    };
    const navigationContent = (_jsxs(_Fragment, { children: [_jsx(StatusSummary, { onNavigate: handleNavigateToStatus, collapsed: !isDesktop && !mobileSidebarOpen }), _jsx("div", { className: "min-h-0 flex-1 overflow-auto", children: _jsx(SimpleMenu, { items: items, activeItemKey: activeItemKey, collapsed: !isDesktop && !mobileSidebarOpen, onItemClick: (item) => {
                        setActiveItemKey(item.id);
                        updateUrl(item.id);
                        if (!isDesktop) {
                            setMobileSidebarOpen(false);
                        }
                    } }) })] }));
    const settingsMainContent = (_jsx(SettingsMainContentRefContext.Provider, { value: settingsMainContentRef, children: _jsx("div", { ref: settingsMainContentRef, className: "flex h-full min-h-0 w-full min-w-0 flex-1 flex-col", "data-testid": "settings-view-main-content", children: _jsx("div", { className: "bg-neutral-grey-5 relative flex min-h-0 w-full flex-1 flex-col overflow-hidden select-text", "data-testid": "settings-view-content", children: selectedPanel ? (_jsx(SettingsBreadcrumbItemsContext.Provider, { value: setBreadcrumbItems, children: _jsxs(SettingsHeaderActionsContext.Provider, { value: setHeaderActions, children: [_jsx("div", { className: "bg-neutral-grey-5 relative shrink-0 px-10 pt-10 pb-4", "data-testid": "settings-view-header", children: _jsxs("div", { className: "flex min-w-0 items-start justify-between gap-4", children: [_jsx(SettingsBreadcrumb, { currentPanelTitle: selectedPanel.title, currentPanelSubtitle: selectedPanel.subtitle, breadcrumbItems: breadcrumbItems }), isDesktop && headerActions ? (_jsx("div", { className: "flex shrink-0 items-center justify-end", "data-testid": "settings-view-header-actions", children: headerActions })) : null] }) }), _jsx("div", { className: "min-h-0 flex-1 overflow-auto", children: selectedPanel.content }, selectedPanel.id)] }) })) : (_jsxs("div", { className: "text-neutral-grey-50 flex h-full flex-col items-center justify-center", children: [_jsx(Info, { className: "mb-4 h-10 w-10" }), _jsx("p", { children: "Select a panel from the menu to view its content" })] })) }) }) }));
    const desktopPanels = [
        {
            name: "settings-navigation",
            defaultSize: 288,
            minSize: 100,
            content: (_jsx("div", { className: "relative z-20 flex h-full min-h-0 flex-col bg-white", "data-testid": "settings-navigation", children: navigationContent })),
            className: "overflow-hidden bg-white",
            hidden: desktopNavigationCollapsed,
        },
        {
            name: "settings-pages",
            defaultSize: "auto",
            minSize: 360,
            content: settingsMainContent,
            className: "overflow-hidden",
        },
    ];
    if (isDesktop) {
        return (_jsx("div", { className: "relative h-full min-h-0", "data-testid": "settings-view", children: _jsx(Splitter, { panels: desktopPanels, localStorageKey: "settings-view-navigation-splitter", direction: "horizontal" }) }));
    }
    return (_jsxs("div", { className: "relative flex h-full min-h-0", "data-testid": "settings-view", children: [mobileSidebarOpen && (_jsx("button", { type: "button", className: "bg-neutral-grey-100/20 absolute inset-0 z-10", "aria-label": "Close settings navigation", onClick: () => setMobileSidebarOpen(false) })), _jsx("div", { className: cn("border-border-default z-20 flex min-h-0 flex-col border-r bg-white", "transition-[width,transform,box-shadow] duration-300 ease-out", mobileSidebarOpen
                    ? "absolute inset-y-0 left-0 w-72 shadow-xl"
                    : "absolute inset-y-0 left-0 w-0 -translate-x-full overflow-hidden border-r-0"), "data-testid": "settings-navigation", children: navigationContent }), settingsMainContent] }));
}
//# sourceMappingURL=SettingsView.js.map