/**
 * Enhanced Help System
 *
 * Interactive help with examples-first approach,
 * contextual tips, and keyboard shortcuts reference.
 */
import React, { useState, useCallback, useMemo } from "react";
import { Box, Text, useInput } from "ink";
/**
 * Format key combination for display
 */
function formatKeys(keys) {
    return keys.map((key, index) => (React.createElement(React.Fragment, { key: key },
        index > 0 && React.createElement(Text, { dimColor: true }, "+"),
        React.createElement(Text, { backgroundColor: "gray", color: "white" },
            " ",
            key,
            " "))));
}
/**
 * Help System Component
 */
export function HelpSystem({ config, initialTopic, onClose, }) {
    const [view, setView] = useState(initialTopic ? "command" : "main");
    const [selectedCategory, setSelectedCategory] = useState(0);
    const [selectedCommand, setSelectedCommand] = useState(0);
    const [searchQuery, setSearchQuery] = useState("");
    const [searchMode, setSearchMode] = useState(false);
    const [tipIndex, setTipIndex] = useState(0);
    // Find command by name (used for search)
    const _findCommand = useCallback((name) => {
        for (const category of config.categories) {
            const command = category.commands.find((c) => c.command.toLowerCase() === name.toLowerCase() ||
                c.aliases?.some((a) => a.toLowerCase() === name.toLowerCase()));
            if (command) {
                return { category, command };
            }
        }
        return null;
    }, [config.categories]);
    // Search results
    const searchResults = useMemo(() => {
        if (!searchQuery)
            return [];
        const query = searchQuery.toLowerCase();
        const results = [];
        for (const category of config.categories) {
            for (const command of category.commands) {
                let score = 0;
                if (command.command.toLowerCase().includes(query)) {
                    score += command.command.toLowerCase().startsWith(query) ? 100 : 50;
                }
                if (command.description.toLowerCase().includes(query)) {
                    score += 30;
                }
                if (command.aliases?.some((a) => a.toLowerCase().includes(query))) {
                    score += 40;
                }
                if (score > 0) {
                    results.push({ category: category.name, command, score });
                }
            }
        }
        return results.sort((a, b) => b.score - a.score).slice(0, 10);
    }, [searchQuery, config.categories]);
    // Current category and commands
    const currentCategory = config.categories[selectedCategory];
    const currentCommand = currentCategory?.commands[selectedCommand];
    // Handle input
    useInput(useCallback((input, key) => {
        // Search mode input
        if (searchMode) {
            if (key.escape) {
                setSearchMode(false);
                setSearchQuery("");
                return;
            }
            if (key.return && searchResults.length > 0) {
                const result = searchResults[0];
                const catIndex = config.categories.findIndex((c) => c.name === result.category);
                if (catIndex !== -1) {
                    setSelectedCategory(catIndex);
                    const cmdIndex = config.categories[catIndex].commands.findIndex((c) => c.command === result.command.command);
                    if (cmdIndex !== -1) {
                        setSelectedCommand(cmdIndex);
                        setView("command");
                    }
                }
                setSearchMode(false);
                setSearchQuery("");
                return;
            }
            if (key.backspace || key.delete) {
                setSearchQuery((prev) => prev.slice(0, -1));
                return;
            }
            if (input && !key.ctrl && !key.meta) {
                setSearchQuery((prev) => prev + input);
            }
            return;
        }
        // Exit
        if (key.escape || input === "q" || input === "Q") {
            if (view === "main") {
                onClose?.();
            }
            else {
                setView("main");
                setSelectedCommand(0);
            }
            return;
        }
        // Search
        if (input === "/" || input === "s" || input === "S") {
            setSearchMode(true);
            return;
        }
        // Shortcuts view
        if (input === "k" || input === "K") {
            setView(view === "shortcuts" ? "main" : "shortcuts");
            return;
        }
        // Navigation
        if (view === "main") {
            if (key.upArrow) {
                setSelectedCategory((prev) => prev > 0 ? prev - 1 : config.categories.length - 1);
            }
            else if (key.downArrow) {
                setSelectedCategory((prev) => prev < config.categories.length - 1 ? prev + 1 : 0);
            }
            else if (key.return || key.rightArrow) {
                setView("category");
                setSelectedCommand(0);
            }
        }
        else if (view === "category") {
            const commands = currentCategory?.commands || [];
            if (key.upArrow) {
                setSelectedCommand((prev) => prev > 0 ? prev - 1 : commands.length - 1);
            }
            else if (key.downArrow) {
                setSelectedCommand((prev) => prev < commands.length - 1 ? prev + 1 : 0);
            }
            else if (key.return || key.rightArrow) {
                setView("command");
            }
            else if (key.leftArrow) {
                setView("main");
            }
        }
        else if (view === "command") {
            if (key.leftArrow) {
                setView("category");
            }
        }
        // Cycle tips
        if (input === "t" || input === "T") {
            setTipIndex((prev) => (prev + 1) % config.tips.length);
        }
    }, [
        view,
        searchMode,
        searchResults,
        config.categories,
        config.tips.length,
        currentCategory,
        onClose,
    ]));
    // Render main view
    const renderMain = () => (React.createElement(Box, { flexDirection: "column" },
        React.createElement(Box, { marginBottom: 1 },
            React.createElement(Text, { bold: true, color: "cyan" }, config.appName),
            React.createElement(Text, { dimColor: true },
                " v",
                config.version)),
        React.createElement(Text, { dimColor: true }, config.description),
        React.createElement(Box, { marginTop: 1, flexDirection: "column" },
            React.createElement(Text, { bold: true, color: "yellow" }, "QUICK START"),
            React.createElement(Box, { marginLeft: 2, flexDirection: "column" },
                React.createElement(Text, null,
                    React.createElement(Text, { color: "cyan" }, "$"),
                    " codebuddy \"add error handling to server.ts\""),
                React.createElement(Text, null,
                    React.createElement(Text, { color: "cyan" }, "$"),
                    " codebuddy \"find all TODO comments\""),
                React.createElement(Text, null,
                    React.createElement(Text, { color: "cyan" }, "$"),
                    " codebuddy \"refactor UserService to async/await\""))),
        React.createElement(Box, { marginTop: 1, flexDirection: "column" },
            React.createElement(Text, { bold: true, color: "yellow" }, "COMMAND CATEGORIES"),
            config.categories.map((category, index) => (React.createElement(Box, { key: category.name, paddingLeft: 2 },
                React.createElement(Text, { color: selectedCategory === index ? "cyan" : undefined, bold: selectedCategory === index },
                    selectedCategory === index ? "❯ " : "  ",
                    category.name),
                React.createElement(Text, { dimColor: true },
                    " - ",
                    category.description))))),
        config.tips.length > 0 && (React.createElement(Box, { marginTop: 1, borderStyle: "round", borderColor: "magenta", padding: 1 },
            React.createElement(Text, { color: "magenta" }, "\uD83D\uDCA1 Tip: "),
            React.createElement(Text, null, config.tips[tipIndex]),
            React.createElement(Text, { dimColor: true }, " (press 't' for next tip)"))),
        React.createElement(Box, { marginTop: 1, flexDirection: "column" },
            config.docUrl && (React.createElement(Text, { dimColor: true },
                "\uD83D\uDCDA Documentation: ",
                React.createElement(Text, { color: "cyan" }, config.docUrl))),
            config.issuesUrl && (React.createElement(Text, { dimColor: true },
                "\uD83D\uDC1B Report issues: ",
                React.createElement(Text, { color: "cyan" }, config.issuesUrl))))));
    // Render category view
    const renderCategory = () => (React.createElement(Box, { flexDirection: "column" },
        React.createElement(Box, { marginBottom: 1 },
            React.createElement(Text, { color: "cyan" }, "\u2190 "),
            React.createElement(Text, { bold: true }, currentCategory?.name)),
        React.createElement(Text, { dimColor: true }, currentCategory?.description),
        React.createElement(Box, { marginTop: 1, flexDirection: "column" }, currentCategory?.commands.map((command, index) => (React.createElement(Box, { key: command.command, paddingLeft: 2 },
            React.createElement(Text, { color: selectedCommand === index ? "cyan" : undefined, bold: selectedCommand === index },
                selectedCommand === index ? "❯ " : "  ",
                command.command),
            React.createElement(Text, { dimColor: true },
                " - ",
                command.description)))))));
    // Render command detail view
    const renderCommand = () => {
        if (!currentCommand)
            return null;
        return (React.createElement(Box, { flexDirection: "column" },
            React.createElement(Box, { marginBottom: 1 },
                React.createElement(Text, { color: "cyan" }, "\u2190 "),
                React.createElement(Text, { bold: true, color: "green" }, currentCommand.command),
                currentCommand.aliases && currentCommand.aliases.length > 0 && (React.createElement(Text, { dimColor: true },
                    " ",
                    "(aliases: ",
                    currentCommand.aliases.join(", "),
                    ")"))),
            React.createElement(Text, null, currentCommand.description),
            currentCommand.args && currentCommand.args.length > 0 && (React.createElement(Box, { marginTop: 1, flexDirection: "column" },
                React.createElement(Text, { bold: true, color: "yellow" }, "ARGUMENTS"),
                currentCommand.args.map((arg) => (React.createElement(Box, { key: arg.name, paddingLeft: 2 },
                    React.createElement(Text, { color: arg.required ? "cyan" : "gray" },
                        arg.name,
                        arg.required && React.createElement(Text, { color: "red" }, "*")),
                    React.createElement(Text, { dimColor: true },
                        " - ",
                        arg.description)))))),
            currentCommand.examples && currentCommand.examples.length > 0 && (React.createElement(Box, { marginTop: 1, flexDirection: "column" },
                React.createElement(Text, { bold: true, color: "yellow" }, "EXAMPLES"),
                currentCommand.examples.map((example, index) => (React.createElement(Box, { key: index, paddingLeft: 2 },
                    React.createElement(Text, { color: "cyan" }, "$ "),
                    React.createElement(Text, null, example))))))));
    };
    // Render shortcuts view
    const renderShortcuts = () => (React.createElement(Box, { flexDirection: "column" },
        React.createElement(Box, { marginBottom: 1 },
            React.createElement(Text, { bold: true, color: "cyan" }, "KEYBOARD SHORTCUTS")),
        config.shortcuts.map((shortcut, index) => (React.createElement(Box, { key: index, paddingLeft: 2 },
            React.createElement(Box, { width: 20 }, formatKeys(shortcut.keys)),
            React.createElement(Text, null, shortcut.description),
            shortcut.context && React.createElement(Text, { dimColor: true },
                " (",
                shortcut.context,
                ")"))))));
    // Render search overlay
    const renderSearch = () => (React.createElement(Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", padding: 1 },
        React.createElement(Box, null,
            React.createElement(Text, { color: "cyan" }, "Search: "),
            React.createElement(Text, null, searchQuery),
            React.createElement(Text, { backgroundColor: "white", color: "black" }, " ")),
        searchResults.length > 0 && (React.createElement(Box, { marginTop: 1, flexDirection: "column" }, searchResults.slice(0, 5).map((result, index) => (React.createElement(Box, { key: result.command.command },
            React.createElement(Text, { color: index === 0 ? "cyan" : undefined }, index === 0 ? "❯ " : "  "),
            React.createElement(Text, { bold: true }, result.command.command),
            React.createElement(Text, { dimColor: true },
                " (",
                result.category,
                ")")))))),
        searchQuery && searchResults.length === 0 && (React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { dimColor: true }, "No results found")))));
    return (React.createElement(Box, { flexDirection: "column" },
        searchMode && renderSearch(),
        !searchMode && (React.createElement(React.Fragment, null,
            view === "main" && renderMain(),
            view === "category" && renderCategory(),
            view === "command" && renderCommand(),
            view === "shortcuts" && renderShortcuts(),
            React.createElement(Box, { marginTop: 1, borderStyle: "single", borderColor: "gray", paddingX: 1 },
                React.createElement(Text, { dimColor: true }, "\u2191\u2193 navigate \u2022 Enter/\u2192 select \u2022 \u2190/Esc back \u2022 / search \u2022 k shortcuts \u2022 q quit"))))));
}
/**
 * Default help configuration for Grok CLI
 */
