import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * LogoutScreen — Confirms and clears stored OAuth credentials (v2).
 *
 * Used as an overlay triggered by the /logout slash command.
 * Calls clearStoredCredentials() on confirm, then pops the overlay.
 */
import { Box, Text } from 'ink';
import { useState, useEffect, useRef } from 'react';
import { ConfirmationInput } from '../primitives/index.js';
import { Colors } from '../styles.js';
import { clearStoredCredentials } from '../../../utils/ampli-settings.js';
import { clearApiKey } from '../../../utils/api-key-store.js';
import { clearCheckpoint } from '../../../lib/session-checkpoint.js';
import { clearAuthFieldsInAmpliConfig } from '../../../lib/ampli-config.js';
import { wizardSuccessExit } from '../../../utils/wizard-abort.js';
var Phase;
(function (Phase) {
    Phase["Confirm"] = "confirm";
    Phase["Done"] = "done";
})(Phase || (Phase = {}));
export const LogoutScreen = ({ onComplete, installDir, onLoggedOut, }) => {
    const [phase, setPhase] = useState(Phase.Confirm);
    const timerRef = useRef(null);
    // Hard mount-guard for the `process.exit(0)` schedule. Without this,
    // any path that unmounts the LogoutScreen between confirm-click and
    // the 1.5s timer firing (overlay swap, ScreenErrorBoundary retry,
    // back-nav before timer drains) would still kill the whole CLI.
    // Process termination must NEVER outlive its owning screen.
    const mountedRef = useRef(true);
    // Clear any pending timer on unmount + flip the mount flag so the
    // exit callback short-circuits if it's already in the macrotask queue.
    useEffect(() => {
        return () => {
            mountedRef.current = false;
            if (timerRef.current !== null) {
                clearTimeout(timerRef.current);
                timerRef.current = null;
            }
        };
    }, []);
    const handleConfirm = () => {
        clearStoredCredentials();
        clearApiKey(installDir);
        clearCheckpoint(installDir, 'logout');
        // Strip OrgId/ProjectId/Zone from project binding + ampli.json mirror so the next login shows
        // the org + project pickers instead of silently reusing stale IDs.
        // (Back-compat: ampli.json still stores the field as `WorkspaceId`.)
        clearAuthFieldsInAmpliConfig(installDir);
        onLoggedOut?.();
        setPhase(Phase.Done);
        // Exit after a short delay so the user sees the confirmation.
        // Routes through wizardSuccessExit so any pending analytics events
        // (logout-confirmed, session metrics) flush before the process
        // tears down.
        //
        // The mount-guard on the inner callback is belt-and-braces with
        // the unmount cleanup above (PR 338) — even if a queued macrotask
        // sneaks past clearTimeout (e.g. unmount races the timer drain on
        // an overloaded event loop), `mountedRef.current` will be false
        // and we'll skip the exit.
        timerRef.current = setTimeout(() => {
            timerRef.current = null;
            if (mountedRef.current)
                void wizardSuccessExit(0);
        }, 1500);
    };
    return (_jsxs(Box, { flexDirection: "column", flexGrow: 1, children: [_jsx(Text, { bold: true, color: Colors.accent, children: "Log Out" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [phase === Phase.Confirm && (_jsx(ConfirmationInput, { message: "Clear stored Amplitude credentials (wizard session + project binding)?", confirmLabel: "Log out", cancelLabel: "Cancel", onConfirm: handleConfirm, onCancel: onComplete })), phase === Phase.Done && (_jsx(Text, { color: Colors.secondary, children: "Logged out. Restart the wizard to re-authenticate." }))] })] }));
};
