"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useMemo, useState } from "react";
import { Building2, AlertCircle, RefreshCw, ChevronsUpDown, Plus, User, } from "lucide-react";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { cn } from "@stigmer/theme";
import { Menu, MenuContent, MenuItem, MenuRadioGroup, MenuRadioItem, MenuSeparator, MenuTrigger, } from "../internal/menu";
import { useOrg } from "./OrgProvider";
import { CreateOrganizationForm } from "./CreateOrganizationForm";
/**
 * Organization switcher dropdown for sidebar navigation.
 *
 * Shows the active organization (name + slug), lists personal and team
 * organizations grouped with icons, and provides a "Create organization"
 * action that opens an inline dialog with {@link CreateOrganizationForm}.
 *
 * Designed for sidebar placement — the trigger uses `sidebar-*` design
 * tokens. The portaled dropdown and dialog use standard `popover-*` /
 * main-area tokens per theme-token-guidelines.
 *
 * Must be rendered inside an {@link OrgProvider}.
 *
 * @example
 * ```tsx
 * <OrgSwitcher onOrgChanged={(org) => navigate("/")} />
 * ```
 */
export function OrgSwitcher({ onOrgChanged, className }) {
    const { orgs, activeOrg, setActiveOrg, isLoading, error, retry, refresh } = useOrg();
    const [createOpen, setCreateOpen] = useState(false);
    const handleOrgSwitch = useCallback((slug) => {
        const org = orgs.find((o) => o.metadata?.slug === slug);
        if (org && org.metadata?.slug !== activeOrg?.metadata?.slug) {
            setActiveOrg(org);
            onOrgChanged?.(org);
        }
    }, [orgs, activeOrg, setActiveOrg, onOrgChanged]);
    const handleCreated = useCallback((org) => {
        setCreateOpen(false);
        refresh(org.metadata?.slug);
        onOrgChanged?.(org);
    }, [refresh, onOrgChanged]);
    const personalOrgs = useMemo(() => orgs.filter((o) => o.spec?.isPersonal), [orgs]);
    const teamOrgs = useMemo(() => orgs.filter((o) => !o.spec?.isPersonal), [orgs]);
    if (isLoading) {
        return _jsx(OrgSwitcherSkeleton, { className: className });
    }
    if (error) {
        return (_jsxs("div", { className: cn("flex items-center gap-2 px-2 py-1.5", className), children: [_jsx(AlertCircle, { className: "text-destructive size-4 shrink-0" }), _jsx("span", { className: "text-destructive truncate text-xs", children: error }), _jsx("button", { onClick: retry, className: "text-sidebar-muted-foreground hover:text-sidebar-foreground shrink-0 rounded p-0.5 transition-colors", "aria-label": "Retry loading organizations", children: _jsx(RefreshCw, { className: "size-3" }) })] }));
    }
    const hasOrgs = orgs.length > 0 && activeOrg;
    const TriggerIcon = activeOrg?.spec?.isPersonal ? User : Building2;
    return (_jsxs(_Fragment, { children: [_jsxs(Menu, { children: [_jsxs(MenuTrigger, { "aria-label": "Organization menu", className: cn("hover:bg-sidebar-accent flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-sm transition-colors focus:outline-none", className), children: [_jsx(TriggerIcon, { className: "text-sidebar-muted-foreground mt-0.5 size-4 shrink-0 self-start" }), hasOrgs ? (_jsx(OrgLabel, { org: activeOrg, slugClassName: "text-sidebar-muted-foreground" })) : (_jsx("span", { className: "text-sidebar-muted-foreground truncate", children: "No organizations" })), _jsx(ChevronsUpDown, { className: "text-sidebar-muted-foreground ml-auto mt-0.5 size-3.5 shrink-0 self-start" })] }), _jsxs(MenuContent, { align: "start", side: "bottom", sideOffset: 4, children: [hasOrgs && (_jsxs(MenuRadioGroup, { value: activeOrg.metadata?.slug ?? "", onValueChange: handleOrgSwitch, children: [personalOrgs.map((org) => (_jsxs(MenuRadioItem, { value: org.metadata?.slug ?? "", className: "items-start", children: [_jsx(User, { className: "mt-0.5 size-3.5 shrink-0" }), _jsx(OrgLabel, { org: org })] }, org.metadata?.slug))), personalOrgs.length > 0 && teamOrgs.length > 0 && (_jsx(MenuSeparator, {})), teamOrgs.map((org) => (_jsxs(MenuRadioItem, { value: org.metadata?.slug ?? "", className: "items-start", children: [_jsx(Building2, { className: "mt-0.5 size-3.5 shrink-0" }), _jsx(OrgLabel, { org: org })] }, org.metadata?.slug)))] })), hasOrgs && _jsx(MenuSeparator, {}), _jsxs(MenuItem, { onClick: () => setCreateOpen(true), children: [_jsx(Plus, { className: "size-4" }), "Create organization"] })] })] }), _jsx(DialogPrimitive.Root, { open: createOpen, onOpenChange: (open) => setCreateOpen(open), children: _jsxs(DialogPrimitive.Portal, { children: [_jsx(DialogPrimitive.Backdrop, { className: cn("fixed inset-0 z-50 bg-black/50", "data-open:animate-in data-open:fade-in-0", "data-closed:animate-out data-closed:fade-out-0", "duration-150") }), _jsxs(DialogPrimitive.Popup, { className: cn("bg-background text-foreground ring-border/20", "fixed top-1/2 left-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2 rounded-lg p-6 shadow-lg ring-1 outline-none", "data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95", "data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", "duration-150"), children: [_jsx(DialogPrimitive.Title, { className: "text-foreground text-sm font-semibold", children: "Create organization" }), _jsx(DialogPrimitive.Description, { className: "text-muted-foreground mt-1 mb-4 text-xs", children: "Organizations are tenancy boundaries that own agents, environments, and other resources." }), _jsx(CreateOrganizationForm, { onCreated: handleCreated, onCancel: () => setCreateOpen(false) })] })] }) })] }));
}
// ---------------------------------------------------------------------------
// Internal sub-components
// ---------------------------------------------------------------------------
/**
 * Two-line org label: name (bold) + slug (muted). Used in the trigger
 * (sidebar context → pass `slugClassName="text-sidebar-muted-foreground"`)
 * and in dropdown radio items (popover context → default `text-muted-foreground`).
 */
function OrgLabel({ org, slugClassName, }) {
    const name = org.metadata?.name || org.metadata?.slug;
    const slug = org.metadata?.slug;
    return (_jsxs("span", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block truncate text-sm font-medium leading-tight", children: name }), slug && (_jsx("span", { className: cn("block truncate text-xs leading-tight", 
                // eslint-disable-next-line stigmer/no-main-tokens-in-sidebar -- OrgLabel renders inside portaled dropdown content (popover context)
                slugClassName ?? "text-muted-foreground"), children: slug }))] }));
}
function OrgSwitcherSkeleton({ className }) {
    return (_jsxs("div", { className: cn("flex items-center gap-2 px-2 py-1.5", className), children: [_jsx("div", { className: "bg-sidebar-muted size-4 animate-pulse rounded" }), _jsx("div", { className: "bg-sidebar-muted h-4 w-24 animate-pulse rounded" })] }));
}
//# sourceMappingURL=OrgSwitcher.js.map