/* 现代化主题JavaScript增强 */

document.addEventListener('DOMContentLoaded', function() {
    // 强制重置鼠标指针样式
    forceCursorReset();
    
    // 初始化所有功能（保留UI动画，删除loading动画）
    initModernTheme();
    initScrollEffects();
    initAnimations();
    initSmoothScrolling();
    initHeaderEffects();
});

// 强制重置鼠标指针样式
function forceCursorReset() {
    // 立即重置
    resetAllCursors();
    
    // 监听DOM变化，实时重置
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                resetElementCursor(mutation.target);
            }
            if (mutation.type === 'childList') {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) { // Element node
                        resetElementCursor(node);
                        const children = node.querySelectorAll('*');
                        children.forEach(resetElementCursor);
                    }
                });
            }
        });
    });
    
    observer.observe(document.body, {
        attributes: true,
        childList: true,
        subtree: true,
        attributeFilter: ['style']
    });
    
    // 定期强制重置
    setInterval(resetAllCursors, 1000);
}

function resetElementCursor(element) {
    if (element && element.style) {
        const tagName = element.tagName.toLowerCase();
        if (['a', 'button', 'input', 'select', 'label'].includes(tagName) && 
            !element.disabled && 
            !element.classList.contains('disabled')) {
            element.style.cursor = 'pointer';
        } else if (['input', 'textarea'].includes(tagName) && 
                   ['text', 'email', 'password', 'search', 'url', 'tel', 'number'].includes(element.type)) {
            element.style.cursor = 'text';
        } else {
            element.style.cursor = 'auto';
        }
    }
}

function resetAllCursors() {
    // 重置所有元素
    const allElements = document.querySelectorAll('*');
    allElements.forEach(resetElementCursor);
    
    // 特别重置可能被JavaScript修改的元素
    const dynamicElements = document.querySelectorAll('.swiper-container, .swiper-wrapper, .swiper-slide, .fancybox-container');
    dynamicElements.forEach(function(element) {
        element.style.cursor = 'auto';
    });
}

// 初始化现代化主题
function initModernTheme() {
    // 添加渐变文字类到标题
    const titles = document.querySelectorAll('h1, h2, h3.widget-title, .archive-title');
    titles.forEach(title => {
        if (!title.querySelector('.gradient-text')) {
            title.innerHTML = `<span class="gradient-text">${title.innerHTML}</span>`;
        }
    });

    // 为链接添加悬浮效果
    const links = document.querySelectorAll('a:not(.btn):not(.nav-link)');
    links.forEach(link => {
        link.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-1px)';
        });
        
        link.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });

    // 为按钮添加点击效果（不是loading效果）
    const buttons = document.querySelectorAll('.btn, button, input[type="submit"]');
    buttons.forEach(button => {
        button.addEventListener('click', function(e) {
            // 创建涟漪效果
            const ripple = document.createElement('span');
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                left: ${x}px;
                top: ${y}px;
                background: rgba(255, 255, 255, 0.3);
                border-radius: 50%;
                transform: scale(0);
                animation: ripple 0.6s linear;
                pointer-events: none;
            `;
            
            this.style.position = 'relative';
            this.style.overflow = 'hidden';
            this.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
}

// 滚动效果
function initScrollEffects() {
    let lastScrollTop = 0;
    const header = document.querySelector('.header');
    
    window.addEventListener('scroll', function() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        // 导航栏滚动效果
        if (scrollTop > 50) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
        
        lastScrollTop = scrollTop;
    });
}

// 初始化动画样式（保留基础UI动画）
function initAnimations() {
    const style = document.createElement('style');
    style.textContent = `
        @keyframes ripple {
            to {
                transform: scale(4);
                opacity: 0;
            }
        }
        
        .floating-element {
            animation: float 6s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
        }
        
        .glow-effect {
            position: relative;
            overflow: hidden;
        }
        
        .glow-effect::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: conic-gradient(from 0deg, transparent, rgba(102, 126, 234, 0.3), transparent);
            animation: rotate 4s linear infinite;
            z-index: -1;
        }
        
        @keyframes rotate {
            100% { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);

    // 为特殊元素添加浮动效果
    const floatingElements = document.querySelectorAll('.logo, .rollbar a');
    floatingElements.forEach((element, index) => {
        element.style.animationDelay = `${index * 0.5}s`;
        element.classList.add('floating-element');
    });
}

// 移除粒子背景效果
function initParticleBackground() {
    // 空函数，移除粒子背景效果
}

// 平滑滚动
function initSmoothScrolling() {
    const links = document.querySelectorAll('a[href^="#"]');
    
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href').substring(1);
            const targetElement = document.getElementById(targetId);
            
            if (targetElement) {
                const offsetTop = targetElement.offsetTop - 80; // 考虑固定导航栏高度
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 导航栏效果增强
function initHeaderEffects() {
    const header = document.querySelector('.header');
    const logo = document.querySelector('.logo a');
    
    // Logo悬浮效果
    if (logo) {
        logo.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.05)';
        });
        
        logo.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    }
    
    // 导航菜单项悬浮效果
    const navItems = document.querySelectorAll('.nav-main > li > a');
    navItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        item.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
    
    // 搜索框焦点效果
    const searchInputs = document.querySelectorAll('.search-input');
    searchInputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.parentElement.style.transform = 'scale(1.02)';
        });
        
        input.addEventListener('blur', function() {
            this.parentElement.style.transform = 'scale(1)';
        });
    });
}

// 夜间模式切换增强
function enhanceNightMode() {
    const nightToggle = document.querySelector('.theme_night');
    
    if (nightToggle) {
        nightToggle.addEventListener('click', function() {
            document.body.style.transition = 'all 0.3s ease';
            
            setTimeout(() => {
                document.body.style.transition = '';
            }, 300);
        });
    }
}

// 加载完成后的初始化
window.addEventListener('load', function() {
    // 增强现有功能
    enhanceNightMode();
    
    // 为VIP按钮添加特殊效果
    const vipButtons = document.querySelectorAll('.nav-vip a, .vip-li a');
    vipButtons.forEach(button => {
        button.classList.add('glow-effect');
    });
});

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
} 