/**
 * Remove a deferred-queue row in the composer (Editor toolbar or Agents tray).
 * Used via CDP callFunction — helpers must stay inside this function.
 */
export function queueRemoveDomAction(action, opts) {
    function normText(s) {
        return s.trim().replace(/\s+/g, ' ').toLowerCase();
    }
    function clickRemoveButton(btn) {
        const el = btn;
        el.scrollIntoView({ block: 'center', behavior: 'instant' });
        el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }));
        el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true }));
        el.click();
    }
    function findRemoveButton(row) {
        const legacy = row.querySelector('button[aria-label="Remove"]');
        if (legacy)
            return legacy;
        const removeAction = row.querySelector('[data-queue-action="remove"]');
        if (removeAction) {
            return (removeAction.closest('button') ||
                removeAction.querySelector('button, .anysphere-icon-button') ||
                removeAction);
        }
        const trash = row.querySelector('.codicon-trashcan');
        if (trash) {
            return (trash.closest('button') ||
                trash.closest('.anysphere-icon-button') ||
                trash.parentElement);
        }
        return null;
    }
    const rowSelectors = [
        '.composer-toolbar-queue-item',
        '[class*="ui-tray--queued"] [class*="queue-sortable-row"]',
        '[class*="ui-tray--queued"] [class*="ui-tray-row"]',
        '[class*="queue-sortable-row"]',
        '[class*="ui-tray-row"]',
    ];
    function queueScope() {
        const input = document.querySelector(".composer-bar [contenteditable='true'], [contenteditable='true']");
        const agentPanel = input?.closest('[class*="agent-panel"]');
        const tray = document.querySelector('[class*="ui-tray--queued"]');
        if (agentPanel && tray && agentPanel.contains(tray)) {
            return agentPanel;
        }
        return (agentPanel ||
            input?.closest('[class*="composer-panel"]') ||
            input?.closest('.composer-bar, [class*="composer-bar"]') ||
            document.querySelector('#composer-toolbar-section') ||
            document.body);
    }
    function rowsInScope() {
        const scope = queueScope();
        const out = [];
        for (const sel of rowSelectors) {
            scope.querySelectorAll(sel).forEach((row) => {
                if (!out.includes(row))
                    out.push(row);
            });
        }
        return out;
    }
    if (action !== 'remove')
        return { ok: false, reason: 'unknown action' };
    const itemId = opts.queueItemId?.trim();
    if (itemId) {
        const row = document.querySelector(`[data-queue-item-id="${itemId}"]`);
        if (!row)
            return { ok: false, reason: 'queue item not found' };
        const btn = findRemoveButton(row);
        if (!btn)
            return { ok: false, reason: 'remove button not found' };
        clickRemoveButton(btn);
        return { ok: true };
    }
    const want = normText(opts.text ?? '');
    const snippet = want.slice(0, 48);
    if (snippet.length >= 4) {
        for (const row of rowsInScope()) {
            const label = row.querySelector('.ui-tray-row__label');
            const rowText = normText(label?.textContent || row.textContent || '');
            const rowSnippet = rowText.slice(0, 48);
            if (!rowText.includes(snippet) && !rowSnippet.includes(snippet.slice(0, 24))) {
                continue;
            }
            const btn = findRemoveButton(row);
            if (!btn)
                return { ok: false, reason: 'remove button not found' };
            clickRemoveButton(btn);
            return { ok: true };
        }
    }
    const path = opts.selectorPath?.trim();
    if (path) {
        const el = document.querySelector(path);
        if (!el)
            return { ok: false, reason: 'selector not found' };
        const row = el.closest('[data-queue-item-id], .composer-toolbar-queue-item, [class*="queue-sortable-row"], [class*="ui-tray-row"]');
        const btn = row ? findRemoveButton(row) : el;
        if (!btn)
            return { ok: false, reason: 'remove target not found' };
        clickRemoveButton(btn);
        return { ok: true };
    }
    return { ok: false, reason: want ? 'queue row not found' : 'no text or selector' };
}
