/**
 * 产品详情页JavaScript功能
 */

// 确保底部文字宽度与图片宽度一致
function adjustScenarioTextWidth() {
    const scenarioImages = document.querySelectorAll('.scenario-image img');
    const scenarioTexts = document.querySelectorAll('.scenario-text');
    
    scenarioImages.forEach((img, index) => {
        if (scenarioTexts[index]) {
            const updateWidth = () => {
                const imgWidth = img.offsetWidth;
                scenarioTexts[index].style.width = imgWidth + 'px';
            };
            
            // 图片加载完成后调整宽度
            // if (img.complete) {
            //     updateWidth();
            // } else {
            //     img.addEventListener('load', updateWidth);
            // }
            
            // 窗口大小改变时重新调整
            window.addEventListener('resize', updateWidth);
        }
    });
}

/**
 * 技术规格手风琴组件
 */
class TechnicalSpecsAccordion {
    constructor(container) {
        this.container = container;
        this.triggers = container.querySelectorAll('.accordion-trigger');
        this.init();
    }

    init() {
        this.bindEvents();
        this.setInitialStates();
    }

    bindEvents() {
        this.triggers.forEach(trigger => {
            trigger.addEventListener('click', (e) => this.handleToggle(e));
            trigger.addEventListener('keydown', (e) => this.handleKeydown(e));
        });
    }

    handleToggle(event) {
        const trigger = event.currentTarget;
        const item = trigger.closest('.accordion-item');
        const panel = item.querySelector('.accordion-panel');
        const isExpanded = trigger.getAttribute('aria-expanded') === 'true';

        this.togglePanel(trigger, panel, !isExpanded);
    }

    handleKeydown(event) {
        const { key } = event;
        const trigger = event.currentTarget;
        
        // 支持键盘导航
        if (key === 'Enter' || key === ' ') {
            event.preventDefault();
            this.handleToggle(event);
        } else if (key === 'ArrowDown' || key === 'ArrowUp') {
            event.preventDefault();
            this.focusNextTrigger(trigger, key === 'ArrowDown');
        }
    }

    togglePanel(trigger, panel, expand) {
        const item = trigger.closest('.accordion-item');
        
        // 更新ARIA属性
        trigger.setAttribute('aria-expanded', expand.toString());
        
        if (expand) {
            // 展开面板
            item.classList.add('is-expanded');
            panel.removeAttribute('hidden');
            panel.style.maxHeight = 'none'; // 先重置maxHeight
            
            // 设置动画高度
            requestAnimationFrame(() => {
                const height = panel.scrollHeight;
                panel.style.maxHeight = '0';
                requestAnimationFrame(() => {
                    panel.style.maxHeight = height + 'px';
                });
            });
        } else {
            // 收起面板
            const currentHeight = panel.scrollHeight;
            panel.style.maxHeight = currentHeight + 'px';
            
            // 强制重绘后设置为0
            requestAnimationFrame(() => {
                panel.style.maxHeight = '0';
                item.classList.remove('is-expanded');
            });
            
            // 动画完成后隐藏
            setTimeout(() => {
                if (!item.classList.contains('is-expanded')) {
                    panel.setAttribute('hidden', '');
                    panel.style.maxHeight = ''; // 清除内联样式
                }
            }, 300);
        }
    }

    focusNextTrigger(currentTrigger, forward = true) {
        const triggers = Array.from(this.triggers);
        const currentIndex = triggers.indexOf(currentTrigger);
        let nextIndex;

        if (forward) {
            nextIndex = currentIndex === triggers.length - 1 ? 0 : currentIndex + 1;
        } else {
            nextIndex = currentIndex === 0 ? triggers.length - 1 : currentIndex - 1;
        }

        triggers[nextIndex].focus();
    }

    setInitialStates() {
        this.triggers.forEach(trigger => {
            const item = trigger.closest('.accordion-item');
            const panel = item.querySelector('.accordion-panel');
            const isExpanded = item.classList.contains('is-expanded');
            
            // 设置初始ARIA属性
            trigger.setAttribute('aria-expanded', isExpanded.toString());
            
            // 设置初始显示状态
            if (isExpanded) {
                panel.removeAttribute('hidden');
                // 确保展开的面板有正确的高度
                requestAnimationFrame(() => {
                    panel.style.maxHeight = panel.scrollHeight + 'px';
                });
            } else {
                panel.setAttribute('hidden', '');
                panel.style.maxHeight = '0';
            }
        });
        
        // 添加调试信息
        console.log('Technical Specs Accordion initialized with', this.triggers.length, 'triggers');
    }
}

// 防止重复初始化的标志
let accordionInitialized = false;
let scenarioWidthInitialized = false;

// 初始化技术规格手风琴
function initTechnicalSpecsAccordion() {
    if (accordionInitialized) {
        return;
    }
    
    const accordionContainer = document.querySelector('.specs-accordion');
    if (accordionContainer) {
        // 检查是否已经初始化过
        if (!accordionContainer.hasAttribute('data-accordion-initialized')) {
            new TechnicalSpecsAccordion(accordionContainer);
            accordionContainer.setAttribute('data-accordion-initialized', 'true');
            accordionInitialized = true;
        }
    }
}

// 初始化场景文字宽度调整
function initScenarioTextWidth() {
    if (scenarioWidthInitialized) {
        return;
    }
    
    adjustScenarioTextWidth();
    scenarioWidthInitialized = true;
}

// 主初始化函数
function initProductsContent() {
    initScenarioTextWidth();
    initTechnicalSpecsAccordion();
}

// DOM加载完成后执行
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initProductsContent);
} else {
    // DOM已经加载完成
    initProductsContent();
}

// 如果是WordPress环境，也在jQuery ready时执行（作为备用）
if (typeof jQuery !== 'undefined') {
    jQuery(document).ready(function() {
        // 延迟执行以避免与其他脚本冲突
        setTimeout(initProductsContent, 100);
    });
}