"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from "react";
import { useStigmer } from "../hooks";
const OrgContext = createContext(null);
const STORAGE_KEY = "stigmer:activeOrgSlug";
function readPersistedSlug() {
    try {
        return localStorage.getItem(STORAGE_KEY);
    }
    catch {
        return null;
    }
}
function persistSlug(slug) {
    try {
        localStorage.setItem(STORAGE_KEY, slug);
    }
    catch {
        // SSR or private browsing — silently ignore.
    }
}
/**
 * Provides organization context to the component tree.
 *
 * Fetches the authenticated user's organizations via
 * `stigmer.organization.findMyOrganizations()`, manages the active
 * organization selection, and persists the choice to `localStorage`
 * under the key `stigmer:activeOrgSlug`.
 *
 * Must be rendered inside a {@link StigmerProvider}.
 *
 * @example
 * ```tsx
 * <StigmerProvider client={client}>
 *   <OrgProvider>
 *     <App />
 *   </OrgProvider>
 * </StigmerProvider>
 * ```
 */
export function OrgProvider({ children }) {
    const stigmer = useStigmer();
    const [orgs, setOrgs] = useState([]);
    const [activeOrg, setActiveOrgState] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const fetchIdRef = useRef(0);
    const load = useCallback(async (targetSlug) => {
        const fetchId = ++fetchIdRef.current;
        setIsLoading(true);
        setError(null);
        try {
            const response = await stigmer.organization.findMyOrganizations();
            const entries = response.entries;
            if (fetchId !== fetchIdRef.current)
                return;
            setOrgs(entries);
            if (entries.length === 0) {
                setActiveOrgState(null);
                return;
            }
            const preferred = targetSlug ?? readPersistedSlug();
            const restored = preferred
                ? entries.find((o) => o.metadata?.slug === preferred)
                : undefined;
            const selected = restored ?? entries[0];
            setActiveOrgState(selected);
            if (selected.metadata?.slug) {
                persistSlug(selected.metadata.slug);
            }
        }
        catch (err) {
            if (fetchId !== fetchIdRef.current)
                return;
            const message = err instanceof Error ? err.message : "Failed to load organizations";
            setError(message);
            setOrgs([]);
            setActiveOrgState(null);
        }
        finally {
            if (fetchId === fetchIdRef.current) {
                setIsLoading(false);
            }
        }
    }, [stigmer]);
    useEffect(() => {
        load();
    }, [load]);
    const setActiveOrg = useCallback((org) => {
        setActiveOrgState(org);
        if (org.metadata?.slug) {
            persistSlug(org.metadata.slug);
        }
    }, []);
    const value = useMemo(() => ({
        orgs,
        activeOrg,
        setActiveOrg,
        isLoading,
        error,
        retry: load,
        refresh: load,
    }), [orgs, activeOrg, setActiveOrg, isLoading, error, load]);
    return _jsx(OrgContext.Provider, { value: value, children: children });
}
/**
 * Access the active organization context from the nearest
 * {@link OrgProvider}.
 *
 * Throws if called outside an `<OrgProvider>` — this surfaces wiring
 * mistakes immediately during development.
 */
export function useOrg() {
    const ctx = useContext(OrgContext);
    if (!ctx) {
        throw new Error("useOrg must be used within <OrgProvider>. " +
            "Wrap your component tree with <OrgProvider> inside a <StigmerProvider>.");
    }
    return ctx;
}
/**
 * Convenience accessor: returns the active org's slug for use in API
 * calls, or an empty string when no org is selected.
 */
export function useActiveOrgSlug() {
    const { activeOrg } = useOrg();
    return activeOrg?.metadata?.slug ?? "";
}
//# sourceMappingURL=OrgProvider.js.map