import * as react from 'react';
import { ReactNode } from 'react';
import * as react_jsx_runtime from 'react/jsx-runtime';
import { z } from 'zod';

declare const workOsOrgIdBrand: unique symbol;
/** A WorkOS organization id (`org_...`) -- the auth identity for API/SSE/query keys. */
type WorkOsOrgId = string & {
    readonly [workOsOrgIdBrand]: true;
};

declare const AccessKeyInputSchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
    systemPath: z.ZodString;
    action: z.ZodDefault<z.ZodEnum<{
        view: "view";
        manage: "manage";
    }>>;
}, z.core.$strict>]>;
type AccessKeyInput = z.input<typeof AccessKeyInputSchema>;
declare const AccessKeys: {
    readonly platformAdmin: {
        readonly systemPath: "platform.admin";
        readonly action: "view";
    };
    readonly organizationManage: {
        readonly systemPath: "permission.org";
        readonly action: "manage";
    };
    readonly membersManage: {
        readonly systemPath: "permission.members";
        readonly action: "manage";
    };
    readonly rolesManage: {
        readonly systemPath: "permission.roles";
        readonly action: "manage";
    };
    /** @reserved Reserved for first-class secret administration routes and command surfaces. */
    readonly secretsManage: {
        readonly systemPath: "permission.secrets";
        readonly action: "manage";
    };
    readonly operationsRead: {
        readonly systemPath: "permission.operations";
        readonly action: "view";
    };
    /** @reserved Reserved for write-level operations administration beyond read-only monitoring. */
    readonly operationsManage: {
        readonly systemPath: "permission.operations";
        readonly action: "manage";
    };
    readonly leadGenManage: {
        readonly systemPath: "sales.lead-gen";
        readonly action: "manage";
    };
    /** @reserved Reserved for acquisition administration once that permission namespace is wired. */
    readonly acquisitionManage: {
        readonly systemPath: "permission.acquisition";
        readonly action: "manage";
    };
    /** @reserved Reserved for project administration permission catalog compatibility. */
    readonly projectsManage: {
        readonly systemPath: "permission.projects";
        readonly action: "manage";
    };
    /** @reserved Reserved for client administration permission catalog compatibility. */
    readonly clientsManage: {
        readonly systemPath: "permission.clients";
        readonly action: "manage";
    };
    readonly operationsOverview: {
        readonly systemPath: "diagnostic.operations.overview";
        readonly action: "view";
    };
    /** @reserved Reserved for a diagnostics surface that lists recent operations executions. */
    readonly operationsRecentExecutions: {
        readonly systemPath: "diagnostic.operations.recent-executions";
        readonly action: "view";
    };
    readonly monitoringExecutionLogs: {
        readonly systemPath: "diagnostic.monitoring.execution-logs";
        readonly action: "view";
    };
    readonly monitoringNotifications: {
        readonly systemPath: "diagnostic.monitoring.notifications";
        readonly action: "view";
    };
};

type AccessRestrictedBy = 'catalog' | 'membership' | 'system-lifecycle' | 'role-permission' | 'diagnostic-allowlist' | null;
type AccessReason = 'allowed' | 'platform-admin-bypass' | 'invalid-access-key' | 'unknown-access-key' | 'organization-mismatch' | 'missing-membership' | 'system-not-active' | 'role-permission-denied' | 'diagnostic-key-not-allowed';
interface AccessAnswer {
    allowed: boolean;
    restrictedBy: AccessRestrictedBy;
    reason: AccessReason;
}

interface AuthContextValue {
    user: {
        id: string;
    } | null;
    isLoading: boolean;
    getAccessToken: () => Promise<string>;
    organizationId?: WorkOsOrgId | null;
    /**
     * Trigger WorkOS AuthKit's sign-in flow (redirect to WorkOS hosted auth page).
     * Used by ProtectedRoute for auto-recovery when `canRecover()` returns true.
     */
    signIn: (options?: {
        state?: {
            returnTo?: string;
        };
    }) => void;
    /**
     * Returns true when a previous session can be recovered (refresh token
     * exists in storage). ProtectedRoute calls `signIn()` only when this returns
     * true; otherwise it navigates to the login page.
     *
     * Explicit logout clears the stored token, so canRecover() returns false
     * and the user sees the login page as expected.
     */
    canRecover: () => boolean;
}
declare function useAuthContext(): AuthContextValue;
declare function AuthProvider({ value, children }: {
    value: AuthContextValue;
    children: ReactNode;
}): react.FunctionComponentElement<react.ProviderProps<AuthContextValue | null>>;

