/* global CleanViewToast, CleanViewModal, puredashConfig, jQuery, confirm */
/**
 * CleanView Modal
 * Handles the custom interaction dialog.
 *
 * @param {Window}   window   - The global window object.
 * @param {Document} document - The document object.
 */
( function ( window, document ) {
	'use strict';

	const ZenModal = {
		overlay: null,
		modal: null,
		lastFocusedElement: null,

		/**
		 * Initialize the modal HTML structure
		 */
		init() {
			if ( this.overlay ) {
				return;
			}

			// Create Overlay
			this.overlay = document.createElement( 'div' );
			this.overlay.className = 'cleanview-modal-overlay';
			this.overlay.style.display = 'none';
			this.overlay.setAttribute( 'aria-hidden', 'true' );

			// Create Modal
			this.modal = document.createElement( 'div' );
			this.modal.className = 'cleanview-modal';
			this.modal.setAttribute( 'role', 'dialog' );
			this.modal.setAttribute( 'aria-modal', 'true' );
			this.modal.setAttribute( 'aria-labelledby', 'cleanview-modal-title' );

			this.overlay.appendChild( this.modal );
			document.body.appendChild( this.overlay );

			// Bind Events
			this.overlay.addEventListener( 'click', ( e ) => {
				if ( e.target === this.overlay ) {
					this.close();
				}
			} );

			document.addEventListener( 'keydown', ( e ) => {
				if ( ! this.isOpen() ) {
					return;
				}

				if ( e.key === 'Escape' ) {
					this.close();
				}

				if ( e.key === 'Tab' ) {
					this.handleTab( e );
				}
			} );
		},

		/**
		 * Open the modal with configuration
		 * @param {Object} config 
		 */
		open( config ) {
			this.init();
			// Store currently focused element
			this.lastFocusedElement = this.modal.ownerDocument.activeElement;

			// Category Icon Mapping
			const categoryIcons = {
				menu: 'menu',
				'admin-bar': 'ellipsis',
				dashboard: 'dashboard',
				notices: 'megaphone',
				other: 'visibility'
			};

			const categoryLabels = {
				menu: 'Menu WordPress',
				'admin-bar': 'Barre d\'outils',
				dashboard: 'Tableau de bord',
				notices: 'Notifications',
				other: 'Divers'
			};

			const catIcon = categoryIcons[ config.category ] || 'visibility';
			const catLabel = categoryLabels[ config.category ] || 'Divers';

			// Render Content
			if ( config.type === 'confirm' ) {
				this.modal.innerHTML = `
					<h2 id="cleanview-modal-title">
					    <span class="dashicons dashicons-warning"></span>
					    ${ config.title || 'Confirm Action' }
					</h2>
					<div class="cleanview-modal-body">
					    <p>${ this.escapeHtml( config.message || 'Are you sure?' ) }</p>
					</div>
					<div class="cleanview-modal-footer">
					    <button class="cleanview-btn cleanview-btn-secondary" id="cleanview-cancel-btn">${ config.i18n.cancel || 'Cancel' }</button>
					    <button class="cleanview-btn cleanview-btn-primary" id="cleanview-confirm-btn">${ config.i18n.confirm || 'Confirm' }</button>
					</div>
				`;
			} else {
				this.modal.innerHTML = `
					<h2 id="cleanview-modal-title">
					    <span class="dashicons dashicons-shield"></span>
					    ${ config.title || 'Block Element' }
					</h2>
					<div class="cleanview-modal-body">
					    <div class="cleanview-category-badge" style="background: #f0f0f1; padding: 5px 10px; border-radius: 4px; display: inline-flex; align-items: center; margin-bottom: 15px; border: 1px solid #dcdcde;">
					        <i class="dashicons dashicons-${ catIcon }" style="font-size: 16px; width: 16px; height: 16px; margin-right: 8px; color: #646970;"></i>
					        <span style="font-weight: 600; font-size: 11px; text-transform: uppercase; color: #50575e;">Type : ${ catLabel }</span>
					    </div>

					    <div class="cleanview-warning" id="cleanview-specificity-warning">
					        <span class="dashicons dashicons-warning"></span>
					        ${ config.warning || 'Warning: This selector matches multiple elements.' }
					    </div>
					    
					    <div class="cleanview-field">
					        <label>${ config.i18n.label || 'Label' }</label>
					        <input type="text" id="cleanview-label-input" value="${ this.escapeHtml( config.label ) }" placeholder="e.g. Annoying Banner">
					    </div>

					    <div class="cleanview-field">
					        <label>Target Selector</label>
					        <code>${ this.escapeHtml( config.selector ) }</code>
					    </div>

					    <div class="cleanview-field">
					         <label>
					            <input type="checkbox" id="cleanview-session-only"> 
					            ${ config.i18n.sessionOnly || 'Hide for this session only' }
					        </label>
					    </div>
					</div>
					<div class="cleanview-modal-footer">
					    <button class="cleanview-btn cleanview-btn-secondary" id="cleanview-cancel-btn">${ config.i18n.cancel || 'Cancel' }</button>

					    <button class="cleanview-btn cleanview-btn-primary" id="cleanview-confirm-btn">${ config.i18n.confirm || 'Hide Element' }</button>
					</div>
				`;
			}

			// Static promo banner (no links) inserted after the Session checkbox field.
			if ( config.type !== 'confirm' ) {
				const promoHtml = `
				    <div class="cleanview-promo-banner" style="margin: 20px 0 0;">
				        <img src="${ puredashConfig.pluginUrl }assets/roles-manager.png" alt="${ 'More control with PureDash Pro — hide elements per user roles and block level access' }" style="max-width: 100%; height: auto; display: block; border-radius: 3px;">
				    </div>
				`;
				this.modal.querySelector( '#cleanview-session-only' ).closest( '.cleanview-field' ).insertAdjacentHTML( 'afterend', promoHtml );
			}

			// Show Specificity Warning if needed
			if ( config.showWarning ) {
				document.getElementById( 'cleanview-specificity-warning' ).style.display = 'block';
			}

			// Show
			this.overlay.style.display = 'flex';
			this.overlay.style.position = 'fixed';
			this.overlay.style.top = '0';
			this.overlay.style.left = '0';
			this.overlay.style.width = '100%';
			this.overlay.style.height = '100%';
			this.overlay.style.justifyContent = 'center';
			this.overlay.style.alignItems = 'center';
			this.overlay.setAttribute( 'aria-hidden', 'false' );

			// Bind Button Events
			document.getElementById( 'cleanview-cancel-btn' ).addEventListener( 'click', (e) => {
				e.preventDefault();
				e.stopPropagation();
				this.close();
				if ( typeof config.onCancel === 'function' ) {
					config.onCancel();
				}
			} );

			document.getElementById( 'cleanview-confirm-btn' ).addEventListener( 'click', () => {
				if ( config.type === 'confirm' ) {
					if ( config.onConfirm ) {
						config.onConfirm();
					}
					this.close();
					return;
				}

				const label = document.getElementById( 'cleanview-label-input' ).value;
				const isSession = document.getElementById( 'cleanview-session-only' ).checked;

				if ( config.onConfirm ) {
					config.onConfirm( {
						label: label,
						isSession: isSession,
						category: config.category,
					} );
				}
				this.close();
			} );

			// Trap Focus
			const focusable = this.modal.querySelectorAll( 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' );
			if ( focusable.length ) {
				focusable[ 0 ].focus();
			}
		},

		/**
		 * Close the modal
		 */
		close() {
			if ( ! this.overlay ) {
				return;
			}
			this.overlay.style.display = 'none';
			this.overlay.setAttribute( 'aria-hidden', 'true' );
			if ( this.lastFocusedElement ) {
				this.lastFocusedElement.focus();
			}
		},

		/**
		 * Check if modal is open.
		 *
		 * @return {boolean} True if open.
		 */
		isOpen() {
			return this.overlay && this.overlay.style.display === 'flex';
		},

		/**
		 * Escape HTML to prevent XSS.
		 *
		 * @param {string} text - The text to escape.
		 * @return {string} Escaped HTML.
		 */
		escapeHtml( text ) {
			const div = document.createElement( 'div' );
			div.textContent = text;
			return div.innerHTML;
		}
	};

	/**
	 * CleanView Toast Notification System
	 * Replaces native alert() with custom styled notifications
	 */
	const ZenToast = {
		container: null,

		/**
		 * Initialize toast container
		 */
		init() {
			if ( this.container ) {
				return;
			}

			this.container = document.createElement( 'div' );
			this.container.className = 'cleanview-toast-container';
			document.body.appendChild( this.container );
		},

		/**
		 * Show a toast notification
		 *
		 * @param {string} message  - The message to display.
		 * @param {string} type     - Type: 'success', 'error', 'warning', 'info'.
		 * @param {number} duration - Duration in ms (0 = manual close).
		 */
		show( message, type = 'info', duration = 4000 ) {
			this.init();

			const toast = document.createElement( 'div' );
			toast.className = `cleanview-toast cleanview-toast-${ type }`;

			const icons = {
				success: 'yes-alt',
				error: 'dismiss',
				warning: 'warning',
				info: 'info'
			};

			toast.innerHTML = `
				<span class="dashicons dashicons-${ icons[ type ] || 'info' }"></span>
				<span class="cleanview-toast-message">${ this.escapeHtml( message ) }</span>
				<button class="cleanview-toast-close" aria-label="Close">
					<span class="dashicons dashicons-no-alt"></span>
				</button>
			`;

			// Close button handler
			toast.querySelector( '.cleanview-toast-close' ).addEventListener( 'click', () => {
				this.dismiss( toast );
			} );

			this.container.appendChild( toast );

			// Animate in
			requestAnimationFrame( () => {
				toast.classList.add( 'cleanview-toast-visible' );
			} );

			// Auto dismiss
			if ( duration > 0 ) {
				setTimeout( () => {
					this.dismiss( toast );
				}, duration );
			}

			return toast;
		},

		/**
		 * Dismiss a toast.
		 *
		 * @param {HTMLElement} toast - The toast element to dismiss.
		 */
		dismiss( toast ) {
			if ( ! toast || ! toast.parentNode ) {
				return;
			}

			toast.classList.remove( 'cleanview-toast-visible' );
			toast.classList.add( 'cleanview-toast-hiding' );

			setTimeout( () => {
				if ( toast.parentNode ) {
					toast.parentNode.removeChild( toast );
				}
			}, 300 );
		},

		/**
		 * Show success toast
		 *
		 * @param {string} message  - The message to display.
		 * @param {number} duration - Duration in ms (optional).
		 */
		success( message, duration ) {
			return this.show( message, 'success', duration );
		},

		/**
		 * Show error toast
		 *
		 * @param {string} message  - The message to display.
		 * @param {number} duration - Duration in ms (optional, default 6000).
		 */
		error( message, duration ) {
			return this.show( message, 'error', duration || 6000 );
		},

		/**
		 * Show warning toast
		 *
		 * @param {string} message  - The message to display.
		 * @param {number} duration - Duration in ms (optional, default 5000).
		 */
		warning( message, duration ) {
			return this.show( message, 'warning', duration || 5000 );
		},

		/**
		 * Show info toast
		 *
		 * @param {string} message  - The message to display.
		 * @param {number} duration - Duration in ms (optional).
		 */
		info( message, duration ) {
			return this.show( message, 'info', duration );
		},

		/**
		 * Escape HTML to prevent XSS.
		 *
		 * @param {string} text - The text to escape.
		 * @return {string} Escaped HTML.
		 */
		escapeHtml( text ) {
			const div = document.createElement( 'div' );
			div.textContent = text;
			return div.innerHTML;
		}
	};

	// Expose Globals
	window.CleanViewModal = ZenModal;
	window.CleanViewToast = ZenToast;

} )( window, document );
