let currentPlatform = 'douyin';
let currentPage = 1;
const giftsPerPage = 32;
let currentFilteredGifts = null;
let allGiftData = {};
let platformList = [];
let captchaAnswer = '';

function initPage() {
    if (window._gd) allGiftData = window._gd;
    if (window._pl) {
        platformList = window._pl.map(p => ({ ...p, count: (allGiftData[p.key] || []).length }));
    }

    const params = new URLSearchParams(window.location.search);
    if (params.get('p') && platformList.some(p => p.key === params.get('p'))) {
        currentPlatform = params.get('p');
    }
    if (params.get('page')) {
        currentPage = parseInt(params.get('page')) || 1;
    }
    if (params.get('q')) {
        document.getElementById('giftSearchInput').value = params.get('q');
    }

    renderPlatformButtons();
    lucide.createIcons();

    if (localStorage.getItem('gift_verified') === '1') {
        showMainContent();
    } else {
        showLoginModal();
    }
}

function showLoginModal() {
    const modal = document.getElementById('loginModal');
    modal.style.display = 'flex';
    generateCaptcha();
    setTimeout(() => {
        const content = document.getElementById('loginModalContent');
        content.classList.remove('scale-95', 'opacity-0');
        content.classList.add('scale-100', 'opacity-100');
    }, 10);
    lucide.createIcons();
}

function closeLoginModal() {
    const content = document.getElementById('loginModalContent');
    content.classList.remove('scale-100', 'opacity-100');
    content.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        document.getElementById('loginModal').style.display = 'none';
    }, 300);
}

function generateCaptcha() {
    const canvas = document.getElementById('captchaCanvas');
    const ctx = canvas.getContext('2d');
    const w = canvas.width, h = canvas.height;
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    captchaAnswer = '';
    for (let i = 0; i < 4; i++) captchaAnswer += chars[Math.floor(Math.random() * chars.length)];

    ctx.fillStyle = 'rgba(30, 20, 50, 0.9)';
    ctx.fillRect(0, 0, w, h);

    for (let i = 0; i < 4; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * w, Math.random() * h);
        ctx.lineTo(Math.random() * w, Math.random() * h);
        ctx.strokeStyle = `rgba(${100 + Math.random()*155}, ${50 + Math.random()*100}, ${150 + Math.random()*105}, 0.4)`;
        ctx.stroke();
    }

    for (let i = 0; i < 30; i++) {
        ctx.fillStyle = `rgba(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255}, 0.5)`;
        ctx.fillRect(Math.random() * w, Math.random() * h, 2, 2);
    }

    const colors = ['#e0d0ff', '#f0c0ff', '#c0e0ff', '#ffe0c0'];
    for (let i = 0; i < 4; i++) {
        ctx.font = `bold ${22 + Math.random()*6}px monospace`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillStyle = colors[i];
        ctx.save();
        ctx.translate(30 + i * 30, h / 2 + (Math.random() - 0.5) * 10);
        ctx.rotate((Math.random() - 0.5) * 0.4);
        ctx.fillText(captchaAnswer[i], 0, 0);
        ctx.restore();
    }
}

function doLogin() {
    const cardKey = document.getElementById('modalCardKey').value.trim();
    const captcha = document.getElementById('modalCaptcha').value.trim();
    const btn = document.getElementById('modalLoginBtn');

    if (!cardKey) { showToast('请输入卡密'); return; }
    if (!captcha) { showToast('请输入验证码'); return; }

    btn.disabled = true;
    btn.innerHTML = '<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> 验证中...';
    lucide.createIcons();

    setTimeout(() => {
        const keyValid = cardKey.startsWith('TB_') && cardKey.length >= 20;
        const captchaValid = captcha.toLowerCase() === captchaAnswer.toLowerCase();

        if (keyValid && captchaValid) {
            localStorage.setItem('gift_verified', '1');
            showToast('验证成功');
            closeLoginModal();
            setTimeout(() => showMainContent(), 400);
        } else if (!captchaValid) {
            showToast('验证码错误');
            generateCaptcha();
            document.getElementById('modalCaptcha').value = '';
        } else {
            showToast('卡密错误');
            generateCaptcha();
            document.getElementById('modalCaptcha').value = '';
        }
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="log-in" class="w-5 h-5"></i> 立即验证';
        lucide.createIcons();
    }, 600);
}

