"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { useSsoProvider } from "./useSsoProvider";
/**
 * Org-aware SSO discovery prompt.
 *
 * Guides the user through finding and connecting to their
 * organization's SSO provider:
 *
 * 1. Enter an organization slug (or receive one via `initialOrg`)
 * 2. The component calls {@link useSsoProvider} to look up the SSO
 *    configuration
 * 3. If found, displays a prominent "Sign in with [provider]" button
 * 4. If not found, displays a clear message
 *
 * Platform builders embed this component in their own login pages to
 * offer SSO authentication. The Console composes it with an Auth0
 * fallback and OIDC redirect handling.
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <SsoLoginPrompt
 *   initialOrg="acme"
 *   onSsoLogin={(provider, org) => {
 *     // Initiate OIDC redirect with provider.issuer, provider.oidcClientId
 *   }}
 * />
 * ```
 */
export function SsoLoginPrompt({ initialOrg, onSsoLogin, className, }) {
    const [orgInput, setOrgInput] = useState(initialOrg ?? "");
    const [submittedOrg, setSubmittedOrg] = useState(initialOrg ?? null);
    const { ssoProvider, isLoading, error } = useSsoProvider(submittedOrg);
    const inputRef = useRef(null);
    const phase = resolvePhase(submittedOrg, isLoading, ssoProvider, error);
    // Focus the org input when returning to the input phase.
    useEffect(() => {
        if (phase === "input") {
            inputRef.current?.focus();
        }
    }, [phase]);
    const handleSubmitOrg = useCallback((e) => {
        e.preventDefault();
        const trimmed = orgInput.trim().toLowerCase();
        if (trimmed)
            setSubmittedOrg(trimmed);
    }, [orgInput]);
    const handleReset = useCallback(() => {
        setSubmittedOrg(null);
        setOrgInput("");
    }, []);
    const handleRetry = useCallback(() => {
        if (submittedOrg) {
            setSubmittedOrg(null);
            // Re-trigger after clearing so the hook resets, then re-set.
            queueMicrotask(() => setSubmittedOrg(submittedOrg));
        }
    }, [submittedOrg]);
    const handleSsoClick = useCallback(() => {
        if (ssoProvider && submittedOrg) {
            onSsoLogin(ssoProvider, submittedOrg);
        }
    }, [ssoProvider, submittedOrg, onSsoLogin]);
    const handleSsoKeyDown = useCallback((e) => {
        if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            handleSsoClick();
        }
    }, [handleSsoClick]);
    return (_jsxs("div", { className: cn("w-full", className), role: "region", "aria-label": "SSO sign-in", children: [phase === "input" && (_jsx(OrgInputForm, { ref: inputRef, value: orgInput, onChange: setOrgInput, onSubmit: handleSubmitOrg })), phase === "loading" && (_jsx(LoadingState, { org: submittedOrg })), phase === "found" && ssoProvider && (_jsx(FoundState, { provider: ssoProvider, org: submittedOrg, onClick: handleSsoClick, onKeyDown: handleSsoKeyDown, onChangeOrg: handleReset })), phase === "not-found" && (_jsx(NotFoundState, { org: submittedOrg, onBack: handleReset })), phase === "error" && error && (_jsx(ErrorState, { error: error, onRetry: handleRetry, onBack: handleReset }))] }));
}
// ---------------------------------------------------------------------------
// Phase resolution
// ---------------------------------------------------------------------------
function resolvePhase(submittedOrg, isLoading, ssoProvider, error) {
    if (!submittedOrg)
        return "input";
    if (isLoading)
        return "loading";
    if (error)
        return "error";
    if (ssoProvider)
        return "found";
    return "not-found";
}
// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------
import { forwardRef } from "react";
const OrgInputForm = forwardRef(function OrgInputForm({ value, onChange, onSubmit }, ref) {
    return (_jsxs("form", { onSubmit: onSubmit, className: "space-y-3", children: [_jsx("label", { htmlFor: "sso-org-input", className: "block text-sm font-medium text-foreground", children: "Organization" }), _jsx("input", { ref: ref, id: "sso-org-input", type: "text", value: value, onChange: (e) => onChange(e.target.value), placeholder: "Enter your organization slug", autoComplete: "organization", spellCheck: false, className: cn("block w-full rounded-md border border-input bg-background px-3 py-2", "text-sm text-foreground placeholder:text-muted-foreground", "focus:outline-none focus:ring-2 focus:ring-ring", "transition-colors") }), _jsx("button", { type: "submit", disabled: !value.trim(), className: cn("w-full rounded-md px-4 py-2 text-sm font-medium", "bg-primary text-primary-foreground", "hover:bg-primary-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50", "transition-colors"), children: "Continue" })] }));
});
function LoadingState({ org }) {
    return (_jsxs("div", { className: "flex flex-col items-center gap-3 py-4", "aria-busy": "true", "aria-label": `Looking up SSO provider for ${org}`, children: [_jsx(SpinnerIcon, {}), _jsxs("p", { className: "text-sm text-muted-foreground", children: ["Looking up ", _jsx("span", { className: "font-medium text-foreground", children: org }), "\u2026"] })] }));
}
function FoundState({ provider, org, onClick, onKeyDown, onChangeOrg, }) {
    return (_jsxs("div", { className: "space-y-4", children: [_jsx("div", { className: "text-center", children: _jsxs("p", { className: "text-xs text-muted-foreground", children: ["Signing in to", " ", _jsx("span", { className: "font-medium text-foreground", children: org })] }) }), _jsxs("button", { type: "button", onClick: onClick, onKeyDown: onKeyDown, className: cn("flex w-full items-center justify-center gap-2 rounded-md px-4 py-2.5", "text-sm font-medium", "bg-primary text-primary-foreground", "hover:bg-primary-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "transition-colors"), children: [_jsx(SsoShieldIcon, {}), "Sign in with ", provider.displayName] }), _jsx("button", { type: "button", onClick: onChangeOrg, className: "block w-full text-center text-xs text-muted-foreground hover:text-foreground transition-colors", children: "Not your organization? Change" })] }));
}
function NotFoundState({ org, onBack, }) {
    return (_jsxs("div", { className: "space-y-3 text-center", children: [_jsxs("p", { className: "text-sm text-muted-foreground", children: ["No SSO provider configured for", " ", _jsx("span", { className: "font-medium text-foreground", children: org }), "."] }), _jsx("button", { type: "button", onClick: onBack, className: "text-xs text-primary hover:text-primary-hover transition-colors", children: "Try a different organization" })] }));
}
function ErrorState({ error, onRetry, onBack, }) {
    return (_jsxs("div", { className: "space-y-3 text-center", role: "alert", children: [_jsx("p", { className: "text-sm text-destructive", children: getUserMessage(error) }), _jsxs("div", { className: "flex items-center justify-center gap-3", children: [_jsx("button", { type: "button", onClick: onRetry, className: cn("rounded-md px-3 py-1.5 text-xs font-medium", "bg-primary text-primary-foreground hover:bg-primary-hover", "transition-colors"), children: "Retry" }), _jsx("button", { type: "button", onClick: onBack, className: "text-xs text-muted-foreground hover:text-foreground transition-colors", children: "Back" })] })] }));
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function SpinnerIcon() {
    return (_jsx("svg", { width: "20", height: "20", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin text-muted-foreground", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
function SsoShieldIcon() {
    return (_jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M8 1.5L2 4v4c0 3.5 2.5 5.5 6 7 3.5-1.5 6-3.5 6-7V4L8 1.5z" }), _jsx("path", { d: "M6 8l1.5 1.5L10 6.5" })] }));
}
//# sourceMappingURL=SsoLoginPrompt.js.map