import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Text, useInput } from 'ink';
import { useRef, useState } from 'react';
import TextInput from '../components/text-input.js';
import { useTerminalWidth } from '../hooks/useTerminalWidth.js';
import { useTheme } from '../hooks/useTheme.js';
import { ensureString } from '../utils/type-helpers.js';
const FREEFORM_VALUE = '__freeform__';
export default function QuestionPrompt({ question, onAnswer, }) {
    const { colors } = useTheme();
    const boxWidth = useTerminalWidth();
    const answeredRef = useRef(false);
    const [isFreeformMode, setIsFreeformMode] = useState(false);
    const [freeformValue, setFreeformValue] = useState('');
    const [selectedIndex, setSelectedIndex] = useState(0);
    // Build option items. The model controls `options`, so it may not be an
    // array of strings — coerce so a malformed call can't crash.
    const safeOptions = Array.isArray(question.options) ? question.options : [];
    const items = safeOptions.map(opt => {
        const label = ensureString(opt);
        return { label, value: label };
    });
    if (question.allowFreeform) {
        items.push({ label: 'Type a custom answer…', value: FREEFORM_VALUE });
    }
    // Reset internal state whenever a new question arrives. When two ask_user
    // calls fire back-to-back, React batches the null->new state transition so
    // this component re-renders with new props instead of unmounting, leaving
    // stale state (answeredRef silently blocks submission; selection/freeform
    // carry over).
    const [previousQuestion, setPreviousQuestion] = useState(question);
    if (question !== previousQuestion) {
        setPreviousQuestion(question);
        answeredRef.current = false;
        setIsFreeformMode(false);
        setFreeformValue('');
        setSelectedIndex(0);
    }
    const submitAnswer = (answer) => {
        if (answeredRef.current)
            return;
        answeredRef.current = true;
        onAnswer(answer);
    };
    const handleSelect = (item) => {
        if (!item)
            return;
        if (item.value === FREEFORM_VALUE) {
            setIsFreeformMode(true);
            return;
        }
        submitAnswer(item.value);
    };
    const handleFreeformSubmit = (value) => {
        if (value.trim()) {
            submitAnswer(value.trim());
        }
    };
    useInput((input, key) => {
        // In freeform mode the TextInput owns typing; only handle Escape (back).
        if (isFreeformMode) {
            if (key.escape) {
                setIsFreeformMode(false);
                setFreeformValue('');
            }
            return;
        }
        if (key.escape) {
            submitAnswer('User declined to answer');
            return;
        }
        if (items.length === 0)
            return;
        if (key.upArrow || input === 'k') {
            setSelectedIndex(i => (i - 1 + items.length) % items.length);
        }
        else if (key.downArrow || input === 'j') {
            setSelectedIndex(i => (i + 1) % items.length);
        }
        else if (key.return) {
            handleSelect(items[selectedIndex]);
        }
    });
    return (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Box, { flexDirection: "row", marginBottom: 1, backgroundColor: colors.base, width: boxWidth, padding: 1, borderStyle: "bold", borderLeft: true, borderRight: false, borderTop: false, borderBottom: false, borderLeftColor: colors.secondary, children: _jsx(Text, { color: colors.text, children: ensureString(question.question) }) }), isFreeformMode ? (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsx(Text, { color: colors.secondary, children: '> ' }), _jsx(TextInput, { value: freeformValue, onChange: setFreeformValue, onSubmit: handleFreeformSubmit })] }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: colors.secondary, children: "Press Enter to submit, Escape to go back" }) })] })) : (_jsxs(Box, { flexDirection: "column", children: [items.map((item, index) => {
                        const isSelected = index === selectedIndex;
                        const isFreeform = item.value === FREEFORM_VALUE;
                        const color = isSelected
                            ? colors.primary
                            : isFreeform
                                ? colors.secondary
                                : colors.text;
                        return (_jsxs(Box, { flexDirection: "row", width: boxWidth, marginBottom: 1, children: [_jsx(Box, { flexShrink: 0, marginRight: 1, children: _jsx(Text, { color: colors.primary, bold: true, children: isSelected ? '❯' : ' ' }) }), _jsx(Box, { flexGrow: 1, flexShrink: 1, children: _jsx(Text, { wrap: "wrap", color: color, bold: isSelected, children: item.label }) })] }, item.value));
                    }), _jsx(Text, { color: colors.secondary, children: "\u2191/\u2193 to move \u00B7 Enter to select \u00B7 Esc to cancel" })] }))] }));
}
//# sourceMappingURL=question-prompt.js.map