/**
 * 速卖通邮费计算工具 - 主界面
 * 新版本主界面，包含小清新配色和完整功能
 */

// 全局变量
let userAction = {
    showType: 1, // 0: 圆盘, 1: 表单
    currency: 'CNY', // 默认人民币
    rate: 1 // 默认汇率
};

let clickCount = 0;
let lastClickTime = 0;
const DOUBLE_CLICK_DELAY = 200; // 双击最大时间间隔（毫秒）

// 已加载的弹窗列表
// const loadedModals = {};

// 初始化函数
async function initMainInterface() {
    // 直接初始化界面，不再等待配置初始化
    // 因为init-config.js已经确保FactoryConfig在页面加载时可用
    
    // 加载用户设置
    await loadUserSettings();
    
    // 初始化界面
    initializeUI();
    
    // 绑定事件
    bindEvents();
    
    // 初始化汇率
    await initializeExchangeRate();

    // 预加载类目数据 (提升用户体验)
    if (window.categoryLoader) {
        console.log('🚀 [Main] 预加载类目数据...');
        window.categoryLoader.getData();
    }
}

// 加载用户设置
async function loadUserSettings() {
    const stored = localStorage.getItem('userAction');
    if (stored) {
        userAction = { ...userAction, ...JSON.parse(stored) };
    }
}

// 保存用户设置
function saveUserSettings() {
    localStorage.setItem('userAction', JSON.stringify(userAction));
}

// 初始化界面
function initializeUI() {
    const mainInterface = document.getElementById('mainInterface');
    const minimizedDisc = document.getElementById('minimizedDisc');
    
    // 设置图标路径 - 使用chrome.runtime.getURL获取扩展资源路径
    const minimizeIcon = document.querySelector('#minimizeBtn .header-icon');
    const heartIcon = document.querySelector('#heartBtn .header-icon');
    
    if (minimizeIcon) {
        minimizeIcon.src = chrome.runtime.getURL('icons/font/AliExpress_suoxiao.png');
    }
    if (heartIcon) {
        heartIcon.src = chrome.runtime.getURL('icons/font/AliExpress_aixin_1.png');
    }
    
    // 根据showType显示对应界面
    if (userAction.showType === 0) {
        mainInterface.classList.add('hidden');
        minimizedDisc.style.display = 'block';
    } else {
        mainInterface.classList.remove('hidden');
        minimizedDisc.style.display = 'none';
    }
    
    // 设置币种选择
    const currencyRadios = document.querySelectorAll('input[name="currency"]');
    currencyRadios.forEach(radio => {
        radio.checked = radio.value === userAction.currency;
    });
    
    // 设置汇率
    const exchangeRateInput = document.getElementById('exchangeRate');
    exchangeRateInput.value = userAction.rate;

    // 恢复上次选择的类目
    const lastCategory = localStorage.getItem('lastSelectedCategory');
    if (lastCategory) {
        const categoryInput = document.getElementById('categoryInput');
        if (categoryInput) {
            categoryInput.value = lastCategory;
            categoryInput.title = lastCategory;
        }
    }
}

