(function initAliExpressExtractor() {
    'use strict';
    console.clear();
    console.log('🚀 正在初始化 AliExpress 一键下载插件...');

    // ==========================================
    // 1. 核心提取逻辑 (直接调用你测试完美的终极版)
    // ==========================================
    async function runExtraction() {
        console.log('🚀 开始全自动提取...');
        let globalHeaders = [];
        let globalTableData = [];
        let isFirstPage = true;

        const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

        function simulateMouseDown(element) {
            const event = new MouseEvent('mousedown', { view: window, bubbles: true, cancelable: true });
            element.dispatchEvent(event);
        }

        async function waitForTableUpdate(actionCallback, actionName = "操作") {
            const getTableText = () => {
                const tbody = document.querySelector('tbody');
                return tbody ? tbody.innerText.trim() : '';
            };
            const oldText = getTableText();
            console.log(`⏳ 执行 [${actionName}]，等待真实数据渲染...`);
            actionCallback();
            await sleep(600);
            let maxWait = 40;
            while (maxWait > 0) {
                const loadingMask = document.querySelector('.ant-spin-spinning, .next-loading-active, div[class*="loading-mask"], div[class*="ait-loading"]');
                if (loadingMask) {
                    await sleep(500); maxWait--; continue;
                }
                const newText = getTableText();
                if (newText !== oldText && newText !== '') {
                    await sleep(600);
                    console.log(`✅ [${actionName}] 页面刷新完毕！`);
                    return true;
                }
                await sleep(500); maxWait--;
            }
            console.warn(`⚠️ [${actionName}] 等待超时，强制放行...`);
            return false;
        }

        function extractCurrentPage() {
            let thElements = Array.from(document.querySelectorAll('thead th, .next-table-header-node, .ant-table-cell'));
            if (thElements.length === 0) return false;

            const currentHeaders = [];
            const excludeIndices = new Set(); 

            thElements.forEach((th, index) => {
                const text = th.innerText.trim().replace(/\n+/g, ' '); 
                if (!text || text.includes('操作')) excludeIndices.add(index);
                else currentHeaders.push(text);
            });

            if (isFirstPage && currentHeaders.length > 0) {
                globalHeaders = currentHeaders;
                isFirstPage = false;
            }

            let trElements = Array.from(document.querySelectorAll('tbody tr.next-table-row, tbody tr.ant-table-row'));
            if (trElements.length === 0) trElements = Array.from(document.querySelectorAll('tbody tr'));

            let extractedRows = 0;
            trElements.forEach(tr => {
                const tdElements = Array.from(tr.querySelectorAll('td'));
                if (tdElements.length === 0) return;
                const rowData = [];
                tdElements.forEach((td, index) => {
                    if (!excludeIndices.has(index)) {
                        rowData.push(td.innerText.trim().replace(/\n+/g, ' | '));
                    }
                });
                if (rowData.length > 0 && rowData.some(cell => cell !== '')) {
                    globalTableData.push(rowData);
                    extractedRows++;
                }
            });
            console.log(`✅ 本页提取到 ${extractedRows} 条数据。`);
            return true;
        }

        try {
            // 切 100 条
            let bottomEle = document.querySelector("ul.ait-table-pagination-left, ul.ant-pagination");
            if (bottomEle) {
                let divPage = bottomEle.querySelector("div.ait-select-selector, div.ant-select-selector");
                if (divPage) {
                    simulateMouseDown(divPage);
                    await sleep(500); 
                    let tempDoms = document.querySelector("div.ait-select-dropdown:not(.ait-select-dropdown-hidden), div.ant-select-dropdown:not(.ant-select-dropdown-hidden)");
                    if (tempDoms) {
                        let option100 = Array.from(tempDoms.querySelectorAll("div.ait-select-item-option, div.ant-select-item-option")).find(item => item.title && item.title.includes("100"));
                        if (option100) {
                            let isSelected = option100.classList.contains('ait-select-item-option-selected') || option100.classList.contains('ant-select-item-option-selected');
                            if (!isSelected) await waitForTableUpdate(() => option100.click(), "切换 100 条/页");
                            else { option100.click(); await sleep(500); }
                        }
                    }
                }
            }

            // 回第一页
            bottomEle = document.querySelector("ul.ait-table-pagination-left, ul.ant-pagination"); 
            if (bottomEle) {
                let firstPageLi = Array.from(bottomEle.querySelectorAll("li.ait-pagination-item, li.ant-pagination-item")).find(item => item.title == "1");
                if (firstPageLi) {
                    let isActive = firstPageLi.classList.contains('ait-pagination-item-active') || firstPageLi.classList.contains('ant-pagination-item-active');
                    if (!isActive) await waitForTableUpdate(() => firstPageLi.click(), "返回第一页");
                }
            }

            // 循环翻页提取
            let pageNum = 1;
            while (true) {
                console.log(`\n📄 正在提取第 ${pageNum} 页...`);
                extractCurrentPage();
                bottomEle = document.querySelector("ul.ait-table-pagination-left, ul.ant-pagination"); 
                if (!bottomEle) break;
                let nextBtn = bottomEle.querySelector("li.ait-pagination-next button, li.ait-pagination-next, li.ant-pagination-next");
                if (!nextBtn || nextBtn.disabled || nextBtn.classList.contains('ant-pagination-disabled') || nextBtn.classList.contains('ait-pagination-disabled')) break;
                await waitForTableUpdate(() => nextBtn.click(), `翻到第 ${pageNum + 1} 页`);
                pageNum++;
            }

            // 数据清洗
            const uniqueData = [];
            const seenStr = new Set();
            for (let row of globalTableData) {
                let rowFingerprint = row.join('|||');
                if (!seenStr.has(rowFingerprint)) {
                    seenStr.add(rowFingerprint);
                    uniqueData.push(row);
                }
            }

            // 自动下载逻辑 (生成 TSV 文本并触发下载)
            const tsvContent = [globalHeaders.join('\t'), ...uniqueData.map(row => row.join('\t'))].join('\n');
            const blob = new Blob([tsvContent], { type: 'text/tab-separated-values;charset=utf-8;' });
            const link = document.createElement('url');
            const url = URL.createObjectURL(blob);
            const downloadBtn = document.createElement('a');
            downloadBtn.href = url;
            downloadBtn.setAttribute('download', `速卖通提取数据_${new Date().getTime()}.xls`); // 伪装成 xls，Excel 可直接打开
            document.body.appendChild(downloadBtn);
            downloadBtn.click();
            document.body.removeChild(downloadBtn);
            URL.revokeObjectURL(url);

            alert(`🎉 提取成功！共提取 ${uniqueData.length} 条数据，已自动为您下载。`);

        } catch (error) {
            console.error('❌ 提取出错：', error);
            alert('❌ 提取出错，请按 F12 查看控制台报错信息。');
        }
    }

    // ==========================================
    // 2. UI 按钮注入与 DOM 监听
    // ==========================================
    function injectButton() {
        const targetNav = document.querySelector('.ait-tabs-nav');
        
        // 如果找不到目标元素，或者按钮已经存在，则退出
        if (!targetNav || document.querySelector('#ali-auto-download-btn')) {
            return;
        }

        // 创建按钮
        const btn = document.createElement('button');
        btn.id = 'ali-auto-download-btn';
        btn.innerText = '一键下载表格';
        
        // 按钮样式（与原网页风格对齐，并使用 margin-left: auto 推到最右边）
        btn.style.cssText = `
            margin-left: auto;
            margin-right: 16px;
            padding: 0 15px;
            height: 32px;
            background-color: #1677ff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            align-self: center;
            z-index: 100;
            transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
            box-shadow: 0 2px 0 rgba(5, 145, 255, 0.1);
        `;

        // 鼠标悬停特效
        btn.onmouseover = () => btn.style.backgroundColor = '#4096ff';
        btn.onmouseout = () => btn.style.backgroundColor = '#1677ff';

        // 绑定点击事件，点击时防止重复点击并执行提取
        btn.onclick = async function() {
            if (btn.innerText === '提取中...') return;
            const originalText = btn.innerText;
            const originalBg = btn.style.backgroundColor;
            
            btn.innerText = '提取中...';
            btn.style.backgroundColor = '#999';
            btn.style.cursor = 'not-allowed';
            
            await runExtraction();
            
            btn.innerText = originalText;
            btn.style.backgroundColor = '#1677ff';
            btn.style.cursor = 'pointer';
        };

        // 追加到 Tab 导航栏的最后面
        targetNav.appendChild(btn);
        console.log('✅ 下载按钮注入成功！');
    }

    // 初始运行一次
    injectButton();

    // 建立 MutationObserver 监听，应对单页应用的动态路由切换
    const observer = new MutationObserver(() => {
        injectButton();
    });

    // 开始监控 body 内容的变动
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

})();