/**
 * Focus a chat row in the Cursor Agents sidebar (CDP callFunction body).
 */
import { readActiveChatDom } from './read-active-chat-dom.js';
export function focusSidebarAgentDom(opts) {
    const wantTitle = (opts.title ?? '').trim();
    const wantId = (opts.agentId ?? '').trim();
    const wantRepo = (opts.repoName ?? '').trim();
    const norm = (s) => s
        .trim()
        .replace(/\s+/g, ' ')
        .replace(/\d+\s*(?:s|m|h|d|w)\b/gi, '')
        .replace(/\d+[smhdw]$/i, '')
        .toLowerCase();
    const titleNorm = wantTitle ? norm(wantTitle) : '';
    const idNorm = wantId.toLowerCase();
    function cleanSidebarTitle(btn) {
        const label = btn.querySelector('.ui-sidebar-menu-button-label');
        let t = (label?.textContent || btn.textContent || '').trim().replace(/\s+/g, ' ');
        t = t
            .replace(/\d+\s*(?:s|m|h|d|w)\b/gi, '')
            .replace(/\d+[smhdw]$/i, '')
            .trim();
        return t;
    }
    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 matchBtn(btn) {
        const t = cleanSidebarTitle(btn);
        const tNorm = norm(t);
        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() === idNorm))
            return true;
        if (titleNorm && tNorm === titleNorm)
            return true;
        if (titleNorm && tNorm.length >= 6 && titleNorm.length >= 6) {
            if (tNorm.includes(titleNorm) || titleNorm.includes(tNorm))
                return true;
        }
        if (idNorm.startsWith('title:') && tNorm === idNorm.slice(6))
            return true;
        return false;
    }
    function activateBtn(btn) {
        const row = btn.closest('li.ui-sidebar-menu-item') ?? btn;
        row.scrollIntoView({ block: 'nearest', behavior: 'instant' });
        const target = btn.querySelector('.ui-sidebar-menu-button-label') ||
            btn;
        target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }));
        target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true }));
        target.click();
    }
    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, reason: 'no-sidebar' };
    let sectionName = '';
    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, ' '));
            // Scope row search by repo only — do not click section head (collapses/expands folder UI).
            if (wantRepo && repoMatches(sectionName, wantRepo)) {
                el.scrollIntoView({ block: 'nearest', behavior: 'instant' });
            }
            continue;
        }
        if (!repoMatches(sectionName, wantRepo))
            continue;
        if (matchBtn(el)) {
            targetBtn = el;
            break;
        }
    }
    if (!targetBtn) {
        for (const btn of document.querySelectorAll(rowSelector)) {
            if (matchBtn(btn)) {
                targetBtn = btn;
                break;
            }
        }
    }
    if (!targetBtn) {
        return { ok: false, reason: 'row-not-found' };
    }
    activateBtn(targetBtn);
    const active = readActiveChatDom();
    const activeTitle = active.title ? norm(active.title) : '';
    const activeId = (active.composerId ?? '').toLowerCase();
    if (titleNorm && activeTitle) {
        const titleOk = activeTitle === titleNorm ||
            activeTitle.includes(titleNorm) ||
            titleNorm.includes(activeTitle);
        if (titleOk)
            return { ok: true, active };
    }
    if (wantId && activeId && (activeId === idNorm || activeId.includes(idNorm))) {
        return { ok: true, active };
    }
    if (active.composerId || active.title) {
        return { ok: true, active, reason: 'clicked-unverified' };
    }
    return { ok: false, reason: 'click-no-active', active };
}