// 绑定事件
function bindEvents() {
    // 缩小按钮
    const minimizeBtn = document.getElementById('minimizeBtn');
    minimizeBtn.addEventListener('click', handleMinimize);
    
    // 爱心按钮
    const heartBtn = document.getElementById('heartBtn');
    heartBtn.addEventListener('click', () => loadAndShowModal(window.FactoryConfig.MODAL_TYPES.ABOUT));
    
    // 添加爱心按钮悬浮事件 - 悬浮时切换图标
    heartBtn.addEventListener('mouseenter', function() {
        const heartIcon = this.querySelector('.header-icon');
        if (heartIcon) {
            heartIcon.src = chrome.runtime.getURL('icons/font/AliExpress_aixin.png');
        }
    });
    
    heartBtn.addEventListener('mouseleave', function() {
        const heartIcon = this.querySelector('.header-icon');
        if (heartIcon) {
            heartIcon.src = chrome.runtime.getURL('icons/font/AliExpress_aixin_1.png');
        }
    });
    
    // 圆盘点击事件
    const minimizedDisc = document.getElementById('minimizedDisc');
    minimizedDisc.addEventListener('click', handleDiscClick);
    
    // 币种切换
    const currencyRadios = document.querySelectorAll('input[name="currency"]');
    currencyRadios.forEach(radio => {
        radio.addEventListener('change', handleCurrencyChange);
    });
    
    // 汇率输入
    const exchangeRateInput = document.getElementById('exchangeRate');
    exchangeRateInput.addEventListener('input', handleRateChange);
    
    // 类目选择输入框点击事件 - 使用工厂模式打开弹窗
    const categoryInput = document.getElementById('categoryInput');
    if (categoryInput) {
        categoryInput.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止冒泡，防止触发外部点击关闭
            loadAndShowModal(window.FactoryConfig.MODAL_TYPES.CATEGORY);
            if (window.categoryModal) {
                window.categoryModal.show();
            }
        });
    }

    // 自动填充类目按钮
    const autoFillBtn = document.getElementById('autoFillCategoryBtn');
    if (autoFillBtn) {
        autoFillBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止冒泡，防止触发页面其他组件的关闭逻辑
            handleAutoFillCategory();
        });
    }

    // 表尾按钮
    document.getElementById('skuPricingBtn').addEventListener('click', () => loadAndShowModal(window.FactoryConfig.MODAL_TYPES.SKU));
    document.getElementById('regionPricingBtn').addEventListener('click', () => loadAndShowModal(window.FactoryConfig.MODAL_TYPES.REGION));
    document.getElementById('aboutBtn').addEventListener('click', () => loadAndShowModal(window.FactoryConfig.MODAL_TYPES.ABOUT));

    // 使主界面可拖动
    const mainInterface = document.getElementById('mainInterface');
    const mainHeader = document.getElementById('mainHeader');
    if (mainInterface && mainHeader) {
        makeDraggable(mainInterface, mainHeader);
        // 设置鼠标样式提示可拖动
        mainHeader.style.cursor = 'move';
    }

    // 使悬浮圆盘可拖动
    if (minimizedDisc) {
        makeDraggable(minimizedDisc);
    }
}

/**
 * 使元素可拖动
 * @param {HTMLElement} element - 要拖动的元素
 * @param {HTMLElement} handle - 拖动的手柄（可选，默认为元素本身）
 */
function makeDraggable(element, handle) {
    let isDragging = false;
    let startX, startY, initialLeft, initialTop;
    const dragHandle = handle || element;

    dragHandle.addEventListener('mousedown', dragStart);

    function dragStart(e) {
        // 忽略输入框和按钮上的点击
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('.header-btn')) {
            return;
        }
        
        // 如果是右键点击，忽略
        if (e.button !== 0) return;

        e.preventDefault();
        
        const rect = element.getBoundingClientRect();
        initialLeft = rect.left;
        initialTop = rect.top;
        startX = e.clientX;
        startY = e.clientY;
        
        isDragging = false;

        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', dragEnd);
    }

    function drag(e) {
        if (!isDragging && (Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5)) {
            isDragging = true;
            
            // 切换为绝对定位/固定定位，并清除可能影响定位的属性
            element.style.position = 'fixed';
            element.style.transform = 'none';
            element.style.bottom = 'auto';
            element.style.right = 'auto';
            element.style.margin = '0';
        }

        if (isDragging) {
            const dx = e.clientX - startX;
            const dy = e.clientY - startY;
            
            element.style.left = `${initialLeft + dx}px`;
            element.style.top = `${initialTop + dy}px`;
        }
    }

    function dragEnd(e) {
        document.removeEventListener('mousemove', drag);
        document.removeEventListener('mouseup', dragEnd);
        
        if (isDragging) {
            // 标记为已拖动，用于阻止点击事件
            element.dataset.wasDragged = 'true';
            // 稍微延迟清除标记，确保点击事件处理器能读取到
            setTimeout(() => {
                 delete element.dataset.wasDragged;
            }, 100);
        }
    }
}

// 处理缩小
function handleMinimize() {
    const mainInterface = document.getElementById('mainInterface');
    const minimizedDisc = document.getElementById('minimizedDisc');
    
    mainInterface.classList.add('hidden');
    minimizedDisc.style.display = 'block';
    
    userAction.showType = 0;
    saveUserSettings();
}

// 处理圆盘点击（单击显示表单，双击打开关于我）
function handleDiscClick(event) {
    // 如果是拖动操作，则不处理点击
    const minimizedDisc = document.getElementById('minimizedDisc');
    if (minimizedDisc && minimizedDisc.dataset.wasDragged === 'true') {
        return;
    }

    const currentTime = new Date().getTime();
    
    if (currentTime - lastClickTime < DOUBLE_CLICK_DELAY) {
        // 双击
        clickCount = 0;
        loadAndShowModal(window.FactoryConfig.MODAL_TYPES.ABOUT);
    } else {
        // 单击
        setTimeout(() => {
            if (clickCount === 1) {
                const mainInterface = document.getElementById('mainInterface');
                const minimizedDisc = document.getElementById('minimizedDisc');
                
                mainInterface.classList.remove('hidden');
                minimizedDisc.style.display = 'none';
                
                userAction.showType = 1;
                saveUserSettings();
            }
            clickCount = 0;
        }, DOUBLE_CLICK_DELAY);
        
        clickCount++;
    }
    
    lastClickTime = currentTime;
}

