"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useMemo, useState } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { useEnvironmentList } from "./useEnvironmentList";
import { EnvironmentVariableEditor } from "./EnvironmentVariableEditor";
/**
 * Displays a list of {@link Environment} resources for an organization
 * with expandable inline variable editors.
 *
 * Each environment is rendered as a collapsible card showing name,
 * description, and variable count. Clicking expands it to reveal a
 * full {@link EnvironmentVariableEditor}. Only one environment is
 * expanded at a time to keep the view focused.
 *
 * Use `labels` to include only matching environments, or
 * `excludeLabels` to remove specific ones from the list (e.g. exclude
 * the personal environment when it is already rendered separately).
 *
 * Part of the **Environment Flow** — manages persistent credentials
 * stored in Environment resources.
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <EnvironmentListPanel org="acme" />
 *
 * <EnvironmentListPanel
 *   org="acme"
 *   excludeLabels={{ "stigmer.ai/personal": "true" }}
 *   readOnly
 * />
 * ```
 */
export function EnvironmentListPanel({ org, labels, excludeLabels, onEnvironmentSelect, readOnly = false, onRefetchRef, className, }) {
    const { environments, isLoading, error, refetch } = useEnvironmentList(org, labels);
    const [expandedId, setExpandedId] = useState(null);
    if (onRefetchRef) {
        onRefetchRef(refetch);
    }
    const filtered = useMemo(() => {
        if (!excludeLabels)
            return environments;
        const labelSets = Array.isArray(excludeLabels)
            ? excludeLabels
            : [excludeLabels];
        if (labelSets.length === 0)
            return environments;
        return environments.filter((env) => {
            const envLabels = env.metadata?.labels ?? {};
            const shouldExclude = labelSets.some((labelSet) => Object.entries(labelSet).every(([k, v]) => envLabels[k] === v));
            return !shouldExclude;
        });
    }, [environments, excludeLabels]);
    const handleToggle = useCallback((env) => {
        const id = env.metadata?.id ?? "";
        if (expandedId === id) {
            setExpandedId(null);
        }
        else {
            setExpandedId(id);
            onEnvironmentSelect?.(env);
        }
    }, [expandedId, onEnvironmentSelect]);
    if (isLoading) {
        return (_jsx("div", { className: cn("space-y-2", className), "aria-busy": "true", "aria-label": "Loading environments", children: Array.from({ length: 2 }, (_, i) => (_jsx("div", { className: "bg-muted-subtle h-14 animate-pulse rounded-lg" }, i))) }));
    }
    if (error) {
        return (_jsx("p", { className: cn("text-destructive text-xs", className), role: "alert", children: getUserMessage(error) }));
    }
    if (filtered.length === 0) {
        return (_jsx("p", { className: cn("text-muted-foreground py-4 text-center text-xs", className), children: "No environments found." }));
    }
    return (_jsx("div", { className: cn("space-y-2", className), role: "list", "aria-label": "Environments", children: filtered.map((env) => {
            const id = env.metadata?.id ?? "";
            const isExpanded = expandedId === id;
            return (_jsx(EnvironmentCard, { environment: env, isExpanded: isExpanded, onToggle: () => handleToggle(env), readOnly: readOnly }, id));
        }) }));
}
// ---------------------------------------------------------------------------
// EnvironmentCard (internal)
// ---------------------------------------------------------------------------
function EnvironmentCard({ environment, isExpanded, onToggle, readOnly, }) {
    const name = environment.metadata?.name || environment.metadata?.slug || "Unnamed";
    const description = environment.spec?.description;
    const variableCount = Object.keys(environment.spec?.data ?? {}).length;
    const environmentId = environment.metadata?.id ?? "";
    return (_jsxs("div", { role: "listitem", className: cn("rounded-lg border transition-colors", isExpanded
            ? "border-border bg-card"
            : "border-border-muted hover:border-border"), children: [_jsxs("button", { type: "button", onClick: onToggle, "aria-expanded": isExpanded, className: "flex w-full items-center gap-3 px-3 py-2.5 text-left", children: [_jsx(ChevronIcon, { expanded: isExpanded }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block truncate text-sm font-medium text-foreground", children: name }), description && (_jsx("span", { className: "block truncate text-xs text-muted-foreground", children: description }))] }), _jsxs("span", { className: "shrink-0 text-xs text-muted-foreground", children: [variableCount, " ", variableCount === 1 ? "variable" : "variables"] })] }), isExpanded && environmentId && (_jsx("div", { className: "border-border-muted border-t px-3 pb-3 pt-2", children: _jsx(EnvironmentVariableEditor, { environmentId: environmentId, readOnly: readOnly }) }))] }));
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function ChevronIcon({ expanded }) {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", className: cn("shrink-0 text-muted-foreground transition-transform duration-150", expanded && "rotate-90"), children: _jsx("path", { d: "M6 4l4 4-4 4" }) }));
}
//# sourceMappingURL=EnvironmentListPanel.js.map