var taskManagerScrapingInterval = null;

function normalizeSearchQuery(value) {
    return String(value || '').trim().toLowerCase();
}

function isExtractionSearchTab(tabUrl, activeQuery = "") {
    if (!tabUrl) return false;

    try {
        const url = new URL(tabUrl);
        const isGoogleSearch = /(^|\.)google\./i.test(url.hostname) && url.pathname === '/search';
        if (!isGoogleSearch || url.searchParams.get('udm') !== '1') {
            return false;
        }

        const tabQuery = normalizeSearchQuery(url.searchParams.get('q'));
        const expectedQuery = normalizeSearchQuery(activeQuery);
        return !expectedQuery || tabQuery === expectedQuery;
    } catch (err) {
        console.warn('Unable to inspect tab URL while stopping extraction:', err);
        return false;
    }
}

function closeExtractionSearchTabs(activeQuery = "", openedWindowIds = []) {
    if (!chrome.tabs?.query) {
        return;
    }

    const extractionWindowIds = new Set(openedWindowIds);

    chrome.tabs.query({}, (tabs) => {
        tabs.forEach(tab => {
            const isTrackedWindow = extractionWindowIds.has(tab.windowId);
            if (!isTrackedWindow && !isExtractionSearchTab(tab.url, activeQuery)) {
                return;
            }

            chrome.tabs.remove(tab.id, () => {
                if (chrome.runtime.lastError) {
                    console.log('Unable to close extraction tab:', chrome.runtime.lastError.message);
                }
            });
        });
    });
}

function rememberOpenedWindow(windowId) {
    if (!windowId) return;

    $box.getLocal(local => {
        if (!local.status) {
            return;
        }

        if (!Array.isArray(local.openedWindows)) {
            local.openedWindows = [];
        }

        if (!local.openedWindows.includes(windowId)) {
            local.openedWindows.push(windowId);
            $box.setLocal(local);
        }
    });
}

TaskManager.container.start = () => {
    $box.getLocal(local => {
        local.status = true;
        $box.setLocal(local, {
            onSet: () => {
                console.log("Opening Google Maps");
                TaskManager.gotoTask(local, 'openMap');
            }
        });
    });
};

TaskManager.container.openMap = () => {
    $box.getLocal(local => {
        console.log(local);

        if (Array.isArray(local.taskList) && local.taskList.length) {
            const activeTask = local.taskList[0] || "";
            const [keyword = "", location = ""] = activeTask.split('~in~');
            local.activeKeyword = keyword.trim();
            local.activeLocation = location.trim();
            local.activeQuery = [local.activeKeyword, local.activeLocation].filter(Boolean).join(' in ');

            if (!local.activeQuery) {
                local.taskList.shift();
                $box.setLocal(local, {
                    onSet: () => {
                        console.log("Skipping empty search query");
                        $box.send('start');
                    }
                });
                return;
            }

            $box.setLocal(local, {
                onSet: () => {
                    console.log("Open Map");
                    console.log(local);
                    closeExtractionSearchTabs(local.activeQuery);

                    const searchUrl = new URL('https://www.google.com/search');
                    searchUrl.searchParams.set('q', local.activeQuery);
                    searchUrl.searchParams.set('udm', '1');
                    const url = searchUrl.toString();
                    // chrome.tabs.create({ url: url, active: true });
                    chrome.windows.create({ url: url, focused: true }, openedWindow => {
                        if (chrome.runtime.lastError) {
                            console.log('Unable to open Google search window:', chrome.runtime.lastError.message);
                            return;
                        }

                        rememberOpenedWindow(openedWindow?.id);
                    });
                }
            });
        } else {
            console.log("Task List is empty");
            local.status = false;
            // $box.setLocal(local);
            TaskManager.gotoTask(local, 'completed');
        }

    });
};


TaskManager.container.completed = () => {
    $box.notify("Scraping Completed");
    $box.getLocal(local => {
        console.log('** Stopping task manager.');
        TaskManager.gotoTask(local, 'stop');
    });
};

TaskManager.container.stop = () => {
    $box.getLocal(local => {
        if (local._taskManager)
            local._taskManager.isWorking = false;
        const activeQuery = local.activeQuery;
        const openedWindowIds = Array.isArray(local.openedWindows) ? local.openedWindows.slice() : [];
        local.status = false;
        local.openedWindows = [];
        console.log("Stoping Taskmanager");
        console.log(taskManagerScrapingInterval);
        clearInterval(taskManagerScrapingInterval);
        $box.setLocal(local, {
            onSet: () => {
                console.log("Stoping TaskManager");
                console.log(local);
                closeExtractionSearchTabs(activeQuery, openedWindowIds);
            }
        });
    });
};