function showPurchaseModal() {
    const modal = document.getElementById('purchaseModal');
    modal.style.display = 'flex';
    setTimeout(() => {
        const content = document.getElementById('purchaseModalContent');
        content.classList.remove('scale-95', 'opacity-0');
        content.classList.add('scale-100', 'opacity-100');
    }, 10);
    lucide.createIcons();
    generatePaymentQR();
}

function closePurchaseModal() {
    // 清除轮询
    if (pollingInterval) {
        clearInterval(pollingInterval);
        pollingInterval = null;
    }
    
    const content = document.getElementById('purchaseModalContent');
    content.classList.remove('scale-100', 'opacity-100');
    content.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        document.getElementById('purchaseModal').style.display = 'none';
    }, 300);
}

async function generatePaymentQR() {
    try {
        // 使用相对路径访问API
        console.log('开始生成二维码...');
        const response = await fetch('/api/generate-qr', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ amount: 9.9 })
        });
        console.log('API响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('API响应数据:', data);
        if (data.success) {
            document.getElementById('qrcodeContainer').innerHTML = `<img src="${data.qrCode}" alt="支付宝收款码" class="w-48 h-48">`;
            document.getElementById('orderInfo').textContent = `订单号：${data.orderId}`;
            // 开始轮询订单状态
            startPolling(data.orderId);
        } else {
            showToast('生成二维码失败');
        }
    } catch (error) {
        console.error('生成二维码错误:', error);
        showToast('网络错误，请稍后重试');
    }
}

let pollingInterval = null;

function startPolling(orderId) {
    // 清除之前的轮询
    if (pollingInterval) {
        clearInterval(pollingInterval);
    }
    
    // 每3秒查询一次订单状态
    pollingInterval = setInterval(async () => {
        try {
            const response = await fetch('/api/query-key', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ orderId })
            });
            const data = await response.json();
            if (data.success) {
                // 支付成功，显示卡密
                clearInterval(pollingInterval);
                showToast(`支付成功！卡密：${data.cardKey}`);
                document.getElementById('modalCardKey').value = data.cardKey;
                closePurchaseModal();
            }
        } catch (error) {
            console.log('轮询失败:', error);
        }
    }, 3000);
}

async function queryCardKey() {
    const orderId = document.getElementById('orderQueryInput').value.trim();
    if (!orderId) {
        showToast('请输入订单号');
        return;
    }
    try {
        // 使用相对路径访问API
        const response = await fetch('/api/query-key', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ orderId })
        });
        const data = await response.json();
        if (data.success) {
            showToast(`卡密：${data.cardKey}`);
            document.getElementById('modalCardKey').value = data.cardKey;
            closePurchaseModal();
        } else {
            showToast('未找到卡密，请确认订单号或等待支付完成');
        }
    } catch (error) {
        showToast('网络错误，请稍后重试');
    }
}

function showToast(msg) {
    let toast = document.getElementById('toastMsg');
    if (!toast) {
        toast = document.createElement('div');
        toast.id = 'toastMsg';
        toast.className = 'fixed top-20 left-1/2 -translate-x-1/2 z-[200] px-6 py-3 rounded-xl bg-black/80 backdrop-blur-sm text-white text-sm border border-white/10 transition-all duration-300';
        document.body.appendChild(toast);
    }
    toast.textContent = msg;
    toast.style.opacity = '1';
    toast.style.transform = 'translateX(-50%) translateY(0)';
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(-50%) translateY(-10px)';
    }, 2000);
}

