/**
 * Admin Global Utilities
 *
 * Shared helpers used across all Changeloger admin pages (Releases, Feedback, Roadmap).
 * Exposes the `window.chaAdmin` namespace.
 *
 * @package Changeloger
 */
( function () {
	'use strict';

	/**
	 * Get the best available REST nonce.
	 *
	 * @return {string} Nonce value.
	 */
	function getNonce() {
		return ( typeof wpApiSettings !== 'undefined' && wpApiSettings.nonce )
			? wpApiSettings.nonce
			: '';
	}

	/**
	 * Escape HTML entities in a string.
	 *
	 * @param {string} str Raw string.
	 * @return {string} Escaped string.
	 */
	function escapeHtml( str ) {
		const el = document.createElement( 'span' );
		el.textContent = str || '';
		return el.innerHTML;
	}

	// ─── Confirm Modal ──────────────────────────────────────────────────

	/**
	 * Show a styled confirmation modal matching the existing cha-modal design.
	 *
	 * @param {Object}  opts
	 * @param {string}  opts.title       Modal heading.
	 * @param {string}  opts.message     Body text (supports HTML).
	 * @param {string}  [opts.confirmText='Confirm'] Confirm button label.
	 * @param {string}  [opts.cancelText='Cancel']   Cancel button label.
	 * @param {boolean} [opts.isDanger=false]         Use danger styling for confirm button.
	 * @return {Promise<boolean>} Resolves `true` on confirm, `false` on dismiss.
	 */
	function confirmModal( opts ) {
		return new Promise( function ( resolve ) {
			// Remove any stale instance.
			const existing = document.getElementById( 'cha-confirm-modal' );
			if ( existing ) {
				existing.remove();
			}

			const confirmClass = opts.isDanger ? 'cha-btn-danger' : 'cha-btn-primary';
			const confirmText  = opts.confirmText || 'Confirm';
			const cancelText   = opts.cancelText || 'Cancel';

			const overlay = document.createElement( 'div' );
			overlay.id        = 'cha-confirm-modal';
			overlay.className = 'cha-modal-overlay active';
			overlay.innerHTML = `
				<div class="cha-modal cha-modal-sm">
					<div class="cha-modal-header">
						<h2>${ escapeHtml( opts.title || 'Are you sure?' ) }</h2>
						<button type="button" class="cha-modal-close" data-action="dismiss">
							<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
							</svg>
						</button>
					</div>
					<div class="cha-modal-body" style="display:block;">
						<div style="color: var(--cha-text-secondary, #475569); font-size: 14px; line-height: 1.6;">
							${ opts.message || '' }
						</div>
					</div>
					<div class="cha-modal-footer">
						<button type="button" class="cha-btn cha-btn-secondary" data-action="dismiss">${ escapeHtml( cancelText ) }</button>
						<button type="button" class="cha-btn ${ confirmClass }" data-action="confirm">${ escapeHtml( confirmText ) }</button>
					</div>
				</div>
			`;

			document.body.appendChild( overlay );

			/**
			 * Clean up and resolve.
			 *
			 * @param {boolean} value Resolve value.
			 */
			function close( value ) {
				overlay.remove();
				resolve( value );
			}

			// Confirm button.
			overlay.querySelector( '[data-action="confirm"]' ).addEventListener( 'click', function () {
				close( true );
			} );

			// All dismiss triggers (close × button, Cancel button).
			overlay.querySelectorAll( '[data-action="dismiss"]' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					close( false );
				} );
			} );

			// Click on overlay backdrop.
			overlay.addEventListener( 'click', function ( e ) {
				if ( e.target === overlay ) {
					close( false );
				}
			} );

			// Escape key.
			function onEscape( e ) {
				if ( e.key === 'Escape' ) {
					document.removeEventListener( 'keydown', onEscape );
					close( false );
				}
			}
			document.addEventListener( 'keydown', onEscape );
		} );
	}

	// ─── Delete Product ─────────────────────────────────────────────────

	/**
	 * Delete a product after showing a confirmation modal.
	 *
	 * Each page passes its own `config.onSuccess` callback to handle
	 * page-specific side-effects (reload list, invalidate caches, etc.).
	 *
	 * @param {number|string} id     Product (term) ID.
	 * @param {Object}        config
	 * @param {string}        config.productsUrl REST products endpoint URL.
	 * @param {string}        [config.nonce]     REST nonce override.
	 * @param {Function}      [config.onSuccess] Called after successful deletion.
	 * @param {Function}      [config.onError]   Called on failure.
	 */
	async function deleteProduct( id, config ) {
		const confirmed = await confirmModal( {
			title: 'Delete Product',
			message: '<p style="margin:0 0 12px;"><strong>Are you sure you want to delete this product?</strong></p>' +
				'<p style="margin:0; color: #b91c1c;">⚠ This will permanently delete ALL associated releases, feedback, and roadmap items. This action cannot be undone.</p>',
			confirmText: 'Delete',
			cancelText: 'Cancel',
			isDanger: true,
		} );

		if ( ! confirmed ) {
			return;
		}

		const nonce = config.nonce || getNonce();

		const reportError = function ( msg ) {
			if ( typeof config.onError === 'function' ) {
				config.onError( msg );
			} else if ( typeof showToast !== 'undefined' ) {
				showToast( msg, 'error' );
			} else {
				alert( msg );
			}
		};

		try {
			const response = await fetch( config.productsUrl + '/' + id, {
				method: 'DELETE',
				credentials: 'same-origin',
				headers: {
					'X-WP-Nonce': nonce,
					'Accept': 'application/json',
				},
			} );

			if ( response.ok ) {
				if ( typeof config.onSuccess === 'function' ) {
					config.onSuccess( id );
				}
				return;
			}

			// Non-OK response. Read body once as text, then try JSON.
			const contentType = response.headers.get( 'content-type' ) || '';
			const bodyText    = await response.text();
			let msg           = '';

			if ( contentType.indexOf( 'application/json' ) !== -1 ) {
				try {
					const data = JSON.parse( bodyText );
					msg = ( data && data.message ) ? data.message : '';
				} catch ( _e ) {
					// Malformed JSON — fall through to status-based message.
				}
			}

			if ( ! msg ) {
				if ( response.status === 401 || response.status === 403 ) {
					msg = 'Your session has expired or you lack permission. Please reload the page and try again.';
				} else if ( response.status === 404 ) {
					msg = 'Delete endpoint not found (404). Try resaving permalinks at Settings → Permalinks.';
				} else {
					msg = 'Error deleting product (HTTP ' + response.status + ').';
				}
			}

			console.error( 'Delete product failed:', response.status, bodyText.slice( 0, 500 ) );
			reportError( msg );
		} catch ( err ) {
			console.error( 'Delete product error:', err );
			reportError( 'Failed to delete product. ' + ( err && err.message ? err.message : '' ) );
		}
	}

	// ─── Product UI Utilities ───────────────────────────────────────────

	/**
	 * Open product modal for adding or editing.
	 *
	 * @param {Object|null} product        Product object to edit, or null for new.
	 * @param {Function}    setEditingFunc Callback to update the page script's `editingProduct` state.
	 */
	function openProductModal( product, setEditingFunc ) {
		if ( typeof setEditingFunc === 'function' ) {
			setEditingFunc( product );
		}

		const form = document.getElementById( 'cha-product-form' );
		const nameInput = document.getElementById( 'cha-product-name' );
		const modalTitle = document.getElementById( 'cha-product-modal-title' );

		if ( form ) {
			form.reset();
		}

		if ( product ) {
			if ( modalTitle ) {
				modalTitle.textContent = 'Edit Product';
			}
			if ( nameInput ) {
				nameInput.value = product.name;
			}
		} else {
			if ( modalTitle ) {
				modalTitle.textContent = 'Add New Product';
			}
		}

		const modal = document.getElementById( 'cha-product-modal' );
		if ( modal ) {
			modal.classList.add( 'active' );
			document.body.style.overflow = 'hidden';
		}

		setTimeout( function () {
			if ( nameInput ) {
				nameInput.focus();
			}
		}, 50 );
	}

	/**
	 * Close the product modal.
	 */
	function closeProductModal() {
		const modal = document.getElementById( 'cha-product-modal' );
		if ( modal ) {
			modal.classList.remove( 'active' );
			document.body.style.overflow = '';
		}
	}

	/**
	 * Show product limit modal with options for Free users.
	 *
	 * @param {Object} config
	 * @param {string} config.upgradeUrl
	 * @param {string} config.homeUrl
	 * @param {string} config.adminUrl
	 * @param {string} config.nonce
	 */
	function showProductLimitModal( config ) {
		const existingModal = document.getElementById( 'cha-product-limit-modal' );
		if ( existingModal ) {
			existingModal.remove();
		}

		const modal = document.createElement( 'div' );
		modal.id = 'cha-product-limit-modal';
		modal.className = 'cha-modal-overlay active';
		modal.innerHTML = `
			<div class="cha-modal cha-modal-variation-2">
				<button type="button" class="cha-modal-close">&times;</button>
				<div class="cha-modal-variation-body">
					<div class="cha-modal-variation-icon">
						<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="white" width="32" height="32">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
						</svg>
					</div>
					<h2 class="cha-modal-variation-title">Product Limit Reached</h2>
					<p class="cha-modal-variation-desc">The free version is limited to 1 product. Choose how you want to proceed:</p>
					
					<div class="cha-modal-options-grid">
						<div class="cha-modal-option-card primary">
							<div class="cha-modal-option-badge">Recommended</div>
							<div class="cha-modal-option-icon">
								<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="24" height="24">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
								</svg>
							</div>
							<h3 class="cha-modal-option-title">Upgrade to Pro</h3>
							<p class="cha-modal-option-desc">Unlock unlimited products, custom domains, text import, and advanced tracking.</p>
							<a href="${ escapeHtml( config.upgradeUrl || '#' ) }" class="cha-btn cha-btn-primary cha-modal-cta-full">Upgrade Now</a>
						</div>

						<div class="cha-modal-option-card secondary">
							<div class="cha-modal-option-icon">
								<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="24" height="24">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
								</svg>
							</div>
							<h3 class="cha-modal-option-title">Use Free Block</h3>
							<p class="cha-modal-option-desc">Create a dedicated page using the Changeloger block for unlimited changelogs.</p>
							<a href="#" class="cha-btn cha-btn-secondary cha-modal-cta-full cha-create-block-page-link">Create Page</a>
						</div>
					</div>
				</div>
			</div>
		`;

		document.body.appendChild( modal );

		modal.querySelector( '.cha-modal-close' ).addEventListener( 'click', function () {
			modal.remove();
		} );
		modal.addEventListener( 'click', function ( e ) {
			if ( e.target === modal ) {
				modal.remove();
			}
		} );

		const createLink = modal.querySelector( '.cha-create-block-page-link' );
		if ( createLink ) {
			createLink.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				if ( createLink.dataset.loading ) {
					return;
				}
				createLink.dataset.loading = 'true';
				createLink.textContent = 'Creating...';

				fetch( config.homeUrl + '/wp-json/wp/v2/pages', {
					method: 'POST',
					credentials: 'same-origin',
					headers: {
						'Content-Type': 'application/json',
						'X-WP-Nonce': config.nonce || getNonce(),
					},
					body: JSON.stringify( {
						title: 'Changelog',
						status: 'draft',
					} ),
				} )
					.then( function ( r ) {
						return r.json();
					} )
					.then( function ( data ) {
						if ( data && data.id ) {
							window.open(
								config.adminUrl + 'post.php?post=' + data.id + '&action=edit&cha_add_block=changeloger',
								'_blank'
							);
							createLink.textContent = 'Page Created ✓';
						} else {
							throw new Error( data.message || 'Failed to create page.' );
						}
					} )
					.catch( function ( error ) {
						console.error( 'Error creating page:', error );
						alert( 'Error: ' + error.message );
						createLink.textContent = 'Use Free Block';
						delete createLink.dataset.loading;
					} );
			} );
		}
	}

	/**
	 * Handle Add Product button click.
	 *
	 * @param {Object} config
	 * @param {boolean}  config.isPremium
	 * @param {Function} config.setEditing Func to clear editing state before open
	 * @param {string}   [config.upgradeUrl]
	 * @param {string}   [config.homeUrl]
	 * @param {string}   [config.adminUrl]
	 * @param {string}   [config.nonce]
	 */
	function handleAddProductClick( config ) {
		if ( ! config.isPremium ) {
			const count = document.querySelectorAll( '.cha-product-tab' ).length;
			if ( count >= 1 ) {
				showProductLimitModal( config );
				return;
			}
		}
		openProductModal( null, config.setEditing );
	}

	// ─── Toast Notifications ────────────────────────────────────────────

	/**
	 * Show a toast notification.
	 *
	 * @param {string} msg  The message to display.
	 * @param {string} type 'success' or 'error'.
	 */
	function showToast( msg, type ) {
		let container = document.getElementById( 'cha-toast-container' );
		if ( ! container ) {
			container = document.createElement( 'div' );
			container.id = 'cha-toast-container';
			container.className = 'cha-toast-container';
			document.body.appendChild( container );
		}

		const toast = document.createElement( 'div' );
		toast.className = 'cha-toast cha-toast-' + ( type || 'info' );
		
		let icon = '';
		if ( type === 'success' ) {
			icon = '<svg width="20" height="20" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>';
		} else if ( type === 'error' ) {
			icon = '<svg width="20" height="20" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>';
		}

		toast.innerHTML = `<div class="cha-toast-icon">${icon}</div><div class="cha-toast-msg">${escapeHtml( msg )}</div><button class="cha-toast-close">&times;</button>`;

		container.appendChild( toast );

		const closeBtn = toast.querySelector( '.cha-toast-close' );
		closeBtn.addEventListener( 'click', function() {
			toast.remove();
		} );

		setTimeout( function() {
			if ( toast.parentNode ) {
				toast.remove();
			}
		}, 4000 );
	}

	// ─── Public API ─────────────────────────────────────────────────────

	window.chaAdmin = {
		escapeHtml: escapeHtml,
		getNonce: getNonce,
		confirmModal: confirmModal,
		deleteProduct: deleteProduct,
		openProductModal: openProductModal,
		closeProductModal: closeProductModal,
		showProductLimitModal: showProductLimitModal,
		handleAddProductClick: handleAddProductClick,
		showToast: showToast
	};
} )();
