$(document).ready(function() {
    // 主题切换功能
    const themeToggle = $('#themeToggle');
    const body = $('body');
    const icon = themeToggle.find('i');
    
    // 检查本地存储中的主题设置
    const currentTheme = localStorage.getItem('theme') || 'light';
    body.addClass(`theme-${currentTheme}`);
    updateThemeIcon(currentTheme);
    
    // 主题切换事件
    themeToggle.on('click', function() {
        const isLight = body.hasClass('theme-light');
        const newTheme = isLight ? 'dark' : 'light';
        
        body.removeClass('theme-light theme-dark')
            .addClass(`theme-${newTheme}`);
        
        localStorage.setItem('theme', newTheme);
        updateThemeIcon(newTheme);
    });
    
    // 更新主题图标
    function updateThemeIcon(theme) {
        icon.removeClass('fa-sun fa-moon')
            .addClass(theme === 'light' ? 'fa-moon' : 'fa-sun');
    }
    
    // 链接点击统计
    $('.site-card').on('click', function() {
        const linkId = $(this).data('link-id');
        // 异步记录点击次数
        $.post('includes/click_counter.php', { id: linkId });
    });
    
    // 添加滚动动画
    $(window).scroll(function() {
        $('.category-section').each(function() {
            const elementTop = $(this).offset().top;
            const elementBottom = elementTop + $(this).outerHeight();
            const viewportTop = $(window).scrollTop();
            const viewportBottom = viewportTop + $(window).height();
            
            if (elementBottom > viewportTop && elementTop < viewportBottom) {
                $(this).addClass('animate__fadeInUp');
            }
        });
    });
    
    // 初始化工具提示
    $('[data-bs-toggle="tooltip"]').tooltip();
    
    // 平滑滚动
    $('a[href^="#"]').on('click', function(e) {
        e.preventDefault();
        const target = $(this.hash);
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top - 70
            }, 500);
        }
    });
});