function showMainContent() {
    document.getElementById('mainContent').style.display = 'block';
    document.getElementById('batchDownloadWrap').style.display = 'block';
    renderGifts();
    lucide.createIcons();
    window.addEventListener('scroll', handleNavbarScroll);
}

function handleNavbarScroll() {
    const navbar = document.getElementById('navbar');
    if (window.scrollY > 50) {
        navbar.classList.add('bg-opacity-90', 'shadow-lg');
    } else {
        navbar.classList.remove('bg-opacity-90', 'shadow-lg');
    }
}

function renderPlatformButtons() {
    const container = document.getElementById('platformButtons');
    if (!container || typeof platformList === 'undefined') return;

    container.innerHTML = platformList.map(p => `
        <button onclick="switchPlatform('${p.key}')"
            class="platform-btn px-5 py-2 rounded-full text-sm font-medium transition-all ${p.key === currentPlatform ? 'platform-btn-active' : ''}"
            data-platform="${p.key}">
            ${p.name}
        </button>
    `).join('');

    updatePlatformInfo();
}

function updateURL() {
    const params = new URLSearchParams();
    params.set('p', currentPlatform);
    if (currentPage > 1) params.set('page', currentPage);
    const q = document.getElementById('giftSearchInput').value.trim();
    if (q) params.set('q', q);
    const newURL = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
    history.replaceState(null, '', newURL);
}

function switchPlatform(platformKey) {
    if (platformKey === currentPlatform) return;
    currentPlatform = platformKey;
    currentPage = 1;
    currentFilteredGifts = null;

    document.getElementById('giftSearchInput').value = '';

    document.querySelectorAll('.platform-btn').forEach(btn => {
        btn.classList.toggle('platform-btn-active', btn.dataset.platform === platformKey);
    });

    updatePlatformInfo();
    renderGifts();
    updateURL();
}

function updatePlatformInfo() {
    const info = document.getElementById('currentPlatformInfo');
    const platform = platformList.find(p => p.key === currentPlatform);
    if (info && platform) {
        info.textContent = `当前平台：${platform.name} | 共 ${platform.count} 个礼物`;
    }
}

function getCurrentGifts() {
    if (currentFilteredGifts) return currentFilteredGifts;
    return allGiftData[currentPlatform] || [];
}

function renderGifts() {
    const giftContainer = document.getElementById('giftContainer');
    const gifts = getCurrentGifts();

    if (!gifts || gifts.length === 0) {
        giftContainer.innerHTML = '<div class="text-center col-span-full py-12 text-gray-500">暂无礼物数据</div>';
        removePagination();
        return;
    }

    giftContainer.innerHTML = '<div class="col-span-full flex justify-center py-16"><div class="w-10 h-10 border-4 border-purple-500/30 border-t-purple-500 rounded-full animate-spin"></div></div>';

    setTimeout(() => {
        renderGiftsContent(giftContainer, gifts);
    }, 150);
}

