document.addEventListener('DOMContentLoaded', function() {

    // ==========================================
    //  1. 轮播图
    // ==========================================
    const slides = document.querySelectorAll('.hero-banner .slide');
    const prevBtn = document.getElementById('sliderPrev');
    const nextBtn = document.getElementById('sliderNext');
    const dots = document.querySelectorAll('.slider-dots .dot');
    let currentSlide = 0;
    let slideInterval;

    function showSlide(index) {
        if (slides.length === 0) return;
        slides.forEach(s => s.classList.remove('active'));
        dots.forEach(d => d.classList.remove('active'));
        slides[index].classList.add('active');
        dots[index].classList.add('active');
    }

    function nextSlide() {
        if (slides.length === 0) return;
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide(currentSlide);
    }

    function prevSlide() {
        if (slides.length === 0) return;
        currentSlide = (currentSlide - 1 + slides.length) % slides.length;
        showSlide(currentSlide);
    }

    function startInterval() {
        if (slides.length > 0) {
            slideInterval = setInterval(nextSlide, 4000);
        }
    }

    function resetInterval() {
        clearInterval(slideInterval);
        startInterval();
    }

    if (prevBtn) {
        prevBtn.addEventListener('click', function() {
            prevSlide();
            resetInterval();
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', function() {
            nextSlide();
            resetInterval();
        });
    }

    dots.forEach(function(dot) {
        dot.addEventListener('click', function() {
            currentSlide = parseInt(dot.dataset.slide);
            showSlide(currentSlide);
            resetInterval();
        });
    });

    startInterval();

    // ==========================================
    //  2. 倒计时
    // ==========================================
    const daysEl = document.getElementById('countdownDays');
    const hoursEl = document.getElementById('countdownHours');
    const minutesEl = document.getElementById('countdownMinutes');
    const secondsEl = document.getElementById('countdownSeconds');
    const editBtn = document.getElementById('editDateBtn');
    const datePickerWrapper = document.getElementById('datePickerWrapper');
    const saveBtn = document.getElementById('saveDateBtn');
    const weddingDateInput = document.getElementById('weddingDateInput');
    const presetBtns = document.querySelectorAll('.preset-date');

    let weddingDate = localStorage.getItem('weddingDate') || '2025-10-01';
    if (weddingDateInput) weddingDateInput.value = weddingDate;

    function updateCountdown() {
        if (!daysEl) return;
        const target = new Date(weddingDate + 'T00:00:00');
        const now = new Date();
        const diff = target - now;

        if (diff <= 0) {
            daysEl.textContent = '0';
            hoursEl.textContent = '0';
            minutesEl.textContent = '0';
            secondsEl.textContent = '0';
            return;
        }

        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (86400000)) / (3600000));
        const minutes = Math.floor((diff % 3600000) / 60000);
        const seconds = Math.floor((diff % 60000) / 1000);

        daysEl.textContent = days;
        hoursEl.textContent = hours.toString().padStart(2, '0');
        minutesEl.textContent = minutes.toString().padStart(2, '0');
        secondsEl.textContent = seconds.toString().padStart(2, '0');
    }

    if (daysEl) {
        updateCountdown();
        setInterval(updateCountdown, 1000);
    }

    if (editBtn && datePickerWrapper) {
        editBtn.addEventListener('click', function() {
            datePickerWrapper.style.display = 'block';
        });
    }

    if (saveBtn && datePickerWrapper) {
        saveBtn.addEventListener('click', function() {
            weddingDate = weddingDateInput.value;
            localStorage.setItem('weddingDate', weddingDate);
            updateCountdown();
            datePickerWrapper.style.display = 'none';
        });
    }

    presetBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const date = btn.dataset.date;
            weddingDateInput.value = date;
            weddingDate = date;
            localStorage.setItem('weddingDate', date);
            updateCountdown();
            if (datePickerWrapper) datePickerWrapper.style.display = 'none';
        });
    });

    // ==========================================
    //  3. 备婚清单 Tab 切换 + 进度
    // ==========================================
    const tabBtns = document.querySelectorAll('.checklist-tabs .tab-btn');
    const checklistItemsContainer = document.getElementById('checklistItems');
    const progressFill = document.querySelector('.progress-fill');
    const progressPercent = document.getElementById('progressPercent');

    const checklistData = {
        'half-year': [
            { text: '确定婚期和预算', priority: 'urgent' },
            { text: '预订酒店/场地', priority: 'important' },
            { text: '确定宾客名单', priority: '' },
            { text: '选定婚庆公司', priority: '' },
            { text: '拍摄婚纱照', priority: 'important' }
        ],
        'three-months': [
            { text: '试菜确定菜单', priority: '' },
            { text: '确定伴郎伴娘', priority: '' },
            { text: '购买婚戒', priority: 'important' },
            { text: '发送请柬', priority: 'urgent' }
        ],
        'one-month': [
            { text: '最终确认宾客人数', priority: 'urgent' },
            { text: '安排婚车', priority: '' },
            { text: '购买婚礼用品', priority: '' },
            { text: '与司仪沟通流程', priority: 'important' }
        ],
        'one-week': [
            { text: '取婚纱礼服', priority: 'important' },
            { text: '确认所有供应商', priority: 'urgent' },
            { text: '准备发言稿', priority: '' },
            { text: '放松心情，做个美容', priority: '' }
        ]
    };

    function loadChecklist(period) {
        if (!checklistItemsContainer) return;
        const tasks = checklistData[period] || [];
        let html = '';
        tasks.forEach(function(task, index) {
            const priorityClass = task.priority ? 'task-priority ' : '';
            const priorityText = task.priority === 'urgent' ? '紧急' : (task.priority === 'important' ? '重要' : '');
            html += '<li class="checklist-item">' +
                '<input type="checkbox" id="task_' + period + '_' + index + '" class="task-check">' +
                '<label for="task_' + period + '_' + index + '">' + task.text + '</label>' +
                (task.priority ? '<span class="' + priorityClass + task.priority + '">' + priorityText + '</span>' : '') +
                '</li>';
        });
        checklistItemsContainer.innerHTML = html;
        updateChecklistProgress();
    }

    function updateChecklistProgress() {
        if (!checklistItemsContainer || !progressFill || !progressPercent) return;
        const checks = checklistItemsContainer.querySelectorAll('.task-check');
        const total = checks.length;
        const checked = Array.from(checks).filter(function(c) { return c.checked; }).length;
        const percent = total ? Math.round((checked / total) * 100) : 0;
        progressFill.style.width = percent + '%';
        progressPercent.textContent = percent + '%';
    }

    if (tabBtns.length > 0) {
        const defaultTab = document.querySelector('.tab-btn.active');
        loadChecklist(defaultTab ? (defaultTab.dataset.period || 'half-year') : 'half-year');

        tabBtns.forEach(function(btn) {
            btn.addEventListener('click', function() {
                tabBtns.forEach(function(b) { b.classList.remove('active'); });
                btn.classList.add('active');
                loadChecklist(btn.dataset.period);
            });
        });

        if (checklistItemsContainer) {
            checklistItemsContainer.addEventListener('change', function(e) {
                if (e.target.classList.contains('task-check')) {
                    updateChecklistProgress();
                }
            });
        }
    }

    // ==========================================
    //  4. 智能顾问模拟回复
    // ==========================================
    const quickAskBtn = document.getElementById('quickAskBtn');
    const quickQuestion = document.getElementById('quickQuestion');
    const advisorPreview = document.getElementById('advisorPreview');

    if (quickAskBtn && quickQuestion && advisorPreview) {
        quickAskBtn.addEventListener('click', function() {
            const question = quickQuestion.value.trim();
            if (!question) {
                advisorPreview.innerHTML = '<span class="preview-text">请输入您的问题</span>';
                return;
            }
            let answer;
            const lowerQ = question.toLowerCase();
            if (lowerQ.includes('习俗') || lowerQ.includes('婚俗')) {
                answer = '阳泉本地讲究"过大礼""回门"等习俗，建议提前咨询本地婚庆管家。';
            } else if (lowerQ.includes('预算') || lowerQ.includes('费用')) {
                answer = '普通婚礼预算约5-10万，可参考我们的"预算与省钱"服务制定详细计划。';
            } else {
                answer = '感谢您的提问，我们的婚礼顾问会在24小时内与您联系。';
            }
            advisorPreview.innerHTML = '<span class="preview-text">建议：' + answer + '</span>';
            quickQuestion.value = '';
        });
    }

    // ==========================================
    //  5. 商家筛选功能
    // ==========================================
    const vendorFilterBtns = document.querySelectorAll('.vendor-filters .filter-btn');
    const vendorCards = document.querySelectorAll('.vendor-card');

    if (vendorFilterBtns.length > 0) {
        vendorFilterBtns.forEach(function(btn) {
            btn.addEventListener('click', function() {
                vendorFilterBtns.forEach(function(b) { b.classList.remove('active'); });
                btn.classList.add('active');

                const filter = btn.dataset.filter;
                vendorCards.forEach(function(card) {
                    if (filter === 'all' || card.dataset.type === filter) {
                        card.style.display = 'block';
                    } else {
                        card.style.display = 'none';
                    }
                });
            });
        });
    }

    // ==========================================
    //  6. 案例筛选功能
    // ==========================================
    const galleryFilterBtns = document.querySelectorAll('.gallery-filters .filter-btn');
    const galleryCards = document.querySelectorAll('.gallery-card');

    if (galleryFilterBtns.length > 0) {
        galleryFilterBtns.forEach(function(btn) {
            btn.addEventListener('click', function() {
                galleryFilterBtns.forEach(function(b) { b.classList.remove('active'); });
                btn.classList.add('active');

                const filter = btn.dataset.filter;
                galleryCards.forEach(function(card) {
                    if (filter === 'all' || card.dataset.type === filter) {
                        card.style.display = 'block';
                    } else {
                        card.style.display = 'none';
                    }
                });
            });
        });
    }

    // ==========================================
    //  7. 搜索功能
    // ==========================================
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');

    // 搜索范围：覆盖网站主要页面中的卡片、标题、内容块
    var SEARCH_SELECTORS = [
        '.service-card', '.service-detail-card', '.vendor-card',
        '.tool-card', '.additional-card', '.package-card',
        '.gallery-card', '.season-card', '.detail-card',
        '.card', '.info-card', '.feature-card', '.custom-card',
        '.section-title h2', '.section-title h3',
        '.page-banner h1', '.page-banner p',
        '.service-features li', '.additional-grid .additional-card',
        '.tradition-card', '.timeline-item',
        '.bazi-form-card', '.dating-card', '.invitation-card'
    ].join(', ');

    function searchNoticeEl() {
        return document.getElementById('searchNotice');
    }

    function removeSearchNotice() {
        var el = searchNoticeEl();
        if (el) el.remove();
    }

    function showSearchNotice(msg, isError) {
        removeSearchNotice();
        var notice = document.createElement('div');
        notice.id = 'searchNotice';
        notice.className = 'search-notice' + (isError ? ' search-notice--error' : '');
        notice.innerHTML = msg;
        // 放在面包屑下方或 site-main 顶部
        var target = document.querySelector('.site-main');
        if (target) {
            target.insertBefore(notice, target.firstChild);
        }
        // 5 秒后自动消失
        setTimeout(function() {
            if (searchNoticeEl() === notice) notice.remove();
        }, 5000);
    }

    function clearSearchHighlights() {
        var els = document.querySelectorAll('.search-highlight');
        for (var i = 0; i < els.length; i++) {
            els[i].classList.remove('search-highlight');
        }
    }

    function performSearch() {
        if (!searchInput) return;
        var query = searchInput.value.trim().toLowerCase();

        removeSearchNotice();

        if (!query) {
            // 空查询：清除所有高亮，不显示任何提示
            clearSearchHighlights();
            return;
        }

        // 先清除旧的高亮
        clearSearchHighlights();

        // 搜索范围内匹配关键词
        var items = document.querySelectorAll(SEARCH_SELECTORS);
        var firstMatch = null;
        var matchCount = 0;

        for (var i = 0; i < items.length; i++) {
            var text = items[i].textContent.toLowerCase();
            if (text.indexOf(query) !== -1) {
                items[i].classList.add('search-highlight');
                if (!firstMatch) firstMatch = items[i];
                matchCount++;
            }
        }

        if (matchCount > 0 && firstMatch) {
            // 只滚动到第一个匹配项，避免页面跳窜
            firstMatch.scrollIntoView({ behavior: 'smooth', block: 'center' });
            showSearchNotice(
                '找到 <strong>' + matchCount + '</strong> 条与 "<strong>' +
                escapeHtml(query) + '</strong>" 相关的结果',
                false
            );
        } else {
            showSearchNotice(
                '未找到与 "<strong>' + escapeHtml(query) +
                '</strong>" 相关的结果，请尝试其他关键词',
                true
            );
        }
    }

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }

    if (searchBtn && searchInput) {
        searchBtn.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') performSearch();
        });
        // 输入框获得焦点时，如果有高亮则清除
        searchInput.addEventListener('focus', function() {
            if (this.value.trim() === '') {
                clearSearchHighlights();
                removeSearchNotice();
            }
        });
    }

    // ==========================================
    //  8. 收藏本站按钮
    // ==========================================
    const favBtn = document.getElementById('favBtn');
    if (favBtn) {
        favBtn.addEventListener('click', function(e) {
            e.preventDefault();
            if (window.sidebar && window.sidebar.addPanel) {
                window.sidebar.addPanel(document.title, window.location.href, '');
            } else if (window.external && window.external.AddFavorite) {
                window.external.AddFavorite(window.location.href, document.title);
            } else {
                alert('请使用 Ctrl+D 快捷键收藏本站');
            }
        });
    }

    // ==========================================
    //  9. 移动端菜单切换
    // ==========================================
    const mobileMenuBtn = document.getElementById('mobileMenuBtn');
    const navMenu = document.getElementById('navMenu');

    if (mobileMenuBtn && navMenu) {
        mobileMenuBtn.addEventListener('click', function() {
            navMenu.classList.toggle('active');
            const icon = mobileMenuBtn.querySelector('i');
            if (!icon) return;
            if (navMenu.classList.contains('active')) {
                icon.classList.remove('fa-bars');
                icon.classList.add('fa-times');
            } else {
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            }
        });

        // 点击菜单项时关闭菜单
        const navLinks = navMenu.querySelectorAll('a');
        navLinks.forEach(function(link) {
            link.addEventListener('click', function() {
                navMenu.classList.remove('active');
                const icon = mobileMenuBtn.querySelector('i');
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            });
        });

        // 点击页面其他区域关闭菜单
        document.addEventListener('click', function(e) {
            if (!mobileMenuBtn.contains(e.target) && !navMenu.contains(e.target)) {
                navMenu.classList.remove('active');
                const icon = mobileMenuBtn.querySelector('i');
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            }
        });
    }

});