// 处理币种变化
function handleCurrencyChange(event) {
    userAction.currency = event.target.value;
    
    if (userAction.currency === 'CNY') {
        userAction.rate = 1;
        document.getElementById('exchangeRate').value = 1;
    } else if (userAction.currency === 'USD') {
        // 从定价工具获取汇率
        getExchangeRateFromPricingTool();
    }
    
    saveUserSettings();
}

// 处理汇率变化
function handleRateChange(event) {
    userAction.rate = parseFloat(event.target.value) || 1;
    saveUserSettings();
}

// 从定价工具获取汇率
// async function getExchangeRateFromPricingTool() {
//     try {
//         if (window.PricingStorage) {
//             const pricingData = await window.PricingStorage.getPricingData();
//             if (pricingData && pricingData.exchangeRate) {
//                 userAction.rate = pricingData.exchangeRate;
//                 document.getElementById('exchangeRate').value = userAction.rate;
//                 saveUserSettings();
//             }
//         }
//     } catch (error) {
//         console.error('获取汇率失败:', error);
//         userAction.rate = 7; // 默认值
//         document.getElementById('exchangeRate').value = userAction.rate;
//         saveUserSettings();
//     }
// }

// 修改初始化汇率函数，使用storage.js中的汇率数据
async function initializeExchangeRate() {
    try {
        // 从PricingStorage获取已有的汇率数据
        const pricingData = await window.PricingStorage.getPricingData();
        const currentRate = pricingData.exchangeRate || 7; // 默认7.25
        
        // 更新输入框placeholder
        const exchangeRateInput = document.getElementById('exchangeRate');
        if (exchangeRateInput) {
            exchangeRateInput.placeholder = `1美元 = ${currentRate}人民币`;
        }
        
        // 如果用户还没有设置汇率，使用storage中的汇率
        if (userAction.currency === 'USD' && userAction.rate === 1) {
            userAction.rate = currentRate;
            exchangeRateInput.value = currentRate;
            saveUserSettings();
        }
    } catch (error) {
        console.log('使用默认汇率');
        // 如果获取失败，使用默认汇率
        const exchangeRateInput = document.getElementById('exchangeRate');
        if (exchangeRateInput) {
            exchangeRateInput.placeholder = '1美元 = 7人民币';
        }
    }
}

// 同时更新从定价工具获取汇率的函数
async function getExchangeRateFromPricingTool() {
    try {
        if (window.PricingStorage) {
            const pricingData = await window.PricingStorage.getPricingData();
            if (pricingData && pricingData.exchangeRate) {
                userAction.rate = pricingData.exchangeRate;
                document.getElementById('exchangeRate').value = userAction.rate;
                
                // 更新placeholder显示当前汇率
                const exchangeRateInput = document.getElementById('exchangeRate');
                exchangeRateInput.placeholder = `1美元 = ${pricingData.exchangeRate}人民币`;
                
                saveUserSettings();
            }
        }
    } catch (error) {
        console.error('获取汇率失败:', error);
    }
}

// 处理自动填充类目
async function handleAutoFillCategory() {
    const categoryText = document.getElementById('categoryInput').value;
    if (!categoryText) {
        alert('请先输入类目字符串，例如：珠宝/流行饰品/耳饰/耳夹');
        return;
    }
    
    // 解析类目字符串
    // 使用特殊分隔符 ➤ 分割，如果未找到则尝试使用 / 或 \ (兼容旧格式，但可能存在歧义)
    let categories;
    if (categoryText.includes('➤')) {
        categories = categoryText.split('➤').map(s => s.trim()).filter(s => s);
    } else {
        categories = categoryText.split(/[\/\\]/).map(s => s.trim()).filter(s => s);
    }
    
    if (categories.length === 0) {
        alert('类目格式不正确');
        return;
    }
    
    console.log('开始自动填充类目:', categories);
    
    try {
        // 记录操作日志
        if (window.api && window.api.logOperation) {
            window.api.logOperation('填充类目');
        }

        await autoFillCategories(categories);
    } catch (error) {
        console.error('自动填充失败:', error);
        alert('自动填充失败: ' + error.message);
    }
}


