/**
 * Freefactu Modal Handlers
 *
 * Common modal functionality for environment info and certificate help modals.
 *
 * @package Freefactu
 * @since 1.3.0
 */

(function() {
	'use strict';

	document.addEventListener('DOMContentLoaded', function() {
		// Initialize environment modal
		initModal('freefactu-environment-modal', 'freefactuOpenEnvironmentModal');
		
		// Initialize certificate modal
		initModal('freefactu-certificate-modal', 'freefactuOpenCertificateModal');
		
		// Initialize SIF producer modal
		initSifProducerModal();
	});

	/**
	 * Initialize a modal with common handlers.
	 *
	 * @param {string} modalId        ID of the modal element.
	 * @param {string} globalFunction Name of the global function to open the modal.
	 */
	function initModal(modalId, globalFunction) {
		var modal = document.getElementById(modalId);
		if (!modal) return;

		// Close button handlers
		var closeButtons = modal.querySelectorAll('.freefactu-modal-close, .freefactu-modal-close-btn');
		closeButtons.forEach(function(btn) {
			btn.addEventListener('click', function() {
				modal.style.display = 'none';
			});
		});

		// Click outside to close (supports both old overlay-wrapper and new modal-wrapper patterns)
		modal.addEventListener('click', function(e) {
			if (e.target === modal || e.target.classList.contains('freefactu-modal-overlay')) {
				modal.style.display = 'none';
			}
		});

		// ESC key to close
		document.addEventListener('keydown', function(e) {
			if (e.key === 'Escape' && modal.style.display !== 'none') {
				modal.style.display = 'none';
			}
		});

		// Global function to open the modal
		window[globalFunction] = function() {
			if (modal) {
				modal.style.display = 'flex';
			}
		};
	}

	/**
	 * Initialize SIF Producer Info modal for the declarations page.
	 */
	function initSifProducerModal() {
		var link = document.getElementById('freefactu-sif-producer-info-link');
		var modal = document.getElementById('freefactu-sif-producer-modal');
		
		if (!link || !modal) return;

		// Open modal
		link.addEventListener('click', function(e) {
			e.preventDefault();
			modal.style.display = 'flex';
		});

		// Close button
		var closeButtons = modal.querySelectorAll('.freefactu-modal-close');
		closeButtons.forEach(function(btn) {
			btn.addEventListener('click', function(e) {
				e.preventDefault();
				modal.style.display = 'none';
			});
		});

		// Overlay click
		var overlay = modal.querySelector('.freefactu-modal-overlay');
		if (overlay) {
			overlay.addEventListener('click', function(e) {
				if (e.target === overlay) {
					modal.style.display = 'none';
				}
			});
		}

		// ESC key
		document.addEventListener('keydown', function(e) {
			if (e.key === 'Escape' && modal.style.display !== 'none' && modal.style.display !== '') {
				modal.style.display = 'none';
			}
		});
	}
})();
