/**
 * Click composer questionnaire (Questions) — VS Code needs mousedown on options.
 * Supports legacy `.composer-questionnaire-toolbar` and Glass `.ui-tray`.
 */
export function questionnaireDomAction(action, opts) {
    function isQuestionnaireTray(el) {
        return (el.classList.contains('ui-tray') &&
            !!el.querySelector('.ui-tray-option') &&
            !!el.querySelector('.ui-tray-actions'));
    }
    function findRoot() {
        const scopes = [
            document.querySelector('[class*="composer-panel"]'),
            document.querySelector('.composer-bar')?.parentElement,
            document.querySelector('[class*="agent-panel"]'),
            document.body,
        ].filter((el) => Boolean(el));
        for (const scope of scopes) {
            const legacy = scope.querySelector('.composer-questionnaire-toolbar');
            if (legacy)
                return legacy;
            for (const tray of scope.querySelectorAll('.ui-tray')) {
                if (isQuestionnaireTray(tray))
                    return tray;
            }
        }
        return (document.querySelector('.composer-questionnaire-toolbar') ||
            [...document.querySelectorAll('.ui-tray')].find(isQuestionnaireTray) ||
            null);
    }
    function activate(el) {
        const target = el ?? el;
        target.scrollIntoView({ block: 'center', behavior: 'instant' });
        target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }));
        target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true }));
        target.click();
    }
    function findFreeformRow(root) {
        if (opts.selectorPath) {
            const hit = document.querySelector(opts.selectorPath);
            const row = hit?.closest('.ui-tray-option, .questionnaire-freeform-option, .composer-questionnaire-toolbar-option');
            if (row)
                return row;
        }
        const letter = (opts.letter ?? '').trim().toUpperCase();
        const optionSel = '.ui-tray-option, .composer-questionnaire-toolbar-option';
        for (const optEl of root.querySelectorAll(optionSel)) {
            if (optEl.classList.contains('questionnaire-freeform-option'))
                return optEl;
            if (letter) {
                const badge = (optEl.querySelector('.ui-tray-option__badge, .composer-questionnaire-toolbar-option-letter')?.textContent || '')
                    .trim()
                    .toUpperCase();
                if (badge === letter)
                    return optEl;
            }
            if (/^other/i.test((optEl.textContent || '').trim()))
                return optEl;
        }
        return root.querySelector('.questionnaire-freeform-option');
    }
    function fillInput(el, text) {
        el.focus();
        if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
            el.value = text;
            el.dispatchEvent(new Event('input', { bubbles: true }));
            el.dispatchEvent(new Event('change', { bubbles: true }));
            return true;
        }
        if (el.isContentEditable) {
            el.textContent = text;
            el.dispatchEvent(new InputEvent('input', { bubbles: true, data: text }));
            return true;
        }
        return false;
    }
    function findFreeformInput(root, row) {
        const scopes = [row, root].filter((el) => Boolean(el));
        for (const scope of scopes) {
            for (const sel of [
                'input:not([type="hidden"])',
                'textarea',
                '[contenteditable="true"]',
                '[role="textbox"]',
            ]) {
                const hit = scope.querySelector(sel);
                if (hit instanceof HTMLElement && hit.offsetParent !== null)
                    return hit;
            }
        }
        return null;
    }
    const root = findRoot();
    if (!root)
        return false;
    if (action === 'freeform_text') {
        const text = (opts.text ?? '').trim();
        if (!text)
            return false;
        const row = findFreeformRow(root);
        if (row)
            activate(row);
        let input = findFreeformInput(root, row);
        if (!input && row) {
            activate(row);
            input = findFreeformInput(root, row);
        }
        if (!input)
            return false;
        return fillInput(input, text);
    }
    if (action === 'skip' || action === 'continue') {
        const want = action === 'skip' ? /^(skip|пропустить)$/i : /^(continue|next|продолжить|далее)$/i;
        const actionRoot = root.querySelector('.ui-tray-actions, .composer-questionnaire-toolbar-actions') || root;
        for (const btn of actionRoot.querySelectorAll('button')) {
            const label = (btn.textContent || '').replace(/\s+/g, ' ').trim();
            if (!label || !want.test(label))
                continue;
            activate(btn);
            return true;
        }
        return false;
    }
    const letter = (opts.letter ?? '').trim().toUpperCase();
    const labelNeedle = (opts.label ?? '').trim().toLowerCase().slice(0, 48);
    if (opts.selectorPath) {
        const el = document.querySelector(opts.selectorPath);
        if (el) {
            const row = el.closest('.ui-tray-option, .questionnaire-freeform-option, .composer-questionnaire-toolbar-option') || el;
            activate(row);
            return true;
        }
    }
    const optionSel = '.ui-tray-option, .composer-questionnaire-toolbar-option';
    for (const optEl of root.querySelectorAll(optionSel)) {
        const optLetter = (optEl.querySelector('.ui-tray-option__badge, .composer-questionnaire-toolbar-option-letter')?.textContent || '')
            .trim()
            .toUpperCase();
        const optLabel = (optEl.querySelector('.ui-tray-option__label, .composer-questionnaire-toolbar-option-label')?.textContent ||
            optEl.textContent ||
            '')
            .trim()
            .toLowerCase();
        if (letter && optLetter === letter) {
            activate(optEl);
            return true;
        }
        if (labelNeedle && optLabel.includes(labelNeedle)) {
            activate(optEl);
            return true;
        }
    }
    return false;
}
