import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * EmailCaptureScreen — Collect user email on the create-account onboarding path
 * (`--auth-onboarding create-account`; legacy alias: `--signup`).
 *
 * Required before Terms of Service acceptance. Pre-populates from `--email` /
 * `WizardSession.signupEmail` when the CLI or session already supplied them.
 */
import { Box, Text } from 'ink';
import { useMemo, useState } from 'react';
import { TextInput } from '@inkjs/ui';
import { useWizardStore } from '../hooks/useWizardStore.js';
import { useScreenInput } from '../hooks/useScreenInput.js';
import { Colors, Icons } from '../styles.js';
import { useScreenHints } from '../hooks/useScreenHints.js';
import { DEFAULT_AMPLITUDE_ZONE, EMAIL_REGEX, } from '../../../lib/constants.js';
import { performDirectSignup } from '../../../utils/direct-signup.js';
import { replaceStoredUser } from '../../../utils/ampli-settings.js';
import { fetchAmplitudeUser } from '../../../lib/api.js';
import { PickerMenu } from '../primitives/index.js';
import { analytics } from '../../../utils/analytics.js';
import { resolveZone } from '../../../lib/zone-resolution.js';
const EXISTING_USER_OPTIONS = [
    { label: 'Log in with existing account', value: 'login' },
    { label: 'Use a different email', value: 'retry' },
    { label: 'Cancel', value: 'cancel' },
];
export const EmailCaptureScreen = ({ store }) => {
    useWizardStore(store);
    const { session } = store;
    const [email, setEmail] = useState(session.signupEmail ?? '');
    const [step, setStep] = useState('email');
    const [error, setError] = useState(null);
    const [isChecking, setIsChecking] = useState(false);
    const [inputKey, setInputKey] = useState(0);
    // TextInput from @inkjs/ui does not surface Esc — handle it here so the user
    // can return to the name step, router-back, or rewind to Welcome (draft cleared).
    const routerCanGoBack = store.canGoBack();
    const hints = useMemo(() => {
        const base = [{ key: 'Enter', label: 'Continue' }];
        if (step === 'name' || step === 'existing_user') {
            base.push({ key: 'Esc', label: 'Back' });
        }
        else if (routerCanGoBack) {
            base.push({ key: 'Esc', label: 'Back' });
        }
        else {
            base.push({ key: 'Esc', label: 'Welcome' });
        }
        return base;
    }, [step, routerCanGoBack]);
    useScreenHints(hints);
    useScreenInput((_input, key) => {
        if (!key.escape || isChecking)
            return;
        if (step === 'name') {
            setStep('email');
            setError(null);
            setInputKey((k) => k + 1);
            return;
        }
        if (step === 'existing_user') {
            setEmail('');
            setError(null);
            setStep('email');
            return;
        }
        analytics.wizardCapture('signup email screen back', {});
        if (store.canGoBack()) {
            store.goBack();
            return;
        }
        store.backToWelcome();
    }, { isActive: !isChecking });
    const handleEmailSubmit = (value) => {
        const trimmed = value.trim();
        if (!trimmed) {
            setError('Email is required');
            return;
        }
        if (!EMAIL_REGEX.test(trimmed)) {
            setError('Please enter a valid email address');
            return;
        }
        setEmail(trimmed);
        setError(null);
        setStep('name');
        setInputKey((k) => k + 1); // Force input to clear
    };
    const handleNameSubmit = async (value) => {
        const trimmed = value.trim();
        if (!trimmed) {
            setError('Full name is required');
            return;
        }
        setError(null);
        setIsChecking(true);
        const zone = resolveZone(session, DEFAULT_AMPLITUDE_ZONE, {
            readDisk: false,
        });
        try {
            const result = await performDirectSignup({
                email,
                fullName: trimmed,
                zone,
            });
            if (result.kind === 'error' && result.code === 'user_already_exists') {
                analytics.wizardCapture('existing user detected during signup', {
                    zone,
                    'error code': result.code,
                });
                setIsChecking(false);
                setStep('existing_user');
                return;
            }
            if (result.kind === 'success') {
                const tokens = {
                    accessToken: result.tokens.accessToken,
                    idToken: result.tokens.idToken,
                    refreshToken: result.tokens.refreshToken,
                    expiresAt: result.tokens.expiresAt,
                };
                let user;
                try {
                    const userInfo = await fetchAmplitudeUser(tokens.idToken, zone);
                    user = {
                        id: userInfo.id,
                        firstName: userInfo.firstName,
                        lastName: userInfo.lastName,
                        email: userInfo.email,
                        zone,
                        tosAccepted: true,
                        tosAcceptedAt: new Date().toISOString(),
                    };
                }
                catch {
                    const parts = trimmed.split(/\s+/);
                    user = {
                        id: 'pending',
                        firstName: parts[0] ?? '',
                        lastName: parts.slice(1).join(' '),
                        email,
                        zone,
                        tosAccepted: true,
                        tosAcceptedAt: new Date().toISOString(),
                    };
                }
                replaceStoredUser(user, tokens);
                store.markSignupTokensObtained();
            }
            setIsChecking(false);
            store.setSignupEmail(email);
            store.setSignupFullName(trimmed);
            store.markEmailCaptureComplete();
        }
        catch {
            setIsChecking(false);
            store.setSignupEmail(email);
            store.setSignupFullName(trimmed);
            store.markEmailCaptureComplete();
        }
    };
    const handleExistingUserChoice = (value) => {
        const choice = Array.isArray(value) ? value[0] : value;
        if (choice === 'login') {
            store.switchToLogin();
            store.markEmailCaptureComplete();
        }
        else if (choice === 'retry') {
            setEmail('');
            setError(null);
            setStep('email');
        }
        else {
            store.cancelWizard('User cancelled signup');
        }
    };
    if (step === 'existing_user') {
        return (_jsxs(Box, { flexDirection: "column", flexGrow: 1, children: [_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { bold: true, color: Colors.heading, children: "Account already exists" }), _jsxs(Text, { color: Colors.muted, children: ["The email ", _jsx(Text, { bold: true, children: email }), " is already registered."] })] }), _jsx(Box, { flexDirection: "column", marginBottom: 1, children: _jsx(Text, { children: "What would you like to do?" }) }), _jsx(PickerMenu, { options: EXISTING_USER_OPTIONS, onSelect: handleExistingUserChoice })] }));
    }
    return (_jsxs(Box, { flexDirection: "column", flexGrow: 1, children: [_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { bold: true, color: Colors.heading, children: "Create your Amplitude account" }), _jsx(Text, { color: Colors.muted, children: step === 'email'
                            ? 'Enter your email to get started'
                            : 'Enter your full name' })] }), _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [isChecking ? (_jsxs(Text, { color: Colors.muted, children: [Icons.dot, " Checking account status..."] })) : step === 'email' ? (_jsx(TextInput, { defaultValue: email, placeholder: "your.email@example.com", onSubmit: handleEmailSubmit }, `email-${inputKey}`)) : (_jsx(TextInput, { defaultValue: session.signupFullName ?? '', placeholder: "First Last", onSubmit: (value) => {
                            void handleNameSubmit(value);
                        } }, `name-${inputKey}`)), error && (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { color: Colors.error, children: [Icons.cross, " ", error] }) }))] }), !isChecking && (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { color: Colors.muted, children: [Icons.dot, " We'll use this to create your Amplitude account"] }), step === 'email' && (_jsxs(Text, { color: Colors.muted, children: [Icons.dot, " You'll need to accept our Terms of Service after"] }))] }))] }));
};