export const DEFAULT_HELP_CONFIG = {
    appName: "CodeBuddy CLI",
    version: "1.0.0",
    description: "AI-powered terminal agent using CodeBuddy API",
    docUrl: "https://github.com/phuetz/code-buddy#readme",
    issuesUrl: "https://github.com/phuetz/code-buddy/issues",
    categories: [
        {
            name: "Chat",
            description: "Interactive conversation commands",
            commands: [
                {
                    command: "/help",
                    description: "Show this help",
                    aliases: ["/?", "/h"],
                    examples: ["/help", "/help model"],
                },
                {
                    command: "/clear",
                    description: "Clear conversation history",
                    aliases: ["/c"],
                },
                {
                    command: "/exit",
                    description: "Exit the application",
                    aliases: ["/quit", "/q"],
                },
            ],
        },
        {
            name: "Model",
            description: "AI model configuration",
            commands: [
                {
                    command: "/model",
                    description: "Show or change the current model",
                    args: [
                        { name: "name", description: "Model name to switch to", required: false },
                    ],
                    examples: ["/model", "/model grok-2", "/model grok-2-vision"],
                },
            ],
        },
        {
            name: "Theme",
            description: "Visual customization",
            commands: [
                {
                    command: "/theme",
                    description: "Show or change the theme",
                    args: [
                        { name: "name", description: "Theme name", required: false },
                    ],
                    examples: ["/theme", "/theme dark", "/theme catppuccin"],
                },
                {
                    command: "/avatar",
                    description: "Change avatar preset",
                    args: [
                        { name: "preset", description: "Avatar preset name", required: false },
                    ],
                    examples: ["/avatar", "/avatar minimal", "/avatar emoji"],
                },
            ],
        },
        {
            name: "Settings",
            description: "Configuration and preferences",
            commands: [
                {
                    command: "/config",
                    description: "Show or update configuration",
                    examples: ["/config", "/config set maxCost 5"],
                },
                {
                    command: "/api-key",
                    description: "Update API key",
                },
            ],
        },
    ],
    shortcuts: [
        { keys: ["Enter"], description: "Send message" },
        { keys: ["Shift", "Enter"], description: "New line in input" },
        { keys: ["↑", "↓"], description: "Navigate history" },
        { keys: ["Ctrl", "C"], description: "Cancel current operation" },
        { keys: ["Ctrl", "L"], description: "Clear screen" },
        { keys: ["Tab"], description: "Autocomplete command" },
        { keys: ["Shift", "Tab"], description: "Toggle auto-edit mode", context: "in chat" },
        { keys: ["Esc"], description: "Cancel/close dialog" },
    ],
    tips: [
        "Use 'think', 'megathink', or 'ultrathink' keywords for extended reasoning",
        "Press Shift+Tab to toggle auto-edit mode for automatic file changes",
        "You can use @file.ts to reference files in your messages",
        "Set YOLO_MODE=true for full autonomy (no confirmations)",
        "Use /model to switch between Grok models",
    ],
};
export default HelpSystem;
//# sourceMappingURL=HelpSystem.js.map