"use client";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { OAUTH_CALLBACK_MESSAGE_TYPE, OAUTH_BROADCAST_CHANNEL, } from "./useMcpServerOAuthConnect";
/**
 * Lightweight component for OAuth callback pages.
 *
 * Render this component at the URL configured as your OAuth redirect
 * URI (`STIGMER_OAUTH_REDIRECT_URI`). It extracts the `code` and
 * `state` query parameters from the current URL, posts them back to
 * the opener window via `window.postMessage`, and closes the popup.
 *
 * The component handles three scenarios:
 * 1. **Popup with opener** (primary): posts the message and closes.
 * 2. **No opener, `onFallback` provided**: calls the fallback with
 *    the extracted parameters so the host app can handle them.
 * 3. **No opener, no fallback**: shows a message asking the user to
 *    return to the main window.
 *
 * Platform builders create a route in their application that renders
 * this component:
 *
 * @example
 * ```tsx
 * // app/auth/oauth/callback/page.tsx (Next.js)
 * import { OAuthCallbackHandler } from "@stigmer/react";
 *
 * export default function OAuthCallbackPage() {
 *   return <OAuthCallbackHandler />;
 * }
 * ```
 */
export function OAuthCallbackHandler({ onFallback, className, }) {
    const [status, setStatus] = useState("processing");
    const [errorMessage, setErrorMessage] = useState(null);
    const didRun = useRef(false);
    useEffect(() => {
        if (didRun.current)
            return;
        didRun.current = true;
        const params = new URLSearchParams(window.location.search);
        const code = params.get("code");
        const state = params.get("state");
        const oauthError = params.get("error");
        if (oauthError) {
            const description = params.get("error_description") || oauthError;
            setErrorMessage(`Authentication failed: ${description}`);
            setStatus("error");
            return;
        }
        if (!code || !state) {
            setErrorMessage("Missing authorization code or state parameter. " +
                "This page should only be reached via an OAuth redirect.");
            setStatus("error");
            return;
        }
        const message = {
            type: OAUTH_CALLBACK_MESSAGE_TYPE,
            code,
            state,
        };
        // Always broadcast via BroadcastChannel — works even when
        // Cross-Origin-Opener-Policy has severed window.opener.
        let broadcastSent = false;
        try {
            const bc = new BroadcastChannel(OAUTH_BROADCAST_CHANNEL);
            bc.postMessage(message);
            bc.close();
            broadcastSent = true;
        }
        catch {
            // BroadcastChannel unavailable — rely on postMessage below.
        }
        const opener = window.opener;
        if (opener && !opener.closed) {
            try {
                opener.postMessage(message, window.location.origin);
                setStatus("done");
                window.close();
            }
            catch {
                if (broadcastSent) {
                    setStatus("done");
                    window.close();
                }
                else {
                    setErrorMessage("Could not communicate with the parent window. " +
                        "Please close this tab and try again.");
                    setStatus("error");
                }
            }
            return;
        }
        // opener is null (COOP case) but BroadcastChannel delivered the message.
        if (broadcastSent) {
            setStatus("done");
            window.close();
            return;
        }
        if (onFallback) {
            onFallback({ code, state });
            setStatus("done");
            return;
        }
        setStatus("no-opener");
    }, [onFallback]);
    return (_jsx("div", { className: cn("flex min-h-[200px] items-center justify-center p-8", className), children: _jsxs("div", { className: "max-w-sm text-center", children: [status === "processing" && (_jsxs(_Fragment, { children: [_jsx(Spinner, {}), _jsx("p", { className: "mt-3 text-sm text-muted-foreground", children: "Completing authentication..." })] })), status === "done" && (_jsx("p", { className: "text-sm text-muted-foreground", children: "Authentication complete. You can close this window." })), status === "no-opener" && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, {}), _jsx("p", { className: "mt-3 text-sm font-medium text-foreground", children: "Authentication successful" }), _jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: "Please close this tab and return to the application to continue." })] })), status === "error" && (_jsxs(_Fragment, { children: [_jsx(WarningIcon, {}), _jsx("p", { className: "mt-3 text-sm font-medium text-destructive", children: "Authentication failed" }), errorMessage && (_jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: errorMessage }))] }))] }) }));
}
// ---------------------------------------------------------------------------
// Icons -- inline SVGs (no external icon dependency, matches SDK pattern)
// ---------------------------------------------------------------------------
function Spinner() {
    return (_jsx("svg", { width: "24", height: "24", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "mx-auto animate-spin text-muted-foreground", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
function CheckIcon() {
    return (_jsx("svg", { width: "24", height: "24", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", className: "mx-auto text-success", "aria-hidden": "true", children: _jsx("path", { d: "m3 8.5 3.5 3.5 6.5-8" }) }));
}
function WarningIcon() {
    return (_jsxs("svg", { width: "24", height: "24", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "mx-auto text-destructive", "aria-hidden": "true", children: [_jsx("path", { d: "M8 1.5 1 14h14L8 1.5Z" }), _jsx("path", { d: "M8 6v3.5" }), _jsx("circle", { cx: "8", cy: "11.5", r: "0.5", fill: "currentColor", stroke: "none" })] }));
}
//# sourceMappingURL=OAuthCallbackHandler.js.map