// 图书浏览页面脚本
$(document).ready(function() {
    // 分类筛选下拉菜单
    $('.category-filter-toggle').click(function() {
        $(this).toggleClass('active');
        $('.category-filter-dropdown').toggleClass('show');
    });

    // 点击外部关闭下拉菜单
    $(document).click(function(e) {
        if (!$(e.target).closest('.category-filters').length) {
            $('.category-filter-dropdown').removeClass('show');
            $('.category-filter-toggle').removeClass('active');
        }
    });

    // 处理借阅图书
    let bookIdToBorrow = null;
    let bookTitleToBorrow = '';

    $('.borrow-book').click(function(e) {
        e.preventDefault();
        bookIdToBorrow = $(this).data('id');

        // 获取图书标题
        const bookCard = $(this).closest('.book-card');
        bookTitleToBorrow = bookCard.find('.book-title').text();

        $('#borrowBookTitle').text(bookTitleToBorrow);
        $('#borrowModal').modal('show');
    });

    $('#confirmBorrow').click(function() {
        if (!bookIdToBorrow) return;

        // 禁用按钮防止重复提交
        $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 处理中...');

        $.ajax({
            url: `/borrow/add/${bookIdToBorrow}`,
            type: 'POST',
            success: function(response) {
                $('#borrowModal').modal('hide');

                if (response.success) {
                    showNotification(response.message, 'success');

                    // 更新UI显示
                    const bookCard = $(`.book-card[data-id="${bookIdToBorrow}"]`);

                    // 更改可借状态
                    bookCard.find('.book-ribbon span').removeClass('available').addClass('unavailable').text('已借出');

                    // 更改借阅按钮
                    bookCard.find('.btn-borrow').replaceWith(`
                        <button class="btn-borrow disabled" disabled>
                            <i class="fas fa-check-circle"></i> 已借出
                        </button>
                    `);

                    // 创建借阅成功动画
                    const successOverlay = $('<div class="borrow-success-overlay"><i class="fas fa-check-circle"></i><span>借阅成功</span></div>');
                    bookCard.append(successOverlay);

                    setTimeout(() => {
                        successOverlay.fadeOut(500, function() {
                            $(this).remove();
                        });
                    }, 2000);
                } else {
                    showNotification(response.message, 'error');
                }

                // 恢复按钮状态
                $('#confirmBorrow').prop('disabled', false).html('确认借阅');
            },
            error: function() {
                $('#borrowModal').modal('hide');
                showNotification('借阅操作失败，请稍后重试', 'error');
                $('#confirmBorrow').prop('disabled', false).html('确认借阅');
            }
        });
    });

    // 清除模态框数据
    $('#borrowModal').on('hidden.bs.modal', function() {
        bookIdToBorrow = null;
        bookTitleToBorrow = '';
        $('#borrowBookTitle').text('');
    });

    // 动态添加动画CSS
    const animationCSS = `
        .borrow-success-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(102, 126, 234, 0.9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            border-radius: 10px;
            z-index: 10;
            animation: fadeIn 0.3s;
        }
        
        .borrow-success-overlay i {
            font-size: 40px;
            margin-bottom: 10px;
            animation: scaleIn 0.5s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes scaleIn {
            from { transform: scale(0); }
            to { transform: scale(1); }
        }
    `;

    $('<style>').text(animationCSS).appendTo('head');

    // 显示通知
    function showNotification(message, type) {
        // 移除可能存在的旧通知
        $('.notification-alert').remove();

        const alertClass = type === 'success' ? 'notification-success' : 'notification-error';
        const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

        const notification = `
            <div class="notification-alert ${alertClass}">
                <div class="notification-icon">
                    <i class="fas ${iconClass}"></i>
                </div>
                <div class="notification-message">${message}</div>
                <button class="notification-close">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;

        $('body').append(notification);

        // 显示通知
        setTimeout(() => {
            $('.notification-alert').addClass('show');
        }, 10);

        // 通知自动关闭
        setTimeout(() => {
            $('.notification-alert').removeClass('show');
            setTimeout(() => {
                $('.notification-alert').remove();
            }, 300);
        }, 4000);

        // 点击关闭按钮
        $('.notification-close').click(function() {
            $(this).closest('.notification-alert').removeClass('show');
            setTimeout(() => {
                $(this).closest('.notification-alert').remove();
            }, 300);
        });
    }

    // 添加通知样式
    const notificationCSS = `
        .notification-alert {
            position: fixed;
            top: 20px;
            right: 20px;
            min-width: 300px;
            max-width: 400px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            padding: 15px;
            transform: translateX(calc(100% + 20px));
            transition: transform 0.3s ease;
            z-index: 9999;
        }
        
        .notification-alert.show {
            transform: translateX(0);
        }
        
        .notification-success {
            border-left: 4px solid #4caf50;
        }
        
        .notification-error {
            border-left: 4px solid #f44336;
        }
        
        .notification-icon {
            margin-right: 15px;
            font-size: 24px;
        }
        
        .notification-success .notification-icon {
            color: #4caf50;
        }
        
        .notification-error .notification-icon {
            color: #f44336;
        }
        
        .notification-message {
            flex: 1;
            font-size: 0.95rem;
            color: #3c4858;
        }
        
        .notification-close {
            background: none;
            border: none;
            color: #a0aec0;
            cursor: pointer;
            padding: 5px;
            margin-left: 10px;
            font-size: 0.8rem;
        }
        
        .notification-close:hover {
            color: #4a5568;
        }
        
        @media (max-width: 576px) {
            .notification-alert {
                top: auto;
                bottom: 20px;
                left: 20px;
                right: 20px;
                min-width: auto;
                max-width: none;
                transform: translateY(calc(100% + 20px));
            }
            
            .notification-alert.show {
                transform: translateY(0);
            }
        }
    `;

    $('<style>').text(notificationCSS).appendTo('head');

    // 卡片淡入效果
    $('.book-card').each(function(index) {
        $(this).css('animation-delay', `${0.05 * index}s`);
    });

    // 鼠标悬停时添加卡片提示信息
    $('.book-card').each(function() {
        const title = $(this).find('.book-title').text();
        const author = $(this).find('.book-author').text();
        $(this).attr('title', `${title} - ${author}`);
    });

    // 懒加载图片处理（可选）
    if ('IntersectionObserver' in window) {
        const imgObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    observer.unobserve(img);
                }
            });
        });

        document.querySelectorAll('img.lazy').forEach(img => {
            imgObserver.observe(img);
        });
    } else {
        // 回退机制，直接加载所有图片
        document.querySelectorAll('img.lazy').forEach(img => {
            img.src = img.dataset.src;
        });
    }
});
