import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import React, { useState, useMemo } from 'react';
import { Box, Text } from 'ink';
import { SemanticColors } from '../colors.js';
import { useResponsive } from '../hooks/useResponsive.js';
import { truncateEnd } from '../utils/responsive.js';
import { useKeypress } from '../hooks/useKeypress.js';
export const ProviderDialog = ({ providers, currentProvider, onSelect, onClose, }) => {
    const { isNarrow, isWide, width } = useResponsive();
    const [searchTerm, setSearchTerm] = useState('');
    const [isSearching, setIsSearching] = useState(isNarrow);
    // Filter providers based on search term
    const filteredProviders = useMemo(() => providers.filter((p) => p.toLowerCase().includes(searchTerm.toLowerCase())), [providers, searchTerm]);
    const [index, setIndex] = useState(() => {
        const currentIndex = providers.findIndex((p) => p === currentProvider);
        return Math.max(0, currentIndex);
    });
    // Reset index when search term changes
    React.useEffect(() => {
        if (searchTerm.length === 0) {
            const currentIndex = providers.findIndex((p) => p === currentProvider);
            setIndex(Math.max(0, currentIndex));
        }
        else {
            setIndex(0);
        }
    }, [searchTerm, providers, currentProvider]);
    // Responsive layout calculations
    const columns = isNarrow ? 1 : 3;
    const longest = filteredProviders.reduce((len, p) => Math.max(len, p.length), 0);
    const colWidth = isWide
        ? Math.max(longest + 4, 30)
        : Math.max(longest + 4, 20);
    const rows = Math.ceil(filteredProviders.length / columns);
    const move = (delta) => {
        let next = index + delta;
        if (next < 0)
            next = 0;
        if (next >= filteredProviders.length)
            next = filteredProviders.length - 1;
        setIndex(next);
    };
    useKeypress((key) => {
        if (key.name === 'escape') {
            if (isSearching && searchTerm.length > 0) {
                setSearchTerm('');
            }
            else {
                return onClose();
            }
        }
        if (isSearching || isNarrow) {
            if (key.name === 'return') {
                if (filteredProviders.length > 0) {
                    if (isNarrow) {
                        return onSelect(filteredProviders[index]);
                    }
                    setIsSearching(false);
                }
            }
            else if (key.name === 'tab' && !isNarrow) {
                setIsSearching(false);
            }
            else if (key.name === 'backspace' || key.name === 'delete') {
                setSearchTerm((prev) => prev.slice(0, -1));
            }
            else if (key.sequence &&
                typeof key.sequence === 'string' &&
                !key.ctrl &&
                !key.meta &&
                key.insertable) {
                setSearchTerm((prev) => prev + key.sequence);
            }
        }
        else {
            if (key.name === 'return' && filteredProviders.length > 0) {
                return onSelect(filteredProviders[index]);
            }
            if (key.name === 'tab') {
                setIsSearching(true);
            }
            if (filteredProviders.length === 0) {
                return;
            }
            if (key.name === 'left')
                move(-1);
            if (key.name === 'right')
                move(1);
            if (key.name === 'up')
                move(-columns);
            if (key.name === 'down')
                move(columns);
        }
    }, { isActive: true });
    const renderItem = (name, i) => {
        const selected = i === index && (!isSearching || isNarrow);
        // In wide mode, don't truncate. In standard/narrow, truncate reasonably
        const displayName = isWide
            ? name
            : name.length > 20
                ? truncateEnd(name, 20)
                : name;
        return (_jsx(Box, { width: isWide ? undefined : colWidth, marginRight: 2, children: _jsxs(Text, { color: selected
                    ? SemanticColors.text.accent
                    : isSearching && !isNarrow
                        ? SemanticColors.text.secondary
                        : SemanticColors.text.primary, children: [selected ? '● ' : '○ ', displayName] }) }, name));
    };
    const grid = [];
    for (let r = 0; r < rows; r++) {
        const rowItems = [];
        for (let c = 0; c < columns; c++) {
            const i = r * columns + c;
            if (i < filteredProviders.length)
                rowItems.push(renderItem(filteredProviders[i], i));
        }
        grid.push(_jsx(Box, { children: rowItems }, r));
    }
    const renderContent = () => {
        if (isNarrow) {
            return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: "Select Provider" }), _jsxs(Box, { marginY: 1, children: [_jsxs(Text, { color: SemanticColors.text.primary, children: ["Search: ", _jsx(Text, { color: SemanticColors.text.accent, children: "\u258C" })] }), _jsx(Text, { color: SemanticColors.text.primary, children: searchTerm })] }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Type to filter, Enter to select, Esc to cancel" }), _jsxs(Text, { color: SemanticColors.text.secondary, children: [filteredProviders.length, " providers", searchTerm && ` found`] }), filteredProviders.length > 0 ? (grid) : (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["No providers match \"", searchTerm, "\""] }) }))] }));
        }
        return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: isSearching
                        ? 'Search Providers'
                        : 'Select Provider (←/→/↑/↓, Enter to choose, Esc to cancel)' }), !isNarrow && (_jsxs(Box, { marginY: 1, children: [_jsxs(Text, { color: isSearching
                                ? SemanticColors.text.primary
                                : SemanticColors.text.secondary, children: ["Search:", ' ', isSearching && _jsx(Text, { color: SemanticColors.text.accent, children: "\u258C" })] }), _jsx(Text, { color: SemanticColors.text.primary, children: searchTerm }), searchTerm && (_jsxs(Text, { color: SemanticColors.text.secondary, children: [' ', "(Found ", filteredProviders.length, " of ", providers.length, ' ', "providers)"] }))] })), filteredProviders.length > 0 ? (grid) : (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["No providers match \"", searchTerm, "\""] }) })), filteredProviders.length > 0 && !isSearching && (_jsxs(Text, { color: SemanticColors.text.secondary, children: ["Selected: ", filteredProviders[index]] })), !isNarrow && (_jsx(Text, { color: SemanticColors.text.secondary, children: "Tab to switch modes" }))] }));
    };
    return isNarrow ? (_jsx(Box, { flexDirection: "column", padding: 1, children: renderContent() })) : (_jsx(Box, { borderStyle: "round", borderColor: SemanticColors.border.default, flexDirection: "column", padding: 1, width: Math.min(width, 100), children: renderContent() }));
};
//# sourceMappingURL=ProviderDialog.js.map