import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import React, { useState, useEffect, useCallback } from 'react';
import { Box, Text } from 'ink';
import Spinner from 'ink-spinner';
import { Colors } from '../../colors.js';
import { useKeypress } from '../../hooks/useKeypress.js';
export const AuthenticationStep = ({ provider, method, onComplete, onError, onBack, triggerAuth, isFocused = true, }) => {
    const [apiKey, setApiKey] = useState('');
    const [isAuthenticating, setIsAuthenticating] = useState(false);
    const providerDisplay = provider.charAt(0).toUpperCase() + provider.slice(1);
    const handleApiKeySubmit = useCallback(async () => {
        if (!apiKey.trim()) {
            return;
        }
        setIsAuthenticating(true);
        try {
            await triggerAuth(provider, 'api_key', apiKey.trim());
            onComplete();
        }
        catch (error) {
            setIsAuthenticating(false);
            onError(error instanceof Error ? error.message : String(error));
        }
    }, [apiKey, provider, triggerAuth, onComplete, onError]);
    // Handle keyboard input for API key mode
    useKeypress((key) => {
        if (key.name === 'escape' && !isAuthenticating) {
            onBack();
            return;
        }
        if (method !== 'api_key' || isAuthenticating) {
            return;
        }
        if (key.name === 'return') {
            // eslint-disable-next-line @typescript-eslint/no-floating-promises
            handleApiKeySubmit();
            return;
        }
        if (key.name === 'backspace' || key.name === 'delete') {
            setApiKey((prev) => prev.slice(0, -1));
            return;
        }
        // Accept printable characters (including paste - multi-char sequences)
        const char = key.sequence;
        if (char && !key.ctrl && !key.meta) {
            // Filter to only printable ASCII characters (handles both typing and paste)
            const printable = char.replace(/[^\x20-\x7E]/g, '');
            if (printable) {
                setApiKey((prev) => prev + printable);
            }
        }
    }, { isActive: isFocused });
    // Start OAuth flow automatically - use ref to prevent double-execution
    // React Strict Mode or dependency changes can cause this effect to re-run
    const authStartedRef = React.useRef(false);
    useEffect(() => {
        if (method === 'oauth' && !authStartedRef.current) {
            authStartedRef.current = true;
            setIsAuthenticating(true);
            triggerAuth(provider, 'oauth')
                .then(() => {
                onComplete();
            })
                .catch((error) => {
                setIsAuthenticating(false);
                onError(error instanceof Error ? error.message : String(error));
            });
        }
    }, [method, provider, triggerAuth, onComplete, onError]);
    if (method === 'oauth') {
        return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { flexDirection: "column", marginBottom: 1, children: _jsxs(Text, { bold: true, color: Colors.AccentCyan, children: ["Step 4 of 5: Authenticating with ", providerDisplay] }) }), _jsx(Box, { marginBottom: 1, children: _jsxs(Text, { color: Colors.Foreground, children: [_jsx(Text, { color: Colors.AccentYellow, children: _jsx(Spinner, { type: "dots" }) }), ' ', "Opening browser for OAuth authentication..."] }) }), _jsx(Text, { color: Colors.Foreground, children: "Please complete the authentication in your browser." }), _jsx(Text, { color: Colors.Foreground, children: "This window will update when done." }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: Colors.Gray, children: "Press Esc to cancel and go back" }) })] }));
    }
    const maskedValue = '•'.repeat(apiKey.length);
    return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { flexDirection: "column", marginBottom: 1, children: _jsx(Text, { bold: true, color: Colors.AccentCyan, children: "Step 4 of 5: Enter Your API Key" }) }), isAuthenticating ? (_jsx(Box, { marginBottom: 1, children: _jsxs(Text, { color: Colors.Foreground, children: [_jsx(Text, { color: Colors.AccentYellow, children: _jsx(Spinner, { type: "dots" }) }), ' ', "Validating API key..."] }) })) : (_jsxs(_Fragment, { children: [_jsx(Box, { marginBottom: 1, children: _jsxs(Text, { color: Colors.Foreground, children: ["Enter your ", providerDisplay, " API key:"] }) }), _jsxs(Box, { children: [_jsx(Text, { color: Colors.Foreground, children: "API Key: " }), _jsx(Text, { color: Colors.Foreground, children: maskedValue }), _jsx(Text, { color: Colors.AccentCyan, children: "\u258C" })] })] })), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: Colors.Gray, children: "Press Enter when done, Esc to go back" }) })] }));
};
//# sourceMappingURL=AuthenticationStep.js.map