/**
 * Per-repo «+» / New Agent in Agents sidebar (CDP callFunction).
 * App passes `newChatSelectorPath` from `sidebarRepos` (extract-page); bridge reveals
 * repo row via synthetic hover and clicks — no CDP Input pointer dance.
 */
export function newChatDomAction(opts) {
    function normText(s) {
        return s
            .trim()
            .replace(/\s+/g, ' ')
            .replace(/\d+\s*(?:s|m|h|d|w)\b/gi, '')
            .replace(/\d+[smhdw]$/i, '')
            .toLowerCase();
    }
    function isVisible(el) {
        const h = el;
        const st = getComputedStyle(h);
        if (st.visibility === 'hidden' || st.display === 'none')
            return false;
        if (st.opacity === '0' || st.pointerEvents === 'none')
            return false;
        const r = h.getBoundingClientRect();
        return r.width > 0 && r.height > 0;
    }
    function isHoverRevealedNewChatButton(btn, head) {
        if (!head.contains(btn))
            return false;
        const actions = btn.closest('.ui-sidebar-menu-button-actions');
        if (actions && getComputedStyle(actions).display === 'none')
            return false;
        const br = btn.getBoundingClientRect();
        return br.width > 0 && br.height > 0;
    }
    function clickEl(el) {
        const h = el;
        h.scrollIntoView({ block: 'nearest', behavior: 'instant' });
        try {
            h.focus();
        }
        catch {
            /* ignore */
        }
        const opts = { bubbles: true, cancelable: true, view: window };
        h.dispatchEvent(new PointerEvent('pointerdown', { ...opts, pointerId: 1 }));
        h.dispatchEvent(new MouseEvent('mousedown', opts));
        h.dispatchEvent(new PointerEvent('pointerup', { ...opts, pointerId: 1 }));
        h.dispatchEvent(new MouseEvent('mouseup', opts));
        h.click();
    }
    function clickSelector(path, requireVisible) {
        try {
            const el = document.querySelector(path);
            if (!el)
                return false;
            const btn = (el.closest('button') || el);
            if (requireVisible && !isVisible(btn))
                return false;
            clickEl(btn);
            return true;
        }
        catch {
            return false;
        }
    }
    function sectionScope(head) {
        return head.parentElement ?? head;
    }
    function pathInSection(head, el) {
        if (!head)
            return true;
        const scope = sectionScope(head);
        return head.contains(el) || scope.contains(el);
    }
    function sectionHeadLabel(head) {
        const clone = head.cloneNode(true);
        clone
            .querySelectorAll('button, [role="button"], .ui-icon-button')
            .forEach((el) => el.remove());
        return normText((clone.textContent || '').replace(/\s+/g, ' '));
    }
    function sidebarScrollRoot() {
        return (document.querySelector('[class*="glass-sidebar-scroll"]') ||
            document.querySelector('[class*="glass-sidebar-body"]') ||
            document.querySelector('[class*="glass-sidebar"]'));
    }
    function repoSectionKey(name) {
        const t = name.trim().replace(/\s+/g, ' ');
        const commaIdx = t.indexOf(',');
        if (commaIdx <= 0)
            return t.toLowerCase();
        const pathPart = t.slice(0, commaIdx).trim();
        const suffixPart = t.slice(commaIdx + 1).trim();
        if (!pathPart || !suffixPart)
            return t.toLowerCase();
        const pathLeaf = pathPart.split('/').filter(Boolean).pop()?.toLowerCase() ?? '';
        const suffixNorm = suffixPart.toLowerCase().replace(/\s+/g, '');
        if (suffixNorm === pathLeaf.replace(/\s+/g, '') ||
            pathPart.toLowerCase().endsWith(`/${suffixNorm}`)) {
            return pathPart.toLowerCase();
        }
        return t.toLowerCase();
    }
    function repoMatches(sectionName, wantRepo) {
        const a = repoSectionKey(sectionName);
        const b = repoSectionKey(wantRepo);
        return a === b || a.includes(b) || b.includes(a);
    }
    function findSectionHead(wantRepo) {
        const scroll = sidebarScrollRoot();
        if (!scroll)
            return null;
        for (const head of scroll.querySelectorAll('.ui-sidebar-section-head')) {
            const name = sectionHeadLabel(head);
            if (!name)
                continue;
            if (repoMatches(name, wantRepo)) {
                return head;
            }
        }
        return null;
    }
    function findRepoHeaderRow(wantRepo) {
        const scroll = sidebarScrollRoot();
        const roots = [];
        if (scroll)
            roots.push(scroll);
        roots.push(document);
        for (const root of roots) {
            for (const title of root.querySelectorAll('.ui-sidebar-label-row-title')) {
                const t = normText((title.textContent || '').replace(/\s+/g, ' '));
                if (!t)
                    continue;
                if (repoMatches(t, wantRepo)) {
                    return (title.closest('.ui-sidebar-label-row') || title.parentElement) ?? title;
                }
            }
        }
        return null;
    }
    function hoverRevealTargets(wantRepo) {
        const title = Array.from(document.querySelectorAll('.ui-sidebar-label-row-title')).find((el) => normText(el.textContent || '').includes(wantRepo));
        const head = findSectionHead(wantRepo);
        const out = [];
        if (title)
            out.push(title);
        if (head)
            out.push(head);
        return out;
    }
    function dispatchHover(el) {
        const r = el.getBoundingClientRect();
        const x = r.left + r.width / 2;
        const y = r.top + r.height / 2;
        const hoverOpts = {
            bubbles: true,
            cancelable: true,
            view: window,
            clientX: x,
            clientY: y,
        };
        el.dispatchEvent(new MouseEvent('mouseover', hoverOpts));
        el.dispatchEvent(new MouseEvent('mouseenter', hoverOpts));
        el.dispatchEvent(new MouseEvent('mousemove', hoverOpts));
    }
    function revealRepoHover(wantRepo) {
        for (const el of hoverRevealTargets(wantRepo)) {
            dispatchHover(el);
        }
    }
    function findRepoHeaderPlus(row, head) {
        const scope = head ?? row;
        const icon = scope.querySelector('i[data-icon-name="plus"]');
        if (icon) {
            const btn = icon.closest('button') ||
                icon.closest('[role="button"]') ||
                icon.closest('.ui-icon-button') ||
                icon.parentElement;
            if (btn && head && isHoverRevealedNewChatButton(btn, head))
                return btn;
            if (btn && !head && isVisible(btn))
                return btn;
        }
        const ariaBtn = scope.querySelector('button[aria-label*="New Agent" i]') ||
            scope.querySelector('button[aria-label*="New Chat" i]') ||
            scope.querySelector('button[aria-label*="Новый" i]');
        if (ariaBtn && head && isHoverRevealedNewChatButton(ariaBtn, head))
            return ariaBtn;
        if (ariaBtn && !head && isVisible(ariaBtn))
            return ariaBtn;
        return null;
    }
    function findNewChatButton(root) {
        const sels = [
            'button.ui-icon-button[aria-label*="New Agent" i]',
            'button.ui-icon-button[aria-label*="New Chat" i]',
            "[data-command-id='composer.createNewComposerTab']",
            "[data-command-id*='createNewComposer']",
            'button.codicon-add-two',
            "button[aria-label*='New Chat' i]",
            "button[aria-label*='New Agent' i]",
            "button[aria-label*='Новый чат' i]",
            "button[aria-label*='Новый агент' i]",
            'i[data-icon-name="plus"]',
        ];
        for (const sel of sels) {
            try {
                const hits = root.querySelectorAll(sel);
                for (const hit of hits) {
                    if (hit && isVisible(hit)) {
                        return hit.closest('button') || hit.closest('[role="button"]') || hit;
                    }
                }
            }
            catch {
                /* skip */
            }
        }
        const icon = root.querySelector('.codicon-add-two, .codicon-add');
        if (icon) {
            const btn = icon.closest('button') ||
                icon.closest('.anysphere-icon-button') ||
                icon.parentElement;
            if (btn && isVisible(btn))
                return btn;
        }
        return null;
    }
    function clickInRoot(root, sel) {
        try {
            const hit = root.querySelector(sel);
            if (!hit || !isVisible(hit))
                return false;
            const btn = hit.closest('button') || hit.closest('a') || hit;
            if (!isVisible(btn))
                return false;
            clickEl(btn);
            return true;
        }
        catch {
            return false;
        }
    }
    function clickEditorGlobal() {
        const aux = document.querySelector('#workbench\\.parts\\.auxiliarybar');
        const roots = aux ? [aux] : [];
        roots.push(document);
        for (const root of roots) {
            for (const sel of opts.globalButtonSelectors) {
                if (clickInRoot(root, sel))
                    return true;
            }
        }
        return false;
    }
    const wantRepo = normText(opts.repoName ?? '');
    const selectorPath = opts.selectorPath?.trim() ?? '';
    function findNewChatInSection(head, wantRepo) {
        try {
            head.scrollIntoView({ block: 'nearest', behavior: 'instant' });
            revealRepoHover(wantRepo);
        }
        catch {
            /* ignore */
        }
        const roots = [head, head.parentElement].filter(Boolean);
        for (const root of roots) {
            const btn = findNewChatButton(root);
            if (btn && isHoverRevealedNewChatButton(btn, head))
                return btn;
        }
        const loose = head.querySelector('button[aria-label="New Agent"]');
        if (loose)
            return loose;
        return null;
    }
    if (wantRepo) {
        revealRepoHover(wantRepo);
        const head = findSectionHead(wantRepo);
        const repoRow = findRepoHeaderRow(wantRepo);
        if (selectorPath) {
            const pathEl = document.querySelector(selectorPath);
            if (pathEl && (!head || pathInSection(head, pathEl))) {
                if (clickSelector(selectorPath, false)) {
                    return { ok: true, method: 'selector_path' };
                }
            }
            if (clickSelector(selectorPath, false)) {
                return { ok: true, method: 'selector_path' };
            }
        }
        if (repoRow || head) {
            const plus = findRepoHeaderPlus(repoRow ?? head, head);
            if (plus) {
                clickEl(plus);
                return { ok: true, method: 'dom_click' };
            }
            const looseBtn = head?.querySelector('button[aria-label="New Agent"]');
            if (looseBtn) {
                clickEl(looseBtn);
                return { ok: true, method: 'dom_click' };
            }
        }
        if (head) {
            const btn = findNewChatInSection(head, wantRepo);
            if (btn) {
                clickEl(btn);
                return { ok: true, method: 'dom_click' };
            }
            if (selectorPath && clickSelector(selectorPath, true)) {
                return { ok: true, method: 'selector_path' };
            }
        }
        return {
            ok: false,
            reason: `New chat control not found for folder «${opts.repoName}»`,
        };
    }
    if (selectorPath && clickSelector(selectorPath, true)) {
        return { ok: true, method: 'selector_path' };
    }
    if (clickEditorGlobal())
        return { ok: true, method: 'global' };
    return { ok: false, reason: 'New chat button not found' };
}
