/**
 * Close an empty composer tab in Cursor (editor auxiliary bar or Agents sidebar row).
 * CDP callFunction body — keep helpers inside.
 */
export function closeChatDomAction(opts) {
    const wantId = (opts.agentId ?? '').trim();
    const wantTitle = (opts.title ?? '').trim();
    const wantRepo = (opts.repoName ?? '').trim();
    const stripEditorSuffix = (s) => s.replace(/,\s*Chat Editors:\s*Editor Group\s*\d+\s*$/i, '').trim();
    const norm = (s) => stripEditorSuffix(s)
        .replace(/\s+/g, ' ')
        .replace(/\d+\s*(?:s|m|h|d|w)\b/gi, '')
        .replace(/\d+[smhdw]$/i, '')
        .trim()
        .toLowerCase();
    const titleNorm = wantTitle ? norm(wantTitle) : '';
    const wantLower = wantId.toLowerCase();
    function idMatches(resource) {
        if (wantLower.length < 8 || !resource)
            return false;
        const r = resource.toLowerCase();
        if (r === wantLower)
            return true;
        if (wantLower.length >= 32 && (r.startsWith(wantLower) || wantLower.startsWith(r)))
            return true;
        if (wantLower.length >= 8 && r.length >= 32 && r.startsWith(wantLower))
            return true;
        return false;
    }
    function titleMatches(aria, visible) {
        if (!titleNorm)
            return false;
        for (const raw of [aria, visible]) {
            const c = raw ? norm(raw) : '';
            if (!c)
                continue;
            if (c === titleNorm)
                return true;
            if (c.length >= 8 && titleNorm.length >= 8 && (c.includes(titleNorm) || titleNorm.includes(c))) {
                return true;
            }
        }
        return false;
    }
    function revealHover(el) {
        const h = el;
        h.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, cancelable: true }));
        h.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true }));
    }
    function clickEl(el) {
        const target = el;
        target.scrollIntoView({ block: 'nearest', behavior: 'instant' });
        target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }));
        target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true }));
        target.click();
        return true;
    }
    function findCloseControl(root) {
        const selectors = [
            '.tab-close',
            '.codicon-close',
            'a.codicon-close',
            'button[aria-label*="Close" i]',
            'a[aria-label*="Close" i]',
            '[data-command-id*="close" i]',
            '[data-command-id*="delete" i]',
            'button[aria-label*="Delete" i]',
            'button[aria-label*="Remove" i]',
        ];
        for (const sel of selectors) {
            const hit = root.querySelector(sel);
            if (hit)
                return hit;
        }
        for (const el of root.querySelectorAll('a, button, .action-item, span')) {
            const cls = (el.className || '').toString();
            const aria = el.getAttribute('aria-label') || '';
            if (/close|delete|remove|trash/i.test(cls + aria))
                return el;
        }
        return null;
    }
    function editorTabStillOpen() {
        const aux = document.querySelector('#workbench\\.parts\\.auxiliarybar');
        if (!aux)
            return false;
        for (const tab of aux.querySelectorAll('div.tab[role="tab"]')) {
            const resource = tab.getAttribute('data-resource-name') || '';
            const aria = tab.getAttribute('aria-label') || '';
            const visible = (tab.textContent || '').trim();
            if (idMatches(resource) || titleMatches(aria, visible))
                return true;
        }
        return false;
    }
    function sidebarRowStillOpen() {
        const rowSelector = '.glass-sidebar-agent-list-container li.ui-sidebar-menu-item > div.glass-sidebar-agent-menu-btn, li.ui-sidebar-menu-item > div.glass-sidebar-agent-menu-btn';
        for (const btn of document.querySelectorAll(rowSelector)) {
            const cid = btn.getAttribute('data-composer-id') ||
                btn.closest('li')?.getAttribute('data-composer-id') ||
                btn.closest('[data-composer-id]')?.getAttribute('data-composer-id') ||
                '';
            if (cid && (cid === wantId || cid.toLowerCase() === wantLower))
                return true;
            const label = btn.querySelector('.ui-sidebar-menu-button-label');
            const t = norm((label?.textContent || btn.textContent || '').trim());
            if (titleNorm && t && (t === titleNorm || t.includes(titleNorm) || titleNorm.includes(t))) {
                return true;
            }
        }
        return false;
    }
    function tryCloseEditorTab() {
        const aux = document.querySelector('#workbench\\.parts\\.auxiliarybar');
        if (!aux || document.querySelector('[class*="agent-panel"]')) {
            return { ok: false };
        }
        for (const tab of aux.querySelectorAll('div.tab[role="tab"]')) {
            const resource = tab.getAttribute('data-resource-name') || '';
            const aria = tab.getAttribute('aria-label') || '';
            const visible = (tab.textContent || '').trim();
            if (!idMatches(resource) && !titleMatches(aria, visible))
                continue;
            revealHover(tab);
            const closeBtn = findCloseControl(tab);
            if (closeBtn && clickEl(closeBtn)) {
                return { ok: !editorTabStillOpen(), method: 'editor_tab_close_btn' };
            }
            const label = tab.querySelector('.label-name, .tab-label, [class*="label-name"]') || tab;
            clickEl(label);
            revealHover(tab);
            const closeAfterFocus = findCloseControl(tab);
            if (closeAfterFocus && clickEl(closeAfterFocus)) {
                return { ok: !editorTabStillOpen(), method: 'editor_tab_close_after_focus' };
            }
            tab.dispatchEvent(new MouseEvent('mouseup', { button: 1, buttons: 4, bubbles: true, cancelable: true }));
            tab.dispatchEvent(new MouseEvent('mousedown', { button: 1, buttons: 4, bubbles: true, cancelable: true }));
            if (!editorTabStillOpen())
                return { ok: true, method: 'editor_tab_middle_click' };
        }
        return { ok: false };
    }
    function repoMatches(sectionName, want) {
        if (!want)
            return true;
        const a = norm(sectionName);
        const b = norm(want);
        if (a === b)
            return true;
        if (a.includes(b) || b.includes(a))
            return true;
        const leafA = a.split('/').filter(Boolean).pop() ?? a;
        const leafB = b.split('/').filter(Boolean).pop() ?? b;
        return leafA === leafB || leafA.includes(leafB) || leafB.includes(leafA);
    }
    function tryCloseSidebarRow() {
        const rowSelector = '.glass-sidebar-agent-list-container li.ui-sidebar-menu-item > div.glass-sidebar-agent-menu-btn, li.ui-sidebar-menu-item > div.glass-sidebar-agent-menu-btn';
        const scroll = document.querySelector('[class*="glass-sidebar-scroll"]') ||
            document.querySelector('[class*="glass-sidebar-body"]') ||
            document.querySelector('[class*="glass-sidebar"]');
        if (!scroll)
            return { ok: false };
        let sectionName = '';
        let targetRow = null;
        let targetBtn = null;
        for (const el of scroll.querySelectorAll(`.ui-sidebar-section-head, ${rowSelector}`)) {
            if (el.classList.contains('ui-sidebar-section-head')) {
                const clone = el.cloneNode(true);
                clone.querySelectorAll('button, [role="button"], .ui-icon-button').forEach((n) => n.remove());
                sectionName = norm((clone.textContent || '').replace(/\s+/g, ' '));
                continue;
            }
            if (!repoMatches(sectionName, wantRepo))
                continue;
            const cid = el.getAttribute('data-composer-id') ||
                el.closest('li')?.getAttribute('data-composer-id') ||
                '';
            const label = el.querySelector('.ui-sidebar-menu-button-label');
            const t = norm((label?.textContent || el.textContent || '').trim());
            if ((cid && (cid === wantId || cid.toLowerCase() === wantLower)) || (titleNorm && t === titleNorm)) {
                targetBtn = el;
                targetRow = el.closest('li.ui-sidebar-menu-item') ?? el;
                break;
            }
        }
        if (!targetBtn) {
            for (const btn of document.querySelectorAll(rowSelector)) {
                const cid = btn.getAttribute('data-composer-id') ||
                    btn.closest('li')?.getAttribute('data-composer-id') ||
                    '';
                if (cid && (cid === wantId || cid.toLowerCase() === wantLower)) {
                    targetBtn = btn;
                    targetRow = btn.closest('li.ui-sidebar-menu-item') ?? btn;
                    break;
                }
            }
        }
        if (!targetBtn || !targetRow)
            return { ok: false };
        revealHover(targetRow);
        revealHover(targetBtn);
        const actions = targetRow.querySelector('.ui-sidebar-menu-button-actions') ||
            targetBtn.querySelector('.ui-sidebar-menu-button-actions') ||
            targetRow;
        const closeBtn = findCloseControl(actions);
        if (closeBtn && clickEl(closeBtn)) {
            return { ok: !sidebarRowStillOpen(), method: 'sidebar_row_close_btn' };
        }
        clickEl(targetBtn);
        revealHover(targetRow);
        const closeAfterFocus = findCloseControl(targetRow);
        if (closeAfterFocus && clickEl(closeAfterFocus)) {
            return { ok: !sidebarRowStillOpen(), method: 'sidebar_row_close_after_focus' };
        }
        return { ok: false };
    }
    const editor = tryCloseEditorTab();
    if (editor.ok)
        return { ok: true, method: editor.method };
    const sidebar = tryCloseSidebarRow();
    if (sidebar.ok)
        return { ok: true, method: sidebar.method };
    if (!editorTabStillOpen() && !sidebarRowStillOpen()) {
        return { ok: true, method: 'already_closed' };
    }
    return {
        ok: false,
        reason: wantId
            ? `Close control not found for chat ${wantId.slice(0, 8)}…`
            : 'Close control not found',
    };
}
