'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useRef } from 'react';
import { ChevronLeft, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { getAllAgentModels } from '../../../app/actions/get-all-agent-models.js';
import { updateAgentAndModel } from '../../../app/actions/update-agent-and-model.js';
import { getAgentTypeIcon } from '../../common/feature-node/agent-type-icons.js';
import { getModelMeta } from '../../../lib/model-metadata.js';
import { cn } from '../../../lib/utils.js';
const STEPS = ['select-agent', 'select-model'];
export function WelcomeAgentSetup({ onComplete, className }) {
    const { t } = useTranslation('web');
    const [groups, setGroups] = useState([]);
    const [loading, setLoading] = useState(true);
    const [step, setStep] = useState('select-agent');
    const [selectedAgent, setSelectedAgent] = useState(null);
    const [saving, setSaving] = useState(false);
    const [transitioning, setTransitioning] = useState(false);
    const [visible, setVisible] = useState(true);
    const timeoutRef = useRef(undefined);
    useEffect(() => {
        getAllAgentModels()
            .then(setGroups)
            .finally(() => setLoading(false));
    }, []);
    const activeGroup = selectedAgent ? groups.find((g) => g.agentType === selectedAgent) : null;
    const transitionTo = useCallback((nextStep, setup) => {
        setTransitioning(true);
        setVisible(false);
        if (timeoutRef.current)
            clearTimeout(timeoutRef.current);
        timeoutRef.current = setTimeout(() => {
            setup?.();
            setStep(nextStep);
            requestAnimationFrame(() => {
                setVisible(true);
                setTransitioning(false);
            });
        }, 150);
    }, []);
    useEffect(() => {
        return () => {
            if (timeoutRef.current)
                clearTimeout(timeoutRef.current);
        };
    }, []);
    const saveAndComplete = useCallback(async (agentType, model) => {
        setSaving(true);
        try {
            await updateAgentAndModel(agentType, model);
            // Fade out the entire wizard before handing off to the next view
            setVisible(false);
            if (timeoutRef.current)
                clearTimeout(timeoutRef.current);
            timeoutRef.current = setTimeout(() => {
                onComplete();
            }, 200);
        }
        catch {
            setSaving(false);
        }
    }, [onComplete]);
    const handleAgentSelect = useCallback((agentType) => {
        const group = groups.find((g) => g.agentType === agentType);
        if (group && group.models.length > 0) {
            transitionTo('select-model', () => {
                setSelectedAgent(agentType);
            });
        }
        else {
            saveAndComplete(agentType, null);
        }
    }, [groups, transitionTo, saveAndComplete]);
    const handleModelSelect = useCallback((model) => {
        if (!selectedAgent)
            return;
        saveAndComplete(selectedAgent, model);
    }, [selectedAgent, saveAndComplete]);
    const handleBack = useCallback(() => {
        if (step === 'select-model') {
            transitionTo('select-agent', () => {
                setSelectedAgent(null);
            });
        }
    }, [step, transitionTo]);
    if (loading) {
        return (_jsxs("div", { "data-testid": "welcome-agent-setup", className: cn('flex flex-col items-center justify-center gap-4', className), children: [_jsx(Loader2, { className: "text-muted-foreground h-5 w-5 animate-spin" }), _jsx("p", { className: "text-muted-foreground text-sm", children: t('welcome.loadingAgents') })] }));
    }
    const stepIndex = STEPS.indexOf(step);
    // Dynamic hero text per step
    const heroTitle = step === 'select-agent' ? t('welcome.chooseAgent') : t('welcome.pickModel');
    const heroSubtitle = step === 'select-agent'
        ? t('welcome.selectAgentSubtitle')
        : activeGroup
            ? t('welcome.chooseModelSubtitle', { label: activeGroup.label })
            : '';
    return (_jsxs("div", { "data-testid": "welcome-agent-setup", className: cn('flex w-full flex-col items-center', className), children: [_jsx("div", { className: "mb-8 flex w-full max-w-xs items-center gap-1.5", children: STEPS.map((s, i) => (_jsx("div", { className: cn('h-[3px] flex-1 rounded-full transition-colors duration-300', i <= stepIndex ? 'bg-foreground/60' : 'bg-muted') }, s))) }), _jsxs("div", { className: cn('flex w-full flex-col items-center transition-opacity duration-200', visible && !transitioning ? 'opacity-100' : 'opacity-0'), children: [_jsx("h1", { className: "text-foreground/90 text-center text-5xl font-extralight tracking-tight", children: heroTitle }), _jsx("p", { className: "text-muted-foreground mt-3 text-center text-lg leading-relaxed font-light", children: heroSubtitle }), _jsxs("div", { className: "mt-8 flex w-full flex-col items-center", children: [step === 'select-agent' && (_jsx("div", { "data-testid": "agent-list", className: "grid w-full max-w-lg gap-3", style: {
                                    gridTemplateColumns: `repeat(${Math.min(groups.length, 4)}, minmax(0, 1fr))`,
                                }, children: groups.map((group) => {
                                    const GroupIcon = getAgentTypeIcon(group.agentType);
                                    return (_jsxs("button", { type: "button", disabled: saving, "data-testid": `agent-option-${group.agentType}`, className: "border-border hover:bg-accent hover:border-foreground/20 flex cursor-pointer flex-col items-center gap-3 rounded-2xl border px-4 py-5 transition-all duration-150 active:scale-[0.97] disabled:opacity-50", onClick: () => handleAgentSelect(group.agentType), children: [_jsx(GroupIcon, { className: "text-foreground/70 h-7 w-7" }), _jsx("span", { className: "text-sm font-medium", children: group.label })] }, group.agentType));
                                }) })), step === 'select-model' && activeGroup ? (_jsxs("div", { "data-testid": "model-list", className: "flex w-full max-w-lg flex-col items-center gap-4", children: [_jsxs("button", { type: "button", disabled: saving, className: "text-muted-foreground hover:text-foreground flex cursor-pointer items-center gap-1.5 self-start text-sm transition-colors", onClick: handleBack, children: [_jsx(ChevronLeft, { className: "h-4 w-4" }), t('welcome.back')] }), _jsx("div", { className: "grid w-full gap-3", style: {
                                            gridTemplateColumns: `repeat(${Math.min(activeGroup.models.length, 3)}, minmax(0, 1fr))`,
                                        }, children: activeGroup.models.map((m) => {
                                            const meta = getModelMeta(m.id);
                                            return (_jsxs("button", { type: "button", disabled: saving, "data-testid": `model-option-${m.id}`, className: "border-border hover:bg-accent hover:border-foreground/20 flex cursor-pointer flex-col items-center gap-2 rounded-2xl border px-4 py-5 text-center transition-all duration-150 active:scale-[0.97] disabled:opacity-50", onClick: () => handleModelSelect(m.id), children: [_jsx("span", { className: "text-sm font-medium", children: meta.displayName || m.displayName }), _jsx("span", { className: "text-muted-foreground text-xs leading-tight", children: meta.description || m.description })] }, m.id));
                                        }) })] })) : null] })] })] }));
}
