document.addEventListener('DOMContentLoaded', function () {
	const galleries = document.querySelectorAll('.wp-block-gallery');
	
	const Set = haupGlightboxSettings;

	galleries.forEach((gallery, index) => {
		const links = gallery.querySelectorAll('a[href$=".jpg"], a[href$=".jpeg"], a[href$=".png"], a[href$=".webp"]');
		const groupName = `gallery-${index}`;
		links.forEach(link => link.setAttribute('data-glightbox', groupName));

		const lightbox = GLightbox({
			selector: `[data-glightbox="${groupName}"]`,
			loop: true,
			slideEffect: 'fade'
		});

		let autoplayTimeout = null;
		let isPaused = false;
		const delay = Set.delay;

		// ボタン要素を作成（デザインを少し強調）
		const playPauseBtn = document.createElement('button');
		playPauseBtn.id = `glightbox-btn-${index}`;
		playPauseBtn.style.cssText = `
			position: fixed;
			bottom: 20px;
			right: 20px;
			z-index: 2147483647;
			background: rgba(0, 0, 0, 0.7);
			color: #fff;
			border: 2px solid rgba(255, 255, 255, 0.5);
			padding: 10px 20px;
			border-radius: 5px;
			cursor: pointer;
			font-size: 14px;
			font-weight: bold;
			display: none;
			backdrop-filter: blur(5px);
			transition: all 0.2s ease;
			box-shadow: 0 4px 12px rgba(0,0,0,0.3);
		`;

		const updateButtonUI = () => {
			playPauseBtn.innerHTML = isPaused ? Set.text_play : Set.text_pause;
			playPauseBtn.style.borderColor = isPaused ? '#00ff00' : 'rgba(255,255,255,0.5)';
		};

		const goToNext = () => {
			if (isPaused) return;
			const instance = Array.isArray(lightbox) ? lightbox[0] : lightbox;
			if (instance && typeof instance.next === 'function') instance.next();
			else {
				const nextBtn = document.querySelector('.gnext');
				if (nextBtn) nextBtn.click();
			}
		};

		const startAutoplay = () => {
			stopAutoplay();
			if (!isPaused) autoplayTimeout = setTimeout(goToNext, delay);
		};

		const stopAutoplay = () => {
			if (autoplayTimeout) {
				clearTimeout(autoplayTimeout);
				autoplayTimeout = null;
			}
		};

		playPauseBtn.addEventListener('click', (e) => {
			e.preventDefault();
			e.stopPropagation();
			isPaused = !isPaused;
			updateButtonUI();
			if (isPaused) stopAutoplay();
			else startAutoplay();
		});

		lightbox.on('open', () => {
			// body直下ではなく、glightboxのコンテナの中に直接入れる
			const container = document.body; 
			container.appendChild(playPauseBtn);
			playPauseBtn.style.display = 'block';
			isPaused = false;
			updateButtonUI();
			startAutoplay();
		});

		lightbox.on('slide_changed', () => {
			if (!isPaused) startAutoplay();
		});

		lightbox.on('close', () => {
			if (playPauseBtn.parentNode) {
				playPauseBtn.parentNode.removeChild(playPauseBtn);
			}
			stopAutoplay();
		});
	});
});