"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useState } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage, iamRoleDisplayName } from "@stigmer/sdk";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { useInvitationPreview } from "./useInvitationPreview";
import { useRedeemInvitation } from "./useRedeemInvitation";
/**
 * Self-contained invite acceptance flow.
 *
 * Fetches the invitation preview by token (public endpoint, no auth
 * required), displays the organization info and role being offered,
 * and provides an accept button that redeems the invitation.
 *
 * Handles all states: loading, invalid (expired / revoked / fully
 * redeemed), authentication required, redemption in flight,
 * success, and error — with appropriate UX for each.
 *
 * The component is auth-agnostic: it delegates authentication
 * decisions to the host application via `isAuthenticated` and
 * `onAuthRequired` props. Platform builders who render this
 * component only for authenticated users can ignore both props.
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <InvitationRedemption
 *   token={tokenFromUrl}
 *   onAccepted={(inv) => router.push("/dashboard")}
 * />
 *
 * <InvitationRedemption
 *   token={tokenFromUrl}
 *   isAuthenticated={!!currentUser}
 *   onAccepted={(inv) => router.push(`/org/${inv.metadata?.org}`)}
 *   onAuthRequired={() => router.push(`/login?return=/invite/${token}`)}
 * />
 * ```
 */
export function InvitationRedemption({ token, isAuthenticated = true, onAccepted, onAuthRequired, className, }) {
    const { preview, isLoading, error: fetchError, refetch } = useInvitationPreview(token);
    const { redeem, isRedeeming, error: redeemError, clearError } = useRedeemInvitation();
    const [accepted, setAccepted] = useState(null);
    const handleAccept = useCallback(async () => {
        clearError();
        try {
            const invitation = await redeem(token);
            setAccepted(invitation);
            onAccepted?.(invitation);
        }
        catch {
            // error state is managed by useRedeemInvitation
        }
    }, [token, redeem, clearError, onAccepted]);
    // Loading state
    if (isLoading) {
        return (_jsx("div", { className: cn("mx-auto max-w-sm", className), "aria-busy": "true", "aria-label": "Loading invitation", children: _jsx(LoadingSkeleton, {}) }));
    }
    // Fetch error
    if (fetchError) {
        return (_jsx("div", { className: cn("mx-auto max-w-sm", className), children: _jsx(ErrorCard, { message: getUserMessage(fetchError), onRetry: refetch }) }));
    }
    // No preview returned
    if (!preview) {
        return (_jsx("div", { className: cn("mx-auto max-w-sm", className), children: _jsx(ErrorCard, { message: "This invitation could not be found." }) }));
    }
    // Redemption success
    if (accepted) {
        const orgName = preview.organizationName || "the organization";
        const roleName = iamRoleDisplayName(preview.role);
        return (_jsx("div", { className: cn("mx-auto max-w-sm", className), children: _jsxs("div", { className: "rounded-lg border border-primary/30 bg-primary-subtle p-6 text-center", children: [_jsx(SuccessIcon, {}), _jsxs("h2", { className: "mt-3 text-base font-semibold text-foreground", children: ["You\u2019ve joined ", orgName] }), _jsxs("p", { className: "mt-1 text-sm text-muted-foreground", children: ["You now have ", _jsx("span", { className: "font-medium text-foreground", children: roleName }), " access."] })] }) }));
    }
    const orgName = preview.organizationName || "Unknown organization";
    const orgLogo = preview.organizationLogoUrl;
    const orgInitial = orgName.charAt(0).toUpperCase();
    const roleName = iamRoleDisplayName(preview.role);
    const expiresAt = preview.expiresAt ? timestampDate(preview.expiresAt) : null;
    return (_jsx("div", { className: cn("mx-auto max-w-sm", className), children: _jsxs("div", { className: "rounded-lg border border-border bg-card p-6", children: [_jsxs("div", { className: "flex flex-col items-center text-center", children: [orgLogo ? (_jsx("img", { src: orgLogo, alt: `${orgName} logo`, className: "size-12 rounded-full object-cover" })) : (_jsx("div", { className: "flex size-12 items-center justify-center rounded-full bg-muted text-lg font-semibold text-muted-foreground", children: orgInitial })), _jsxs("h2", { className: "mt-3 text-base font-semibold text-foreground", children: ["Join ", orgName] }), preview.label && (_jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: preview.label }))] }), _jsxs("div", { className: "mt-4 flex items-center justify-center gap-3 text-xs text-muted-foreground", children: [_jsxs("span", { className: "inline-flex items-center gap-1", children: [_jsx(ShieldIcon, {}), roleName, " access"] }), expiresAt && (_jsxs(_Fragment, { children: [_jsx(Separator, {}), _jsx("span", { children: formatExpiry(expiresAt) })] }))] }), !preview.isValid && (_jsx(InvalidNotice, { reason: preview.invalidReason })), preview.isValid && (_jsx("div", { className: "mt-5", children: isAuthenticated ? (_jsxs(_Fragment, { children: [_jsxs("button", { type: "button", onClick: handleAccept, disabled: isRedeeming, className: cn("w-full inline-flex items-center justify-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium", "bg-primary text-primary-foreground hover:bg-primary-hover", "disabled:pointer-events-none disabled:opacity-50", "transition-colors"), children: [isRedeeming && _jsx(SpinnerIcon, {}), isRedeeming ? "Accepting\u2026" : "Accept Invitation"] }), redeemError && (_jsx("p", { className: "mt-2 text-center text-[0.65rem] text-destructive", role: "alert", children: getUserMessage(redeemError) }))] })) : (_jsx("button", { type: "button", onClick: onAuthRequired, className: cn("w-full inline-flex items-center justify-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium", "bg-primary text-primary-foreground hover:bg-primary-hover", "transition-colors"), children: "Sign in to accept" })) }))] }) }));
}
// ---------------------------------------------------------------------------
// InvalidNotice (internal)
// ---------------------------------------------------------------------------
function InvalidNotice({ reason }) {
    return (_jsxs("div", { className: "mt-4 rounded-md bg-muted-subtle px-3 py-2.5 text-center", children: [_jsx(WarningIcon, {}), _jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: reason || "This invitation is no longer valid." })] }));
}
// ---------------------------------------------------------------------------
// ErrorCard (internal)
// ---------------------------------------------------------------------------
function ErrorCard({ message, onRetry, }) {
    return (_jsxs("div", { className: "rounded-lg border border-destructive/30 bg-destructive-subtle p-6 text-center", children: [_jsx("p", { className: "text-sm text-destructive", children: message }), onRetry && (_jsx("button", { type: "button", onClick: onRetry, className: cn("mt-3 inline-flex items-center rounded-md px-3 py-1.5 text-xs font-medium", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "transition-colors"), children: "Try again" }))] }));
}
// ---------------------------------------------------------------------------
// LoadingSkeleton (internal)
// ---------------------------------------------------------------------------
function LoadingSkeleton() {
    return (_jsxs("div", { className: "rounded-lg border border-border bg-card p-6 space-y-4", children: [_jsxs("div", { className: "flex flex-col items-center gap-3", children: [_jsx("div", { className: "size-12 rounded-full bg-muted-subtle animate-pulse" }), _jsx("div", { className: "h-5 w-40 rounded bg-muted-subtle animate-pulse" }), _jsx("div", { className: "h-4 w-56 rounded bg-muted-subtle animate-pulse" })] }), _jsxs("div", { className: "flex justify-center gap-3", children: [_jsx("div", { className: "h-4 w-24 rounded bg-muted-subtle animate-pulse" }), _jsx("div", { className: "h-4 w-24 rounded bg-muted-subtle animate-pulse" })] }), _jsx("div", { className: "h-10 w-full rounded-md bg-muted-subtle animate-pulse" })] }));
}
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
function formatExpiry(date) {
    const now = Date.now();
    const diffMs = date.getTime() - now;
    if (diffMs <= 0)
        return "Expired";
    const days = Math.ceil(diffMs / 86_400_000);
    if (days === 1)
        return "Expires tomorrow";
    if (days <= 30)
        return `Expires in ${days} days`;
    return `Expires ${date.toLocaleDateString(undefined, {
        month: "short",
        day: "numeric",
        year: "numeric",
    })}`;
}
// ---------------------------------------------------------------------------
// Separator (internal)
// ---------------------------------------------------------------------------
function Separator() {
    return (_jsx("span", { className: "text-border", "aria-hidden": "true", children: "\u00B7" }));
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function ShieldIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", className: "shrink-0", children: _jsx("path", { d: "M8 1.5l5.5 2v4.5c0 3.5-2.5 5.5-5.5 7-3-1.5-5.5-3.5-5.5-7V3.5L8 1.5z" }) }));
}
function WarningIcon() {
    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", className: "mx-auto text-muted-foreground", children: [_jsx("circle", { cx: "8", cy: "8", r: "6" }), _jsx("path", { d: "M8 5v3.5M8 10.5v.5" })] }));
}
function SuccessIcon() {
    return (_jsxs("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", className: "mx-auto text-primary", children: [_jsx("circle", { cx: "12", cy: "12", r: "10" }), _jsx("path", { d: "M8 12l2.5 2.5L16 9" })] }));
}
function SpinnerIcon() {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
//# sourceMappingURL=InvitationRedemption.js.map