/**
 * Returns a stable reference to getAccessToken that won't change between renders
 *
 * This prevents SSE connections from reconnecting unnecessarily when the
 * WorkOS useAuth hook returns a new getAccessToken function reference
 *
 * @example
 * ```tsx
 * const getAccessToken = useStableAccessToken()
 *
 * useEffect(() => {
 *   fetchEventSourceWithTokenRefresh({
 *     getToken: getAccessToken,
 *     // ...
 *   })
 * }, [getAccessToken]) // Won't re-run on every render
 * ```
 */
declare function useStableAccessToken(): () => Promise<string>;

/**
 * Checks WorkOS session validity when window/tab regains focus
 *
 * When window or tab becomes visible after inactivity, validates session
 * by attempting to get access token. If session expired (WorkOS inactivity
 * timeout exceeded), signs out user and redirects to login.
 *
 * How it works:
 * 1. Window/tab regains focus after inactivity
 * 2. Cancel all pending queries to prevent 401 error cascade
 * 3. Attempt to get access token from WorkOS
 * 4. If successful: Resume queries with fresh token
 * 5. If failed (session expired): Sign out and redirect to login
 *
 * @example
 * // In __root.tsx
 * export function RootLayoutComponent() {
 *   useSessionCheck()
 *   return <YourApp />
 * }
 */
declare function useSessionCheck(): void;

interface InitializationError {
    layer: 'auth' | 'profile' | 'organization';
    message: string;
    originalError?: Error;
}

interface ProtectedRouteProps {
    children: ReactNode;
    /**
     * Path to redirect to when user is unauthenticated and the auth adapter
     * does not provide a `signIn` function.
     * @default '/login'
     */
    redirectTo?: string;
    /**
     * Rendered while initialization is in progress.
     * When not provided, nothing is rendered during initialization.
     */
    fallback?: ReactNode;
    /**
     * Rendered when initialization fails with a non-organization error.
     * Receives the error and a retry callback.
     * When not provided, the error is silently swallowed (children not rendered).
     */
    errorFallback?: (error: InitializationError, retry: () => void) => ReactNode;
    /**
     * When true (default), waits for both user AND organization to be ready
     * before rendering children. When false, only waits for user readiness.
     * @default true
     */
    waitForOrganization?: boolean;
}
/**
 * Headless route guard for authenticated pages.
 *
 * Reads initialization state from the nearest InitializationProvider.
 *
 * When `canRecover()` returns true (refresh token exists), unauthenticated users
 * are sent directly to WorkOS AuthKit via `signIn()`. WorkOS checks its
 * server-side session and either signs the user in immediately (page-reload case)
 * or shows a login form (logged-out case). Explicit logout destroys the
 * server-side session, so the next auto-signIn correctly presents a login form
 * rather than looping.
 *
 * When `canRecover()` returns false, falls back to navigating to `redirectTo`
 * (default: '/login') with a `returnTo` search param.
 *
 * Organization-layer errors are allowed through -- routes like /invitations
 * must be accessible even when the user has no org membership.
 *
 * @example
 * // With custom fallback (your Mantine loader):
 * <ProtectedRoute fallback={<AppShellLoader />}>
 *   <DashboardPage />
 * </ProtectedRoute>
 *
 * @example
 * // Wait only for user, not org (e.g. /invitations route):
 * <ProtectedRoute waitForOrganization={false}>
 *   <InvitationsPage />
 * </ProtectedRoute>
 */
declare function ProtectedRoute({ children, redirectTo, fallback, errorFallback, waitForOrganization }: ProtectedRouteProps): react_jsx_runtime.JSX.Element | null;

interface UseAccessResult extends AccessAnswer {
    isReady: boolean;
    isPlatformAdmin: boolean;
    permissions: readonly string[];
}

interface AccessGuardProps {
    accessKey: AccessKeyInput;
    children: ReactNode;
    fallback?: ReactNode | ((answer: UseAccessResult) => ReactNode);
    loadingFallback?: ReactNode;
    redirectTo?: string | null;
}
/**
 * Unified route/UI guard for the shared Access Model.
 */
declare function AccessGuard({ accessKey, children, fallback, loadingFallback, redirectTo }: AccessGuardProps): react_jsx_runtime.JSX.Element;

export { AccessGuard, AccessKeys, AuthProvider, ProtectedRoute, useAuthContext, useSessionCheck as useRefocusSessionCheck, useSessionCheck, useStableAccessToken };
export type { AccessGuardProps, AccessKeyInput, AuthContextValue, ProtectedRouteProps };
