import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Text } from "ink";
import { HOOK_EVENTS } from "../hooks/events.js";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
import { Pane } from "./design/Pane.js";
import { SelectList } from "./design/SelectList.js";
import { StatusBadge } from "./design/StatusBadge.js";
import { Tabs } from "./design/Tabs.js";
import { truncateCells } from "./design/textLayout.js";
const HOOK_EVENT_DESCRIPTIONS = {
    PreToolUse: "runs before a matching tool is executed and may block the operation",
    PostToolUse: "runs after a matching tool completes successfully",
    PostToolUseFailure: "runs after a matching tool fails",
    UserPromptSubmit: "runs after a user prompt is submitted",
    SessionStart: "runs when a DeepSeekCode session starts",
    Stop: "runs when the session exits normally",
    StopFailure: "runs when the session exits with an error",
    PreCompact: "runs before context compaction",
    PostCompact: "runs after context compaction",
    TaskCreated: "runs when a task is created",
    TaskCompleted: "runs when a task completes",
    Setup: "runs during local workspace setup",
    config: "validates the hooks configuration file",
};
export function HookPanel(props) {
    const { columns } = useTerminalSize();
    const width = Math.max(58, Math.min(112, columns - 4));
    const tabs = hookPanelTabs(props.model);
    const eventOptions = hookPanelEventOptions(props.model);
    const selectedEvent = hookPanelSelectedEvent(props.model);
    const selectedEventIndex = Math.max(0, eventOptions.findIndex((option) => option.selected));
    const hookOptions = hookPanelHookOptions(props.model, selectedEvent);
    const selectedHook = props.model.rows.find((row) => row.event === selectedEvent) ?? props.model.rows[0];
    return (_jsx(Box, { flexDirection: "column", marginBottom: 1, children: _jsxs(Pane, { width: width, title: "hooks", tone: props.model.rows.length > 0 ? "brand" : "muted", paddingX: 1, children: [_jsxs(Box, { flexDirection: "row", justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: "cyan", children: props.model.title }), _jsx(Text, { color: "gray", children: truncateCells(props.model.subtitle, Math.max(24, width - 20)) })] }), _jsxs(Box, { flexDirection: "column", alignItems: "flex-end", children: [_jsx(StatusBadge, { label: `${props.model.rows.length} hooks`, tone: props.model.rows.length > 0 ? "brand" : "muted" }), _jsx(Text, { color: "gray", children: hookPanelStatusLine(props.model) })] })] }), _jsx(Box, { marginTop: 1, children: _jsx(Tabs, { selectedId: "events", title: "view", tabs: tabs, width: width }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "gray", children: "events" }) }), _jsx(SelectList, { options: eventOptions, selectedIndex: selectedEventIndex, visibleCount: Math.min(7, eventOptions.length), width: width }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "gray", children: selectedEvent ? `hooks for ${selectedEvent}` : "hooks" }) }), hookOptions.length > 0 ? (_jsx(SelectList, { options: hookOptions, selectedIndex: 0, visibleCount: 5, width: width })) : (_jsx(Text, { color: "gray", children: selectedEvent ? `No hooks bound to ${selectedEvent}` : "No hooks configured" })), _jsx(HookDetailCard, { row: selectedHook, width: width }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "gray", children: "commands" }) }), _jsx(SelectList, { options: hookPanelCommandOptions(), selectedIndex: 0, visibleCount: 4, width: width }), _jsx(Text, { color: "gray", children: truncateCells(props.model.footer, Math.max(24, width - 4)) })] }) }));
}
export function hookListPanelModel(hooks) {
    return {
        title: "Hooks",
        subtitle: `${hooks.length} configured hook${hooks.length === 1 ? "" : "s"}`,
        selectedEvent: hooks[0]?.event,
        rows: hooks.map((hook) => ({
            key: hook.id,
            id: hook.id,
            status: hook.enabled ? "enabled" : "disabled",
            tone: hook.enabled ? "success" : "muted",
            event: hook.event,
            matcher: hook.matcher || "(all)",
            command: hook.command,
            note: hook.description || `timeout=${hook.timeout_ms}ms`,
        })),
        footer: `events: ${HOOK_EVENTS.join(", ")}`,
    };
}
export function hookValidationPanelModel(result) {
    const rows = [];
    rows.push({
        key: "validation",
        id: result.path,
        status: result.ok ? "ok" : "failed",
        tone: result.ok ? "success" : "error",
        event: "config",
        matcher: "-",
        command: result.ok ? "hooks.json parsed" : result.errors.join("; "),
        note: result.warnings.length > 0 ? `warning: ${result.warnings.join("; ")}` : "",
    });
    return {
        title: "Hook validation",
        subtitle: result.path,
        selectedEvent: "config",
        rows,
        footer: "/hooks add <id> <event> <matcher|-> <command...> | /hooks remove <id>",
    };
}
export function hookPanelTabs(model) {
    const summaries = hookPanelEventSummaries(model);
    return [
        { id: "events", title: "events", count: summaries.length, tone: "brand" },
        { id: "hooks", title: "hooks", count: model.rows.length, tone: model.rows.length > 0 ? "brand" : "muted" },
        { id: "commands", title: "commands", count: hookPanelCommandOptions().length, tone: "muted" },
    ];
}
export function hookPanelEventSummaries(model) {
    const byEvent = new Map();
    for (const event of HOOK_EVENTS) {
        byEvent.set(event, { hooks: 0, enabled: 0, disabled: 0, matchers: new Set() });
    }
    for (const row of model.rows) {
        const summary = byEvent.get(row.event) ?? { hooks: 0, enabled: 0, disabled: 0, matchers: new Set() };
        summary.hooks += 1;
        if (row.status === "enabled" || row.status === "ok") {
            summary.enabled += 1;
        }
        else {
            summary.disabled += 1;
        }
        summary.matchers.add(row.matcher || "(all)");
        byEvent.set(row.event, summary);
    }
    return [...byEvent.entries()].map(([event, summary]) => ({
        event,
        hooks: summary.hooks,
        enabled: summary.enabled,
        disabled: summary.disabled,
        matchers: summary.matchers.size,
        tone: eventSummaryTone(summary.hooks, summary.disabled),
    }));
}
export function hookPanelEventOptions(model) {
    const selectedEvent = hookPanelSelectedEvent(model);
    return hookPanelEventSummaries(model).map((summary) => ({
        id: summary.event,
        label: summary.event,
        detail: `${summary.hooks} hooks | ${summary.matchers} matchers`,
        description: hookEventDescription(summary),
        selected: summary.event === selectedEvent,
        tone: summary.tone,
    }));
}
export function hookPanelHookOptions(model, event = hookPanelSelectedEvent(model)) {
    return model.rows
        .filter((row) => !event || row.event === event)
        .map((row) => ({
        id: row.id,
        label: row.id,
        detail: `${row.status} | ${row.matcher}`,
        description: `${row.command}${row.note ? ` -- ${row.note}` : ""}`,
        selected: row.event === event,
        disabled: row.status === "disabled",
        tone: row.tone,
    }));
}
export function hookPanelCommandOptions() {
    return [
        {
            id: "validate",
            label: "validate",
            detail: "/hooks validate",
            description: "parse hooks.json and show errors or policy warnings",
            tone: "brand",
        },
        {
            id: "add",
            label: "add",
            detail: "/hooks add <id> <event> <matcher|-> <command...>",
            description: "register a command hook in the local project config",
            tone: "success",
        },
        {
            id: "run",
            label: "run",
            detail: "/hooks run <event> [payload-json]",
            description: "execute matching hooks with a small test payload",
            tone: "warning",
        },
        {
            id: "remove",
            label: "remove",
            detail: "/hooks remove <id>",
            description: "remove a configured hook by id",
            tone: "muted",
        },
    ];
}
function hookPanelSelectedEvent(model) {
    if (model.selectedEvent)
        return model.selectedEvent;
    return model.rows[0]?.event ?? HOOK_EVENTS[0];
}
function hookPanelStatusLine(model) {
    const enabled = model.rows.filter((row) => row.status === "enabled" || row.status === "ok").length;
    const disabled = Math.max(0, model.rows.length - enabled);
    return `enabled ${enabled} | inactive ${disabled}`;
}
function HookDetailCard(props) {
    if (!props.row)
        return null;
    const commandWidth = Math.max(18, props.width - 18);
    const noteWidth = Math.max(18, props.width - 18);
    return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Box, { flexDirection: "row", children: [_jsx(StatusBadge, { label: props.row.status, tone: props.row.tone }), _jsx(Text, { children: " " }), _jsx(Text, { color: "cyan", children: truncateCells(props.row.id, 24) }), _jsxs(Text, { color: "gray", children: [" ", truncateCells(`${props.row.event} / ${props.row.matcher}`, Math.max(18, props.width - 34))] })] }), _jsx(Box, { paddingLeft: 2, children: _jsx(Text, { color: "gray", children: truncateCells(props.row.command, commandWidth) }) }), props.row.note ? (_jsx(Box, { paddingLeft: 2, children: _jsx(Text, { color: "gray", children: truncateCells(props.row.note, noteWidth) }) })) : null] }));
}
function hookEventDescription(summary) {
    const base = HOOK_EVENT_DESCRIPTIONS[summary.event] ?? "custom hook event";
    if (summary.hooks === 0)
        return base;
    return `${base}; enabled ${summary.enabled}, inactive ${summary.disabled}`;
}
function eventSummaryTone(hooks, inactive) {
    if (hooks === 0)
        return "muted";
    if (inactive > 0)
        return "warning";
    return "brand";
}