// 自动填充类目逻辑
async function autoFillCategories(categories) {


    //1. 先选择为以下国家进行标题、商品图片、详情描述等内容的差异化设置
    let divCard = document.getElementById("country-card");
    let spanCheck = divCard.querySelectorAll("span.next-checkbox");
    spanCheck.forEach((item)=>{
        let checkedInput = item.querySelector("input");
        if(!checkedInput.checked){
            checkedInput.click();
        }
    });

    //点击
    document.querySelector("button.button-translate").click();

    new Promise((resolve)=>{setTimeout(resolve,200)});

    let divContainer = document.querySelectorAll("div.page-blanoon-container")[0];
    let buttonCopyImgs = divContainer.querySelectorAll("button.ae-image-national__copy");
    buttonCopyImgs.forEach((item)=>{item.click()});





    // 1. 点击类目输入框，激活选择器
    const span = document.querySelector("span.next-input-group");
    if (!span) throw new Error("未找到类目选择器入口 (span.next-input-group)");
    
    const searchInputTrigger = span.querySelector("input");
    if (!searchInputTrigger) throw new Error("未找到类目选择器输入框");
    
    searchInputTrigger.click();
    
    // 等待弹窗出现
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const divCascade = document.querySelector("div.cascade-wrap");
    if (!divCascade) throw new Error("未找到类目级联容器 (div.cascade-wrap)");
    
    // 2. 逐级选择
    for (let i = 0; i < categories.length; i++) {
        const categoryName = categories[i];
        console.log(`正在选择第 ${i + 1} 级类目: ${categoryName}`);
        
        // 等待当前级别的输入框出现
        await waitForInputs(divCascade, i + 1);
        
        const inputs = divCascade.querySelectorAll("input");
        if (inputs.length <= i) throw new Error(`未找到第 ${i + 1} 级类目输入框`);
        
        const currentInput = inputs[i];
        
        // 设置值
        window.reactUtils.setReactValue(currentInput, categoryName);
        
        // 等待列表加载
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 查找对应的列表容器
        const listFrames = divCascade.querySelectorAll("div.list-frame");
        if (listFrames.length <= i) throw new Error(`未找到第 ${i + 1} 级类目列表容器`);
        
        const currentListFrame = listFrames[i];
        
        // 在列表中查找匹配的项并点击
        const firstItem = currentListFrame.querySelector("li");
        if (!firstItem) throw new Error(`第 ${i + 1} 级类目 "${categoryName}" 未找到匹配项`);
        
        firstItem.click();
        
        // 等待下一级加载
        await new Promise(resolve => setTimeout(resolve, 500));
    }

    while (true) {

        if(!document.querySelector("button.next-btn-loading")){
            // 3. 点击确认
            const divFoot = document.querySelector("div.category-content-footer");
            if (divFoot) {
                const btnConfirm = divFoot.querySelector("button");
                if (btnConfirm) {
                    btnConfirm.click();
                    console.log("类目选择完成");
                } else {
                    console.warn("未找到确认按钮");
                }
            } else {
                console.warn("未找到底部操作栏 (div.category-content-footer)");
            }
            break;
        }
        await new Promise((resolve)=>{setTimeout(resolve,200)});
    }


}




// 辅助函数：等待指定数量的输入框出现
function waitForInputs(container, count) {
    return new Promise((resolve, reject) => {
        let checks = 0;
        const interval = setInterval(() => {
            const inputs = container.querySelectorAll("input");
            if (inputs.length >= count) {
                clearInterval(interval);
                resolve();
            }
            checks++;
            if (checks > 20) { // 10秒超时
                clearInterval(interval);
                reject(new Error(`等待第 ${count} 级输入框超时`));
            }
        }, 500);
    });
}

// 修改loadAndShowModal函数，使用枚举类型的工厂模式调用
async function loadAndShowModal(modalType) {

    console.log('加载弹窗类型:', modalType);
    // 检查工厂模式是否已加载
    if (!window.ModalFactory) {
        console.error('ModalFactory 未加载，请检查 manifest.json 配置顺序');
        return;
    }
    
    // 创建工厂实例并创建弹窗
    const modalFactory = new window.ModalFactory();
    await modalFactory.showModalByType(modalType);
}

// 初始化
// 修改初始化部分，先加载HTML再初始化
(function() {
    'use strict';
    
    // 先加载main-interface.html
    fetch(chrome.runtime.getURL('model/main-interface.html'))
        .then(response => response.text())
        .then(html => {
            // 将HTML内容添加到页面
            document.body.insertAdjacentHTML('beforeend', html);
            
            // HTML加载完成后，再进行初始化
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', initMainInterface);
            } else {
                initMainInterface();
            }
        })
        .catch(error => {
            console.error('加载main-interface.html失败:', error);
        });
})();