import { Container, Input, Spacer, Text, getEditorKeybindings, matchesKey, truncateToWidth } from '../../../tui/index.js';
import { theme } from '../../theme/runtime.js';
import { DynamicBorder } from '../primitives/dynamic-border.js';
import { cancelKeyHint, rawKeyHint } from '../primitives/keybinding-hints.js';
class PortSkillsSelectorHeader {
    invalidate() { }
    render(width) {
        return [
            truncateToWidth(theme.bold('External Skill Sources'), width, ''),
            truncateToWidth(theme.fg('muted', 'Toggle sources to control which Claude, Codex, or Agents roots are loaded. Use /skills for per-skill prompt visibility.'), width, '...')
        ];
    }
}
class PortSkillsList {
    searchInput;
    items;
    filteredItems;
    selectedIndex = 0;
    maxVisible = 10;
    _focused = false;
    onCancel;
    onExit;
    onToggle;
    onApply;
    get focused() {
        return this._focused;
    }
    set focused(value) {
        this._focused = value;
        this.searchInput.focused = value;
    }
    constructor(items) {
        this.items = [...items].sort((a, b) => {
            if (a.scope !== b.scope)
                return a.scope === 'project' ? -1 : 1;
            if (a.providerLabel !== b.providerLabel)
                return a.providerLabel.localeCompare(b.providerLabel);
            return a.settingsPath.localeCompare(b.settingsPath);
        });
        this.filteredItems = [...this.items];
        this.searchInput = new Input();
        this.selectFirstItem();
    }
    invalidate() { }
    render(width) {
        const lines = [...this.searchInput.render(width), ''];
        if (this.filteredItems.length === 0) {
            lines.push(theme.fg('muted', '  No external skill sources match your search.'));
            return lines;
        }
        const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), Math.max(0, this.filteredItems.length - this.maxVisible)));
        const endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);
        for (let i = startIndex; i < endIndex; i++) {
            const item = this.filteredItems[i];
            const isSelected = i === this.selectedIndex;
            const cursor = isSelected ? '> ' : '  ';
            const marker = item.active ? theme.fg('success', '[x]') : theme.fg('dim', '[ ]');
            const provider = theme.fg('muted', `[${item.providerLabel} ${item.scope}]`);
            const countLabel = (() => {
                const loaded = item.validSkillCount === 1 ? '1 loaded' : `${item.validSkillCount} loaded`;
                if (item.brokenSkillCount === 0) {
                    return loaded;
                }
                const warned = item.brokenSkillCount === 1
                    ? '1 with warnings'
                    : `${item.brokenSkillCount} with warnings`;
                return `${loaded}, ${warned}`;
            })();
            const count = item.validSkillCount > 0 ? theme.fg('dim', countLabel) : theme.fg('warning', countLabel);
            const warnings = item.warningCount > 0
                ? theme.fg('warning', ` ${item.warningCount} warning${item.warningCount === 1 ? '' : 's'}`)
                : '';
            const pathLabel = isSelected ? theme.bold(item.settingsPath) : item.settingsPath;
            lines.push(truncateToWidth(`${cursor}${marker} ${provider} ${pathLabel} ${count}${warnings}`, width, '...'));
        }
        if (startIndex > 0 || endIndex < this.filteredItems.length) {
            lines.push(theme.fg('dim', `  (${this.selectedIndex + 1}/${this.filteredItems.length})`));
        }
        return lines;
    }
    handleInput(data) {
        const kb = getEditorKeybindings();
        if (kb.matches(data, 'selectUp')) {
            this.selectedIndex = Math.max(0, this.selectedIndex - 1);
            return;
        }
        if (kb.matches(data, 'selectDown')) {
            this.selectedIndex = Math.min(this.filteredItems.length - 1, this.selectedIndex + 1);
            return;
        }
        if (kb.matches(data, 'selectPageUp')) {
            this.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisible);
            return;
        }
        if (kb.matches(data, 'selectPageDown')) {
            this.selectedIndex = Math.min(this.filteredItems.length - 1, this.selectedIndex + this.maxVisible);
            return;
        }
        if (kb.matches(data, 'selectCancel') || matchesKey(data, 'ctrl+c')) {
            this.onCancel?.();
            return;
        }
        if (matchesKey(data, 'space')) {
            const item = this.filteredItems[this.selectedIndex];
            if (!item)
                return;
            item.active = !item.active;
            const canonical = this.items.find((candidate) => candidate.id === item.id);
            if (canonical) {
                canonical.active = item.active;
            }
            this.onToggle?.();
            return;
        }
        if (kb.matches(data, 'selectConfirm')) {
            this.onApply?.(this.items.map((item) => ({ ...item })));
            return;
        }
        this.searchInput.handleInput(data);
        this.filterItems(this.searchInput.getValue());
    }
    filterItems(query) {
        const lowered = query.trim().toLowerCase();
        this.filteredItems = lowered
            ? this.items.filter((item) => item.providerLabel.toLowerCase().includes(lowered) ||
                item.scope.toLowerCase().includes(lowered) ||
                item.settingsPath.toLowerCase().includes(lowered))
            : [...this.items];
        this.selectFirstItem();
    }
    selectFirstItem() {
        this.selectedIndex = this.filteredItems.length > 0 ? 0 : -1;
    }
}
export class PortSkillsSelectorComponent extends Container {
    list;
    _focused = false;
    get focused() {
        return this._focused;
    }
    set focused(value) {
        this._focused = value;
        this.list.focused = value;
    }
    constructor(items, onClose, onExit, onApply, requestRender) {
        super();
        this.addChild(new Spacer(1));
        this.addChild(new DynamicBorder());
        this.addChild(new Spacer(1));
        this.addChild(new PortSkillsSelectorHeader());
        this.addChild(new Spacer(1));
        this.list = new PortSkillsList(items);
        this.list.onCancel = onClose;
        this.list.onExit = onExit;
        this.list.onToggle = () => requestRender();
        this.list.onApply = (draftItems) => {
            onApply(draftItems);
            requestRender();
        };
        this.addChild(this.list);
        this.addChild(new Spacer(1));
        this.addChild(new Text(rawKeyHint('↑↓', 'navigate') +
            '  ' +
            rawKeyHint('space', 'toggle') +
            '  ' +
            rawKeyHint('enter', 'apply') +
            '  ' +
            cancelKeyHint(), 1, 0));
        this.addChild(new Spacer(1));
        this.addChild(new DynamicBorder());
    }
    getList() {
        return this.list;
    }
}
//# sourceMappingURL=port-skills-selector.js.map