function renderGiftsContent(giftContainer, gifts) {

    const totalGifts = gifts.length;
    const totalPages = Math.ceil(totalGifts / giftsPerPage);

    if (currentPage > totalPages) currentPage = totalPages;
    if (currentPage < 1) currentPage = 1;

    const startIndex = (currentPage - 1) * giftsPerPage;
    const endIndex = Math.min(startIndex + giftsPerPage, totalGifts);
    const pageGifts = gifts.slice(startIndex, endIndex);

    giftContainer.innerHTML = pageGifts.map(gift => `
        <div class="gift-item glass-card rounded-xl p-3 flex flex-col items-center group cursor-pointer" onclick="downloadGift('${gift.image}', '${gift.name}')">
            <div class="gift-icon-wrap aspect-square rounded-xl bg-gradient-to-br from-purple-900/30 to-pink-900/30 flex items-center justify-center mb-2 relative overflow-hidden w-full">
                <img src="${gift.image}" alt="${gift.name}" class="w-14 h-14 object-contain transition-transform duration-300 group-hover:scale-110" loading="lazy"
                    onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 64 64%22><rect fill=%22%23333%22 width=%2264%22 height=%2264%22 rx=%228%22/><text x=%2232%22 y=%2236%22 text-anchor=%22middle%22 fill=%22%23999%22 font-size=%2212%22>暂无图</text></svg>'">
                <button onclick="event.stopPropagation(); downloadGift('${gift.image}', '${gift.name}')"
                    class="absolute bottom-1 right-1 w-7 h-7 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center opacity-0 group-hover:opacity-100 hover:bg-white/40 transition-all z-10">
                    <i data-lucide="download" class="w-3.5 h-3.5 text-white pointer-events-none"></i>
                </button>
            </div>
            <h3 class="text-xs font-medium text-center mb-1 truncate w-full">${gift.name}</h3>
            <span class="text-yellow-400 text-xs">ID:${gift.id}</span>
        </div>
    `).join('');

    addPaginationControls(totalGifts);
    lucide.createIcons();
    updateURL();
}

function searchGifts() {
    const searchInput = document.getElementById('giftSearchInput');
    const searchTerm = searchInput.value.trim().toLowerCase();

    if (!searchTerm) {
        currentFilteredGifts = null;
        currentPage = 1;
        renderGifts();
        return;
    }

    const allGifts = allGiftData[currentPlatform] || [];
    currentFilteredGifts = allGifts.filter(gift =>
        gift.name.toLowerCase().includes(searchTerm) ||
        gift.id.includes(searchTerm)
    );
    currentPage = 1;
    renderGifts();
}

function addPaginationControls(totalGifts) {
    const giftContainer = document.getElementById('giftContainer');
    const totalPages = Math.ceil(totalGifts / giftsPerPage);

    removePagination();

    if (totalPages <= 1) {
        if (totalGifts > 0) {
            const info = document.createElement('div');
            info.id = 'paginationContainer';
            info.className = 'flex justify-center items-center mt-8';
            info.innerHTML = `<span class="text-sm text-gray-500">共 ${totalGifts} 个礼物</span>`;
            giftContainer.parentNode.appendChild(info);
        }
        return;
    }

    let paginationContainer = document.createElement('div');
    paginationContainer.id = 'paginationContainer';
    paginationContainer.className = 'flex flex-wrap justify-center items-center mt-8 space-x-2';

    const prevButton = document.createElement('button');
    prevButton.className = `pagination-btn px-4 py-2 rounded-full ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
    prevButton.innerHTML = '<i data-lucide="chevron-left"></i>';
    prevButton.onclick = () => { if (currentPage > 1) { currentPage--; renderGifts(); } };
    paginationContainer.appendChild(prevButton);

    const pageNumbers = [];
    const maxVisiblePages = 7;
    const halfVisible = Math.floor(maxVisiblePages / 2);

    let startPage = Math.max(1, currentPage - halfVisible);
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    if (startPage > 1) {
        pageNumbers.push(1);
        if (startPage > 2) pageNumbers.push('...');
    }

    for (let i = startPage; i <= endPage; i++) {
        pageNumbers.push(i);
    }

    if (endPage < totalPages) {
        if (endPage < totalPages - 1) pageNumbers.push('...');
        pageNumbers.push(totalPages);
    }

    pageNumbers.forEach(page => {
        if (page === '...') {
            const ellipsis = document.createElement('span');
            ellipsis.className = 'px-3 py-2 text-gray-500';
            ellipsis.textContent = '...';
            paginationContainer.appendChild(ellipsis);
        } else {
            const pageButton = document.createElement('button');
            pageButton.className = `pagination-btn px-4 py-2 rounded-full ${currentPage === page ? 'active' : ''}`;
            pageButton.textContent = page;
            pageButton.onclick = () => { currentPage = page; renderGifts(); };
            paginationContainer.appendChild(pageButton);
        }
    });

    const nextButton = document.createElement('button');
    nextButton.className = `pagination-btn px-4 py-2 rounded-full ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
    nextButton.innerHTML = '<i data-lucide="chevron-right"></i>';
    nextButton.onclick = () => { if (currentPage < totalPages) { currentPage++; renderGifts(); } };
    paginationContainer.appendChild(nextButton);

    const pageInfo = document.createElement('span');
    pageInfo.className = 'ml-4 text-sm text-gray-500';
    pageInfo.textContent = `第 ${currentPage}/${totalPages} 页，共 ${totalGifts} 个礼物`;
    paginationContainer.appendChild(pageInfo);

    giftContainer.parentNode.appendChild(paginationContainer);
    lucide.createIcons();
}

