/**
 * 用户中心公告栏滚动模块
 * 支持上下滚动切换公告，自动轮播，手动控制，点击查看详情弹窗
 */

(function(window, document) {
    'use strict';

    var CONFIG = {
        itemHeight: 32,
        itemHeightMobile: 28,
        autoScrollInterval: 5000,
        animationDuration: 400
    };

    var state = {
        currentIndex: 0,
        totalCount: 0,
        autoScrollTimer: null,
        isPaused: false,
        isMobile: false,
        isModalOpen: false
    };

    var elements = {};

    function init() {
        elements.scrollContent = document.getElementById('announcementScroll');
        elements.scrollWrapper = document.getElementById('announcementWrapper');
        elements.prevBtn = document.getElementById('annPrev');
        elements.nextBtn = document.getElementById('annNext');
        elements.indicator = document.getElementById('annIndicator');
        elements.announcementBar = document.getElementById('announcementBar');

        elements.modalOverlay = document.getElementById('annModalOverlay');
        elements.modalTitle = document.getElementById('annModalTitle');
        elements.modalBadge = document.getElementById('annModalBadge');
        elements.modalContent = document.getElementById('annModalContent');
        elements.modalClose = document.getElementById('annModalClose');
        elements.modalOk = document.getElementById('annModalOk');

        if (!elements.scrollContent) {
            return;
        }

        var items = elements.scrollContent.querySelectorAll('.announcement-item');
        state.totalCount = items.length;

        if (state.totalCount <= 0) {
            return;
        }

        state.isMobile = window.innerWidth <= 768;

        updateDisplay();
        bindEvents();

        if (state.totalCount > 1) {
            startAutoScroll();
        }
    }

    function bindEvents() {
        if (elements.prevBtn) {
            elements.prevBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                pauseAutoScroll();
                goToPrev();
                resumeAutoScroll();
            });
        }

        if (elements.nextBtn) {
            elements.nextBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                pauseAutoScroll();
                goToNext();
                resumeAutoScroll();
            });
        }

        if (elements.announcementBar) {
            elements.announcementBar.addEventListener('mouseenter', function() {
                pauseAutoScroll();
            });

            elements.announcementBar.addEventListener('mouseleave', function() {
                if (!state.isModalOpen) {
                    resumeAutoScroll();
                }
            });
        }

        if (elements.scrollWrapper) {
            elements.scrollWrapper.addEventListener('click', function(e) {
                if (e.target.closest('.announcement-nav')) {
                    return;
                }
                openModal();
            });
        }

        if (elements.modalClose) {
            elements.modalClose.addEventListener('click', closeModal);
        }

        if (elements.modalOk) {
            elements.modalOk.addEventListener('click', closeModal);
        }

        if (elements.modalOverlay) {
            elements.modalOverlay.addEventListener('click', function(e) {
                if (e.target === elements.modalOverlay) {
                    closeModal();
                }
            });
        }

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && state.isModalOpen) {
                closeModal();
            }
        });

        window.addEventListener('resize', function() {
            state.isMobile = window.innerWidth <= 768;
            updateDisplay();
        });

        if (elements.scrollContent) {
            var touchStartY = 0;
            var touchEndY = 0;
            var touchStartTime = 0;

            elements.scrollContent.addEventListener('touchstart', function(e) {
                touchStartY = e.changedTouches[0].screenY;
                touchStartTime = Date.now();
                pauseAutoScroll();
            }, { passive: true });

            elements.scrollContent.addEventListener('touchend', function(e) {
                touchEndY = e.changedTouches[0].screenY;
                var touchDuration = Date.now() - touchStartTime;
                var diff = touchStartY - touchEndY;

                if (touchDuration < 200 && Math.abs(diff) < 10) {
                    openModal();
                } else {
                    handleSwipe(touchStartY, touchEndY);
                }
                resumeAutoScroll();
            }, { passive: true });
        }
    }

    function openModal() {
        if (!elements.modalOverlay) return;

        var items = elements.scrollContent.querySelectorAll('.announcement-item');
        var currentItem = items[state.currentIndex];

        if (!currentItem) return;

        var title = currentItem.getAttribute('data-title');
        var content = currentItem.getAttribute('data-content');
        var type = parseInt(currentItem.getAttribute('data-type')) || 1;

        if (elements.modalTitle) {
            elements.modalTitle.textContent = title || '公告';
        }

        if (elements.modalContent) {
            elements.modalContent.innerHTML = content || '';
        }

        if (elements.modalBadge) {
            var typeText = '';
            var typeClass = '';
            switch(type) {
                case 3:
                    typeText = '紧急公告';
                    typeClass = 'type-urgent';
                    break;
                case 2:
                    typeText = '重要公告';
                    typeClass = 'type-important';
                    break;
                default:
                    typeText = '普通公告';
                    typeClass = 'type-normal';
            }
            elements.modalBadge.textContent = typeText;
            elements.modalBadge.className = 'modal-type-badge ' + typeClass;
        }

        state.isModalOpen = true;
        pauseAutoScroll();
        elements.modalOverlay.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        if (!elements.modalOverlay) return;

        state.isModalOpen = false;
        elements.modalOverlay.classList.remove('active');
        document.body.style.overflow = '';
        resumeAutoScroll();
    }

    function handleSwipe(startY, endY) {
        var diff = startY - endY;
        var threshold = 30;

        if (Math.abs(diff) > threshold) {
            if (diff > 0) {
                goToNext();
            } else {
                goToPrev();
            }
        }
    }

    function goToPrev() {
        if (state.totalCount <= 1) return;

        state.currentIndex--;
        if (state.currentIndex < 0) {
            state.currentIndex = state.totalCount - 1;
        }
        updateDisplay();
    }

    function goToNext() {
        if (state.totalCount <= 1) return;

        state.currentIndex++;
        if (state.currentIndex >= state.totalCount) {
            state.currentIndex = 0;
        }
        updateDisplay();
    }

    function updateDisplay() {
        if (!elements.scrollContent) return;

        var itemHeight = state.isMobile ? CONFIG.itemHeightMobile : CONFIG.itemHeight;
        var offset = -state.currentIndex * itemHeight;

        elements.scrollContent.style.transform = 'translateY(' + offset + 'px)';

        if (elements.indicator) {
            elements.indicator.textContent = (state.currentIndex + 1) + '/' + state.totalCount;
        }

        if (elements.prevBtn) {
            elements.prevBtn.disabled = state.totalCount <= 1;
        }
        if (elements.nextBtn) {
            elements.nextBtn.disabled = state.totalCount <= 1;
        }
    }

    function startAutoScroll() {
        if (state.totalCount <= 1) return;

        stopAutoScroll();
        state.autoScrollTimer = setInterval(function() {
            if (!state.isPaused && !state.isModalOpen) {
                goToNext();
            }
        }, CONFIG.autoScrollInterval);
    }

    function stopAutoScroll() {
        if (state.autoScrollTimer) {
            clearInterval(state.autoScrollTimer);
            state.autoScrollTimer = null;
        }
    }

    function pauseAutoScroll() {
        state.isPaused = true;
    }

    function resumeAutoScroll() {
        state.isPaused = false;
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    window.UserAnnouncement = {
        goToPrev: goToPrev,
        goToNext: goToNext,
        openModal: openModal,
        closeModal: closeModal,
        getCurrentIndex: function() {
            return state.currentIndex;
        },
        getTotalCount: function() {
            return state.totalCount;
        }
    };

})(window, document);