document.addEventListener('DOMContentLoaded', () => {
	const accordionButtons = document.querySelectorAll('.wp-block-accordion-heading__toggle');

	const openSpeed = 600;   
	const closeSpeed = 150;  

	accordionButtons.forEach(button => {
		button.addEventListener('click', (e) => {
			const item = button.closest('.wp-block-accordion-item');
      
			// 「スムースアコーディオン」が選択されていない場合は、何もせずWordPressの通常処理に流す
			if (!item || !item.classList.contains('is-style-ha-smooth-accordion')) {
			return;
			}

			//  スタイルが選択されている場合のみ、ここから下の「乗っ取り処理」を実行
			e.preventDefault();
			e.stopImmediatePropagation();

			const panel = item.querySelector('.wp-block-accordion-panel');
			if (!panel) return;

			const isOpen = item.classList.contains('is-open');

			panel.style.setProperty('display', 'block', 'important');
			panel.style.overflow = 'hidden';
			const contentHeight = panel.scrollHeight;

			if (!isOpen) {
				item.classList.add('is-open');
				button.setAttribute('aria-expanded', 'true');
				panel.removeAttribute('inert');

				panel.animate([
					{ height: '0px', opacity: 0 },
					{ height: contentHeight + 'px', opacity: 1 }
				], {
					duration: openSpeed,
					easing: 'cubic-bezier(0.25, 1, 0.5, 1)',
					fill: 'forwards'
				});

				setTimeout(() => {
					panel.style.height = 'auto';
					panel.style.opacity = '1';
				}, openSpeed);

			} else {
				item.classList.remove('is-open');
				button.setAttribute('aria-expanded', 'false');
				panel.setAttribute('inert', '');

				const currentHeight = panel.offsetHeight;

				const closingAnim = panel.animate([
					{ height: currentHeight + 'px', opacity: 1 },
					{ height: '0px', opacity: 0 }
				], {
					duration: closeSpeed,
					easing: 'ease-in',
					fill: 'forwards'
				});

				closingAnim.onfinish = () => {
					panel.style.removeProperty('display');
					panel.style.height = '';
					panel.style.opacity = '';
					panel.getAnimations().forEach(anim => anim.cancel());
				};
			}
		}, { capture: true }); // コアより先にクリックを奪う
	});
});