import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { usePathname, useSearchParams } from "../client/navigation";
import { useEditContext } from "../client/editContext";
import { SimpleMenu } from "../ui/SimpleMenu";
import { StatusSummary } from "./StatusSummary";
import { PageHeader } from "../../components/PageHeader";
import { Info, Menu } from "lucide-react";
import { cn } from "../../lib/utils";
import { GearIcon } from "@radix-ui/react-icons";
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);
        // Also listen for custom pushstate events if EditorShell were to dispatch them,
        // but for now we'll rely on the fact that workspace/updateUrl calls will
        // trigger re-renders of EditorShell and thus update props or state.
        return () => {
            window.removeEventListener("popstate", 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(() => {
        if (urlActiveItemKey && urlActiveItemKey !== activeItemKey) {
            setActiveItemKey(urlActiveItemKey);
        }
    }, [urlActiveItemKey]);
    // 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 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: "flex h-full min-h-0 flex-col", children: [_jsxs("div", { className: "relative shrink-0 border-b border-gray-200", children: [_jsx(PageHeader, { title: "Settings", icon: _jsx(GearIcon, { className: "h-6 w-6" }), description: "Manage Parhelia settings", variant: "compact", showIconBox: false, className: "pr-16" }), !isDesktop && (_jsx("button", { type: "button", onClick: () => setMobileSidebarOpen((v) => !v), className: "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 border-gray-300 bg-white text-gray-700 shadow-sm transition-colors hover:bg-gray-50", "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 }) }))] }), _jsxs("div", { className: "relative flex min-h-0 flex-1 overflow-hidden", children: [!isDesktop && mobileSidebarOpen && (_jsx("button", { type: "button", className: "absolute inset-0 z-10 bg-black/20", "aria-label": "Close settings navigation", onClick: () => setMobileSidebarOpen(false) })), _jsxs("div", { className: cn("z-20 flex min-h-0 flex-col border-r border-gray-200 bg-gray-50", "transition-[width,transform,box-shadow] duration-300 ease-out", isDesktop
                            ? "relative w-64"
                            : mobileSidebarOpen
                                ? "absolute inset-y-0 left-0 w-64 shadow-xl"
                                : "absolute inset-y-0 left-0 w-0 -translate-x-full overflow-hidden border-r-0"), 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);
                                        }
                                    } }) })] }), _jsx("div", { className: "relative flex min-h-0 w-full flex-1 flex-col bg-white select-text", children: selectedPanel ? (_jsxs(_Fragment, { children: [_jsx(PageHeader, { icon: selectedPanel.icon ? (_jsx("span", { className: "[&_svg]:h-5 [&_svg]:w-5", children: selectedPanel.icon })) : undefined, title: selectedPanel.title, description: selectedPanel.subtitle, variant: "compact", showIconBox: false, className: "border-b border-gray-200" }), _jsx("div", { className: "min-h-0 flex-1 overflow-auto", children: selectedPanel.content })] })) : (_jsxs("div", { className: "flex h-full flex-col items-center justify-center text-gray-500", 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