import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { usePathname, useSearchParams } from "../client/navigation";
import { useEditContext } from "../client/editContext";
import { SimpleMenu } from "../ui/SimpleMenu";
import { StatusSummary } from "./StatusSummary";
import { SettingsBreadcrumb } from "./SettingsBreadcrumb";
import { SettingsBreadcrumbItemsContext, SettingsHeaderActionsContext, SettingsMainContentRefContext, } from "./SettingsHeaderActionsContext";
import { Info, Menu } from "lucide-react";
import { cn } from "../../lib/utils";
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 [headerActions, setHeaderActions] = useState(null);
    const [breadcrumbItems, setBreadcrumbItems] = useState(null);
    const settingsMainContentRef = useRef(null);
    const settingsSubtitle = config?.settings.subtitle;
    const items = groups?.map((group) => {
        return {
            id: group.title,
            label: group.title,
            icon: group.icon,
            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);
        }
    };
    return (_jsxs("div", { className: "relative flex h-full min-h-0", "data-testid": "settings-view", children: [!isDesktop && mobileSidebarOpen && (_jsx("button", { type: "button", className: "bg-neutral-grey-100/20 absolute inset-0 z-10", "aria-label": "Close settings navigation", onClick: () => setMobileSidebarOpen(false) })), _jsxs("div", { className: cn("border-border-default bg-white z-20 flex min-h-0 flex-col border-r", "transition-[width,transform,box-shadow] duration-300 ease-out", isDesktop
                    ? "relative w-72"
                    : 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"), children: [(isDesktop || mobileSidebarOpen) && (_jsxs("div", { className: "border-border-default shrink-0 border-b px-4 py-3", children: [_jsx("div", { className: "text-neutral-grey-100 text-base leading-tight font-semibold", children: "Settings" }), settingsSubtitle ? (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-[11px] leading-tight", children: settingsSubtitle })) : null] })), _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);
                                }
                            } }) })] }), _jsx(SettingsMainContentRefContext.Provider, { value: settingsMainContentRef, children: _jsxs("div", { className: "flex w-full min-h-0 min-w-0 flex-1 flex-col", "data-testid": "settings-view-main-content", children: [_jsxs("div", { className: "border-border-default relative shrink-0 border-b", "data-testid": "settings-view-header", children: [selectedPanel && (_jsxs("div", { className: cn("text-neutral-grey-50 flex h-12 items-center gap-4 bg-white pr-6 pl-3 text-sm", !isDesktop && "pr-16"), 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] })), !isDesktop && (_jsx("button", { type: "button", onClick: () => setMobileSidebarOpen((v) => !v), className: "border-border-default text-neutral-grey-100 hover:bg-neutral-grey-5 absolute top-1/2 right-4 z-30 inline-flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-md border bg-white shadow-sm transition-colors", "aria-label": mobileSidebarOpen
                                        ? "Close settings navigation"
                                        : "Open settings navigation", title: mobileSidebarOpen
                                        ? "Close settings navigation"
                                        : "Open settings navigation", children: _jsx(Menu, { className: "h-4 w-4", strokeWidth: 1.75 }) }))] }), _jsx("div", { ref: settingsMainContentRef, className: "relative flex min-h-0 w-full flex-1 flex-col overflow-hidden bg-neutral-grey-5 select-text", "data-testid": "settings-view-content", children: selectedPanel ? (_jsx(SettingsBreadcrumbItemsContext.Provider, { value: setBreadcrumbItems, children: _jsx(SettingsHeaderActionsContext.Provider, { value: setHeaderActions, children: _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" })] })) })] }) })] }));
}
//# sourceMappingURL=SettingsView.js.map