import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { memo, useState, useMemo } from 'react';
import { Settings, ChevronRight, Wallet, Cpu, Zap, User, ChevronDown, RefreshCw, Plus, Pencil, } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { Button } from '../ui/Button';
import { useSettingsStore } from '../../stores/settingsStore';
import { useOnboardingStore } from '../../stores/onboardingStore';
import { useAuthStatus } from '../../hooks/useAuthStatus';
import { useConfig, useAllModels, useUpdateDefaults, } from '../../hooks/useConfig';
import { usePreferences } from '../../hooks/usePreferences';
import { useSetuStore } from '../../stores/setuStore';
import { SetuTopupModal } from './SetuTopupModal';
import { useSetuBalance } from '../../hooks/useSetuBalance';
import { useTopupCallback } from '../../hooks/useTopupCallback';
const SettingsSection = memo(function SettingsSection({ title, icon, children, action, }) {
    return (_jsxs("div", { className: "border-b border-border", children: [_jsxs("div", { className: "px-4 py-3 flex items-center gap-2 bg-muted/30", children: [icon, _jsx("span", { className: "text-sm font-medium flex-1", children: title }), action] }), _jsx("div", { className: "px-4 py-3 space-y-3", children: children })] }));
});
const SettingRow = memo(function SettingRow({ label, value }) {
    return (_jsxs("div", { className: "flex items-center justify-between text-sm", children: [_jsx("span", { className: "text-muted-foreground", children: label }), _jsx("span", { className: "font-mono text-foreground", children: value })] }));
});
const ToggleRow = memo(function ToggleRow({ label, checked, onChange, }) {
    return (_jsxs("div", { className: "flex items-center justify-between text-sm", children: [_jsx("span", { className: "text-muted-foreground", children: label }), _jsx("button", { type: "button", role: "switch", "aria-checked": checked, onClick: () => onChange(!checked), className: `relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${checked ? 'bg-primary' : 'bg-muted'}`, children: _jsx("span", { className: `inline-block h-4 w-4 transform rounded-full transition-transform ${checked ? 'translate-x-6' : 'translate-x-1'} ${checked ? 'bg-primary-foreground' : 'bg-foreground'}` }) })] }));
});
const SelectRow = memo(function SelectRow({ label, value, options, onChange, disabled, }) {
    const [isOpen, setIsOpen] = useState(false);
    const selectedOption = options.find((o) => o.id === value);
    return (_jsxs("div", { className: "flex items-center justify-between text-sm", children: [_jsx("span", { className: "text-muted-foreground", children: label }), _jsxs("div", { className: "relative", children: [_jsxs("button", { type: "button", onClick: () => !disabled && setIsOpen(!isOpen), disabled: disabled, className: "flex items-center gap-1 px-2 py-1 text-xs font-mono bg-muted hover:bg-muted/80 rounded border border-border disabled:opacity-50", children: [_jsx("span", { className: "max-w-[120px] truncate", children: selectedOption?.label || value || 'Select...' }), _jsx(ChevronDown, { className: "w-3 h-3" })] }), isOpen && (_jsxs(_Fragment, { children: [_jsx("div", { className: "fixed inset-0 z-40", onClick: () => setIsOpen(false), role: "presentation" }), _jsx("div", { className: "absolute right-0 top-full mt-1 z-50 min-w-[160px] max-h-[200px] overflow-y-auto bg-popover border border-border rounded-md shadow-lg", children: options.map((option) => (_jsx("button", { type: "button", onClick: () => {
                                        onChange(option.id);
                                        setIsOpen(false);
                                    }, className: `w-full px-3 py-2 text-left text-xs font-mono hover:bg-muted truncate ${option.id === value ? 'bg-muted/50' : ''}`, children: option.label }, option.id))) })] }))] })] }));
});
export const SettingsSidebar = memo(function SettingsSidebar() {
    const isExpanded = useSettingsStore((state) => state.isExpanded);
    const collapseSidebar = useSettingsStore((state) => state.collapseSidebar);
    const { data: config } = useConfig();
    const { data: allModels } = useAllModels();
    const { preferences, updatePreferences } = usePreferences();
    const updateDefaults = useUpdateDefaults();
    const setuBalance = useSetuStore((s) => s.balance);
    const setuWallet = useSetuStore((s) => s.walletAddress);
    const setuUsdcBalance = useSetuStore((s) => s.usdcBalance);
    const setuLoading = useSetuStore((s) => s.isLoading);
    const openTopupModal = useSetuStore((s) => s.openTopupModal);
    // Handle topup success callback from Polar checkout redirect
    useTopupCallback();
    const hasSetu = config?.providers?.includes('setu');
    const { fetchBalance: refreshSetuBalance } = useSetuBalance(hasSetu ? 'setu' : undefined);
    const setOnboardingOpen = useOnboardingStore((s) => s.setOpen);
    const setStep = useOnboardingStore((s) => s.setStep);
    const setManageMode = useOnboardingStore((s) => s.setManageMode);
    const { fetchAuthStatus } = useAuthStatus();
    const providerOptions = useMemo(() => {
        if (!config?.providers || !allModels)
            return [];
        return config.providers
            .filter((p) => allModels[p])
            .map((p) => ({
            id: p,
            label: allModels[p]?.label || p,
        }));
    }, [config?.providers, allModels]);
    const modelOptions = useMemo(() => {
        const provider = config?.defaults?.provider;
        if (!provider || !allModels?.[provider])
            return [];
        return allModels[provider].models.map((m) => ({
            id: m.id,
            label: m.label,
        }));
    }, [config?.defaults?.provider, allModels]);
    const agentOptions = useMemo(() => {
        if (!config?.agents)
            return [];
        return config.agents.map((a) => ({ id: a, label: a }));
    }, [config?.agents]);
    if (!isExpanded)
        return null;
    const handleProviderChange = (provider) => {
        const firstModel = allModels?.[provider]?.models?.[0]?.id;
        updateDefaults.mutate({
            provider,
            model: firstModel || config?.defaults?.model,
        });
    };
    const handleModelChange = (model) => {
        updateDefaults.mutate({ model });
    };
    const handleAgentChange = (agent) => {
        updateDefaults.mutate({ agent });
    };
    const truncateWallet = (address) => {
        if (!address)
            return 'Not configured';
        return `${address.slice(0, 4)}...${address.slice(-4)}`;
    };
    const formatBalance = (balance) => {
        if (balance === null)
            return '—';
        return `$${balance.toFixed(4)}`;
    };
    const formatUsdcBalance = (balance) => {
        if (balance === null)
            return '—';
        return `${balance.toFixed(2)} USDC`;
    };
    return (_jsxs("div", { className: "w-80 border-l border-border bg-background flex flex-col h-full", children: [_jsxs("div", { className: "h-14 border-b border-border px-4 flex items-center justify-between shrink-0", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Settings, { className: "w-4 h-4" }), _jsx("span", { className: "font-medium", children: "Settings" })] }), _jsx(Button, { variant: "ghost", size: "icon", onClick: collapseSidebar, children: _jsx(ChevronRight, { className: "w-4 h-4" }) })] }), _jsxs("div", { className: "flex-1 overflow-y-auto", children: [_jsxs(SettingsSection, { title: "Default Model", icon: _jsx(Cpu, { className: "w-4 h-4 text-muted-foreground" }), children: [_jsx(SelectRow, { label: "Provider", value: config?.defaults?.provider ?? '', options: providerOptions, onChange: handleProviderChange, disabled: updateDefaults.isPending }), _jsx(SelectRow, { label: "Model", value: config?.defaults?.model ?? '', options: modelOptions, onChange: handleModelChange, disabled: updateDefaults.isPending }), _jsx(SelectRow, { label: "Agent", value: config?.defaults?.agent ?? '', options: agentOptions, onChange: handleAgentChange, disabled: updateDefaults.isPending })] }), _jsxs(SettingsSection, { title: "Preferences", icon: _jsx(User, { className: "w-4 h-4 text-muted-foreground" }), children: [_jsx(ToggleRow, { label: "Vim Mode", checked: preferences.vimMode, onChange: (checked) => updatePreferences({ vimMode: checked }) }), _jsx(ToggleRow, { label: "Show Reasoning", checked: preferences.reasoningEnabled, onChange: (checked) => updatePreferences({ reasoningEnabled: checked }) }), _jsx(SelectRow, { label: "Tool Approval", value: config?.defaults?.toolApproval ?? 'auto', options: [
                                    { id: 'auto', label: 'Auto (no approval)' },
                                    { id: 'dangerous', label: 'Dangerous only' },
                                    { id: 'all', label: 'All tools' },
                                ], onChange: (value) => updateDefaults.mutate({
                                    toolApproval: value,
                                }), disabled: updateDefaults.isPending })] }), config?.providers?.includes('setu') && (_jsxs(SettingsSection, { title: "Setu Wallet", icon: _jsx(Wallet, { className: "w-4 h-4 text-muted-foreground" }), action: _jsx("button", { type: "button", onClick: refreshSetuBalance, disabled: setuLoading, className: "p-1 hover:bg-muted rounded transition-colors disabled:opacity-50", title: "Refresh balances", children: _jsx(RefreshCw, { className: `w-3.5 h-3.5 text-muted-foreground ${setuLoading ? 'animate-spin' : ''}` }) }), children: [setuWallet && (_jsx("div", { className: "flex justify-center pb-3", children: _jsx("div", { className: "p-2 bg-white rounded-lg", children: _jsx(QRCodeSVG, { value: setuWallet, size: 120, level: "M", includeMargin: false }) }) })), _jsx(SettingRow, { label: "Address", value: truncateWallet(setuWallet) }), _jsx(SettingRow, { label: "Balance", value: formatBalance(setuBalance) }), _jsx(SettingRow, { label: "USDC", value: formatUsdcBalance(setuUsdcBalance) }), _jsxs(Button, { variant: "secondary", size: "sm", onClick: openTopupModal, className: "w-full mt-2 gap-2", children: [_jsx(Plus, { className: "w-4 h-4" }), "Top Up Balance"] })] })), _jsx(SetuTopupModal, {}), _jsx(SettingsSection, { title: "Providers", icon: _jsx(Zap, { className: "w-4 h-4 text-muted-foreground" }), action: _jsx("button", { type: "button", onClick: () => {
                                fetchAuthStatus().then(() => {
                                    setStep('wallet');
                                    setManageMode(true);
                                    setOnboardingOpen(true);
                                });
                            }, className: "p-1 hover:bg-muted rounded transition-colors", title: "Manage providers", children: _jsx(Pencil, { className: "w-3.5 h-3.5 text-muted-foreground" }) }), children: _jsx("div", { className: "flex flex-wrap gap-2", children: config?.providers?.map((provider) => (_jsx("span", { className: "px-2 py-1 text-xs bg-muted rounded-md font-mono", children: provider }, provider))) ?? _jsx("span", { className: "text-muted-foreground text-sm", children: "None" }) }) })] })] }));
});
//# sourceMappingURL=SettingsSidebar.js.map