function removePagination() {
    const existing = document.getElementById('paginationContainer');
    if (existing) existing.remove();
}

function downloadGift(imageUrl, giftName) {
    fetch(imageUrl, { mode: 'cors', referrerPolicy: 'no-referrer' })
        .then(response => response.blob())
        .then(blob => {
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `${giftName}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        })
        .catch(() => {
            const link = document.createElement('a');
            link.href = imageUrl;
            link.download = `${giftName}.png`;
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
}

async function batchDownload() {
    const gifts = getCurrentGifts();
    if (!gifts || gifts.length === 0) { showToast('暂无礼物可下载'); return; }

    const start = (currentPage - 1) * giftsPerPage;
    const end = Math.min(start + giftsPerPage, gifts.length);
    const pageGifts = gifts.slice(start, end);

    if (window.showDirectoryPicker) {
        let dirHandle = null;
        try {
            dirHandle = await window.showDirectoryPicker({ mode: 'readwrite' });
        } catch (e) {
            return;
        }

        const platform = platformList.find(p => p.key === currentPlatform);
        const folderName = platform ? platform.name : currentPlatform;
        let subDir;
        try {
            subDir = await dirHandle.getDirectoryHandle(folderName, { create: true });
        } catch (e) {
            subDir = dirHandle;
        }

        showToast(`正在下载 ${pageGifts.length} 个礼物...`);

        let success = 0;
        for (let i = 0; i < pageGifts.length; i++) {
            const gift = pageGifts[i];
            try {
                const response = await fetch(gift.image, { mode: 'cors', referrerPolicy: 'no-referrer' });
                const blob = await response.blob();
                const fileName = `${gift.name}.png`;
                const fileHandle = await subDir.getFileHandle(fileName, { create: true });
                const writable = await fileHandle.createWritable();
                await writable.write(blob);
                await writable.close();
                success++;
            } catch (e) {
                console.warn('下载失败:', gift.name);
            }
        }

        showToast(`下载完成，成功 ${success}/${pageGifts.length} 个`);
    } else {
        showToast(`正在下载 ${pageGifts.length} 个礼物...`);
        let success = 0;
        for (let i = 0; i < pageGifts.length; i++) {
            const gift = pageGifts[i];
            try {
                const response = await fetch(gift.image, { mode: 'cors', referrerPolicy: 'no-referrer' });
                const blob = await response.blob();
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = `${gift.name}.png`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
                success++;
            } catch (e) {
                console.warn('下载失败:', gift.name);
            }
            await new Promise(r => setTimeout(r, 300));
        }
        showToast(`下载完成，成功 ${success}/${pageGifts.length} 个`);
    }
}

window.onload = initPage;

document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter' && document.getElementById('loginModal').style.display === 'flex') {
        doLogin();
    }
    if (e.key === 'Escape') {
        if (document.getElementById('loginModal').style.display === 'flex') {
            closeLoginModal();
        }
    }
    if (e.key === '/' && !e.ctrlKey && !e.metaKey) {
        const active = document.activeElement;
        if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA')) return;
        e.preventDefault();
        document.getElementById('giftSearchInput').focus();
    }
});