/**
 * Template Library JS
 *
 * Handles the "Choose Template" popup shown after a new Header/Footer
 * template draft is created.
 *
 * Changes from original:
 * ----------------------
 * 1. Type dropdown moved to sits-tpl-modal-body (was already in body; now
 *    hidden during load, revealed only AFTER templates finish loading).
 * 2. Spinner/loading animation added to "Use This", "Insert & Edit with
 *    Elementor", and "Skip — Start Blank" buttons while requests are pending.
 * 3. Template previews now use <img> tags instead of inline SVG. Each
 *    template JSON should include a "thumbnail" field with a relative path
 *    (e.g. "header/header-classic-light.png") inside
 *    includes/template-library/templates/. A generic placeholder is shown
 *    when no thumbnail is provided.
 *
 * @package Softech_Addons_for_Elementor
 */
/* global sitsTemplateLibrary, jQuery */

( function ( $ ) {
	'use strict';

	var cfg            = window.sitsTemplateLibrary || {};
	var s              = cfg.strings || {};
	var currentPostId  = 0;
	var currentType    = '';
	var selectedTemplateId = '';

	/* ------------------------------------------------------------------ */
	/* Spinner markup helper                                               */
	/* ------------------------------------------------------------------ */

	function spinnerHtml() {
		return '<span class="sits-tpl-btn-spinner" aria-hidden="true"></span>';
	}

	/* ------------------------------------------------------------------ */
	/* Public API                                                           */
	/* ------------------------------------------------------------------ */

	function showTemplateLibrary( postId, type ) {
		currentPostId      = postId;
		currentType        = type;
		selectedTemplateId = '';

		var $popup = $( buildPopupHtml() );
		$( 'body' ).append( $popup );

		setTimeout( function () {
			$popup.addClass( 'sits-tpl-overlay--visible' );
		}, 10 );

		loadTemplates( currentType, $popup );
		attachEvents( $popup );
	}

	window.sitsShowTemplateLibrary = showTemplateLibrary;

	/* ------------------------------------------------------------------ */
	/* Build popup HTML                                                     */
	/* ------------------------------------------------------------------ */

	function buildPopupHtml() {
		var typeOptions = [
			{ val: 'header',      label: 'Header'      },
			{ val: 'footer',      label: 'Footer'      },
			{ val: 'archive',     label: 'Archive'     },
			{ val: 'single_page', label: 'Single Page' },
			{ val: 'single_post', label: 'Single Post' },
			{ val: '404_page',    label: '404 Page'    },
		];
		var typeOptsHtml = typeOptions.map( function ( t ) {
			return '<option value="' + t.val + '"' + ( t.val === currentType ? ' selected' : '' ) + '>' + t.label + '</option>';
		} ).join( '' );

		return (
			'<div class="sits-tpl-overlay" role="dialog" aria-modal="true" aria-label="' + ( s.selectTemplate || 'Choose Template' ) + '">' +
				'<div class="sits-tpl-modal">' +

					/* ── Modal header (title + close only) ── */
					'<div class="sits-tpl-modal-header">' +
						'<div class="sits-tpl-modal-header-left">' +
							'<div class="sits-tpl-modal-icon">&#9881;</div>' +
							'<div class="sits-tpl-modal-title-wrap">' +
								'<h2>' + ( s.selectTemplate || 'Choose Template' ) + '</h2>' +
								'<p class="sits-tpl-modal-subtitle">Pick a starter design or begin with a blank canvas. Everything is customisable in Elementor.</p>' +
							'</div>' +
						'</div>' +
						'<button type="button" class="sits-tpl-modal-close" aria-label="Close">&times;</button>' +
					'</div>' +

					/* ── Modal body ── */
					'<div class="sits-tpl-modal-body">' +

						/* 1. Loader – shown first while templates fetch */
						'<div class="sits-tpl-loading">' +
							'<div class="sits-tpl-spinner"></div>' +
							'<p>' + ( s.loadingTemplates || 'Loading templates...' ) + '</p>' +
						'</div>' +

						/* 2. Type dropdown – hidden during load, shown after templates appear */
						'<div class="sits-tpl-type-wrap" style="display:none;">' +
							'<select class="sits-tpl-type-select" aria-label="Template type">' +
								typeOptsHtml +
							'</select>' +
						'</div>' +

						/* 3. Template grid (used for header/footer/404/single_post with templates) */
						'<div class="sits-tpl-grid" style="display:none;"></div>' +
						/* 4. No-library state (archive / single_page) — centred, outside grid */
						'<div class="sits-tpl-nolibrary-wrap" style="display:none;"></div>' +
						'<div class="sits-tpl-error" style="display:none;"></div>' +
					'</div>' +

					/* ── Modal footer ── */
					'<div class="sits-tpl-modal-footer">' +
						'<span class="sits-tpl-selected-label"></span>' +
						'<div class="sits-tpl-footer-actions">' +
							'<button type="button" class="sits-tpl-btn sits-tpl-skip-btn">' + ( s.skip || 'Skip — Start Blank' ) + '</button>' +
							'<button type="button" class="sits-tpl-btn sits-tpl-insert-btn" disabled>' +
								'<span class="sits-tpl-btn-check" aria-hidden="true">&#10003;</span> ' + ( s.createAndEdit || 'Insert &amp; Edit with Elementor' ) +
							'</button>' +
						'</div>' +
					'</div>' +

				'</div>' +
			'</div>'
		);
	}

	/* ------------------------------------------------------------------ */
	/* AJAX: load templates                                                 */
	/* ------------------------------------------------------------------ */

	function loadTemplates( type, $popup ) {
		$popup.find( '.sits-tpl-grid' ).hide().empty();
		$popup.find( '.sits-tpl-nolibrary-wrap' ).hide().empty();
		$popup.find( '.sits-tpl-error' ).hide();
		$popup.find( '.sits-tpl-type-wrap' ).hide();   // hide dropdown while loading
		$popup.find( '.sits-tpl-loading' ).show();

		$.ajax( {
			url:  cfg.ajaxurl,
			type: 'POST',
			data: {
				action:        'sits_get_template_library',
				template_type: type,
				nonce:         cfg.nonce
			},
			success: function ( response ) {
				if ( response.success ) {
					displayTemplates( response.data.templates, $popup, response.data.show_empty_state );
				} else {
					showError( $popup, ( response.data && response.data.message ) ? response.data.message : ( s.errorLoading || 'Error loading templates.' ) );
				}
			},
			error: function () {
				showError( $popup, s.errorLoading || 'Error loading templates.' );
			}
		} );
	}

	/* ------------------------------------------------------------------ */
	/* Render templates                                                     */
	/* ------------------------------------------------------------------ */

	function displayTemplates( templates, $popup, showEmptyState ) {
		var $grid        = $popup.find( '.sits-tpl-grid' );
		var $noLibWrap   = $popup.find( '.sits-tpl-nolibrary-wrap' );
		var $loading     = $popup.find( '.sits-tpl-loading' );
		var $typeWrap    = $popup.find( '.sits-tpl-type-wrap' );
		var $skipBtn     = $popup.find( '.sits-tpl-skip-btn' );
		var $insertBtn   = $popup.find( '.sits-tpl-insert-btn' );
		var $footerActs  = $popup.find( '.sits-tpl-footer-actions' );

		// Archive and Single Page have NO template library at all —
		// show a centred info state with ONLY a "Create Template" button.
		// All other types keep the normal Skip + Insert footer buttons.
		var isNoLibraryType = ( currentType === 'archive' || currentType === 'single_page' || currentType === 'single_post' );

		// Always hide the no-library wrapper before deciding what to show
		$noLibWrap.hide().empty();
		$grid.hide().empty();

		/* ── Archive / Single Page: no template library ── */
		if ( isNoLibraryType ) {

			var noLibHtml =
				'<div class="sits-tpl-empty-state">' +
					'<svg class="sits-tpl-empty-icon" viewBox="0 0 200 200" fill="none" xmlns="http://www.w3.org/2000/svg">' +
						'<rect x="50" y="55" width="100" height="85" rx="8" fill="#dde8f0"/>' +
						'<rect x="62" y="68" width="76" height="9" rx="3" fill="#b0c8d8"/>' +
						'<rect x="62" y="83" width="54" height="6" rx="3" fill="#c8dce8"/>' +
						'<rect x="62" y="95" width="64" height="6" rx="3" fill="#c8dce8"/>' +
						'<rect x="62" y="107" width="44" height="6" rx="3" fill="#c8dce8"/>' +
						'<circle cx="100" cy="162" r="16" fill="#1c718a" opacity="0.18"/>' +
						'<path d="M92 162 L97 168 L109 155" stroke="#1c718a" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" fill="none"/>' +
					'</svg>' +
					'<h3>Start from a Blank Canvas</h3>' +
					'<p>No pre-built templates available for this type.<br>Open the Elementor editor to build your own from scratch.</p>' +
				'</div>';

			// Swap footer: hide Skip + Insert, show only "Create Template"
			$skipBtn.hide();
			$insertBtn.hide();
			if ( ! $footerActs.find( '.sits-tpl-create-blank-btn' ).length ) {
				$footerActs.append(
					'<button type="button" class="sits-tpl-btn sits-tpl-create-blank-btn">&#43;&nbsp;Create Template</button>'
				);
			}
			$footerActs.find( '.sits-tpl-create-blank-btn' ).show();

			$loading.fadeOut( 200, function () {
				$typeWrap.fadeIn( 200 );
				// Put the centered state inside the no-library wrapper (not the grid)
				$noLibWrap.html( noLibHtml ).fadeIn( 250 );
			} );
			return;
		}

		/* ── All other types: restore normal footer buttons ── */
		$footerActs.find( '.sits-tpl-create-blank-btn' ).hide();
		// Skip is shown/hidden by setFooterEmpty/setFooterSelected; restore base state
		$skipBtn.show();
		$insertBtn.show();

		/* ── Standard empty state (header/footer/404/single_post with no templates yet) ── */
		if ( showEmptyState || ! templates || 0 === templates.length ) {
			var emptyHtml =
				'<div class="sits-tpl-empty-state">' +
					'<svg class="sits-tpl-empty-icon" viewBox="0 0 200 200" fill="none" xmlns="http://www.w3.org/2000/svg">' +
						'<rect x="40" y="80" width="80" height="70" rx="6" fill="#ccd9de"/>' +
						'<rect x="48" y="88" width="64" height="8" rx="3" fill="#a8bec5"/>' +
						'<rect x="48" y="102" width="44" height="6" rx="3" fill="#c0d0d6"/>' +
						'<rect x="48" y="114" width="54" height="6" rx="3" fill="#c0d0d6"/>' +
						'<circle cx="140" cy="90" r="30" fill="#d8e8ec"/>' +
						'<path d="M126 90 Q132 78 140 82 Q148 70 154 84 Q164 80 162 92 Q168 100 158 104 Q156 112 148 108 Q142 116 134 110 Q126 114 124 104 Q114 100 126 90Z" fill="#b0c8d0"/>' +
						'<path d="M130 96 Q135 105 140 100 Q145 94 150 96" stroke="#7a9ea8" stroke-width="2.5" stroke-linecap="round" fill="none"/>' +
						'<circle cx="133" cy="90" r="3" fill="#7a9ea8"/>' +
						'<circle cx="147" cy="88" r="3" fill="#7a9ea8"/>' +
					'</svg>' +
					'<h3>Haven\'t Saved Templates Yet?</h3>' +
					'<p>This is where your templates should be. Design it. Save it. Reuse it.</p>' +
					'<button type="button" class="sits-tpl-skip-btn sits-tpl-btn">Start with a Blank Canvas</button>' +
				'</div>';

			$loading.fadeOut( 200, function () {
				$typeWrap.fadeIn( 200 );
				$grid.html( emptyHtml ).fadeIn( 250 );
			} );
			return;
		}

		$.each( templates, function ( i, tpl ) {
			$grid.append( buildTemplateCard( tpl ) );
		} );

		/* Hide loader → reveal dropdown + grid */
		$loading.fadeOut( 200, function () {
			$typeWrap.fadeIn( 200 );
			$grid.fadeIn( 250 );
		} );
	}

	function buildTemplateCard( tpl ) {
		var title       = tpl.title       || 'Untitled Template';
		var description = tpl.description || '';
		var isPro       = tpl.pro         || false;

		var proLabel = isPro ? '<span class="sits-tpl-pro-label">PRO</span>' : '';

		/* Use the thumbnail URL returned by PHP (resolved from JSON "thumbnail" field).
		   Fall back to the plugin placeholder image when no thumbnail is set. */
		var imgSrc = tpl.thumbnail ? tpl.thumbnail : ( cfg.placeholderImage || '' );
		var imgTag = '<img class="sits-tpl-card-img" src="' + imgSrc + '" alt="' + title + '" loading="lazy">';

		return $(
			'<div class="sits-tpl-card"' +
				' data-template-id="' + tpl.template_id + '"' +
				' data-pro="' + ( isPro ? '1' : '0' ) + '"' +
				' tabindex="0"' +
				' role="button"' +
				' aria-pressed="false"' +
				' aria-label="' + title + '">' +

				'<div class="sits-tpl-card-preview">' +
					imgTag +
					proLabel +
					'<span class="sits-tpl-card-check" aria-hidden="true"></span>' +
					'<div class="sits-tpl-card-overlay">' +
						'<button type="button" class="sits-tpl-select-btn">Use This</button>' +
					'</div>' +
				'</div>' +

				'<div class="sits-tpl-card-info">' +
					'<h3 class="sits-tpl-card-title">' + title + '</h3>' +
					( description ? '<p class="sits-tpl-card-desc">' + description + '</p>' : '' ) +
				'</div>' +
			'</div>'
		);
	}

	/* ------------------------------------------------------------------ */
	/* Error display                                                        */
	/* ------------------------------------------------------------------ */

	function showError( $popup, message ) {
		$popup.find( '.sits-tpl-loading' ).hide();
		$popup.find( '.sits-tpl-type-wrap' ).hide();
		$popup.find( '.sits-tpl-grid' ).hide();
		$popup.find( '.sits-tpl-error' ).html( '<p>' + message + '</p>' ).show();
	}

	/* ------------------------------------------------------------------ */
	/* Footer state helpers                                                 */
	/* ------------------------------------------------------------------ */

	function setFooterEmpty( $popup ) {
		$popup.find( '.sits-tpl-skip-btn' ).show();
		$popup.find( '.sits-tpl-insert-btn' )
			.prop( 'disabled', true )
			.removeClass( 'sits-tpl-insert-btn--ready' );
		$popup.find( '.sits-tpl-selected-label' ).text( '' );
	}

	function setFooterSelected( $popup, title ) {
		$popup.find( '.sits-tpl-skip-btn' ).hide();
		$popup.find( '.sits-tpl-insert-btn' )
			.prop( 'disabled', false )
			.addClass( 'sits-tpl-insert-btn--ready' );
		$popup.find( '.sits-tpl-selected-label' ).html( 'Selected: <strong>' + title + '</strong>' );
	}

	/* ------------------------------------------------------------------ */
	/* Button loading-state helpers                                         */
	/* ------------------------------------------------------------------ */

	/** Switch a footer button to spinner+text loading state. */
	function setBtnLoading( $btn, loadingText ) {
		$btn.prop( 'disabled', true )
			.addClass( 'sits-tpl-btn--loading' )
			.html( spinnerHtml() + '<span class="sits-tpl-btn-text">' + loadingText + '</span>' );
	}

	/** Switch a card "Use This" button to spinner-only loading state. */
	function setSelectBtnLoading( $btn ) {
		$btn.prop( 'disabled', true )
			.addClass( 'sits-tpl-btn--loading sits-tpl-select-btn--loading' )
			.html( spinnerHtml() );
	}

	/* ------------------------------------------------------------------ */
	/* Event delegation                                                     */
	/* ------------------------------------------------------------------ */

	function attachEvents( $popup ) {

		/* ── Close: × button ── */
		$popup.on( 'click', '.sits-tpl-modal-close', function () {
			closeAndSkip( $popup );
		} );

		/* ── Close: click outside modal ── */
		$popup.on( 'click', function ( e ) {
			if ( $( e.target ).is( '.sits-tpl-overlay' ) ) {
				closeAndSkip( $popup );
			}
		} );

		/* ── Skip — Start Blank ── */
		$popup.on( 'click', '.sits-tpl-skip-btn', function () {
			setBtnLoading( $( this ), s.skip || 'Skip — Start Blank' );
			closeAndSkip( $popup );
		} );

		/* ── Create Template (archive / single_page no-library state) ── */
		$popup.on( 'click', '.sits-tpl-create-blank-btn', function () {
			setBtnLoading( $( this ), 'Opening editor…' );
			closeAndSkip( $popup );
		} );

		/* ── Type dropdown: reload templates when switched ── */
		$popup.on( 'change', '.sits-tpl-type-select', function () {
			currentType        = $( this ).val();
			selectedTemplateId = '';

			$popup.find( '.sits-tpl-card' )
				.removeClass( 'sits-tpl-card--selected' )
				.attr( 'aria-pressed', 'false' );
			setFooterEmpty( $popup );

			loadTemplates( currentType, $popup );
		} );

		/* ── Card body click: toggle selection ── */
		$popup.on( 'click', '.sits-tpl-card', function ( e ) {
			if ( $( e.target ).closest( '.sits-tpl-select-btn' ).length ) {
				return;
			}

			var $card = $( this );
			var isPro = $card.data( 'pro' ) === 1;

			if ( isPro ) {
				// eslint-disable-next-line no-alert
				alert( 'This is a Pro template. Please upgrade to use it.' );
				return;
			}

			if ( $card.hasClass( 'sits-tpl-card--selected' ) ) {
				$card.removeClass( 'sits-tpl-card--selected' ).attr( 'aria-pressed', 'false' );
				selectedTemplateId = '';
				setFooterEmpty( $popup );
			} else {
				$popup.find( '.sits-tpl-card' )
					.removeClass( 'sits-tpl-card--selected' )
					.attr( 'aria-pressed', 'false' );
				$card.addClass( 'sits-tpl-card--selected' ).attr( 'aria-pressed', 'true' );
				selectedTemplateId = $card.data( 'template-id' );
				setFooterSelected( $popup, $card.find( '.sits-tpl-card-title' ).text() );
			}
		} );

		/* ── Keyboard: Enter / Space on card ── */
		$popup.on( 'keydown', '.sits-tpl-card', function ( e ) {
			if ( 13 === e.which || 32 === e.which ) {
				e.preventDefault();
				$( this ).trigger( 'click' );
			}
		} );

		/* ── "Use This" overlay button ── */
		$popup.on( 'click', '.sits-tpl-select-btn', function ( e ) {
			e.stopPropagation();

			var $selectBtn = $( this );
			var $card      = $selectBtn.closest( '.sits-tpl-card' );
			var isPro      = $card.data( 'pro' ) === 1;

			if ( isPro ) {
				// eslint-disable-next-line no-alert
				alert( 'This is a Pro template. Please upgrade to use it.' );
				return;
			}

			var templateId = $card.data( 'template-id' );
			var title      = $card.find( '.sits-tpl-card-title' ).text();

			/* Mark card selected */
			$popup.find( '.sits-tpl-card' )
				.removeClass( 'sits-tpl-card--selected' )
				.attr( 'aria-pressed', 'false' );
			$card.addClass( 'sits-tpl-card--selected' ).attr( 'aria-pressed', 'true' );
			selectedTemplateId = templateId;
			setFooterSelected( $popup, title );

			/* Show spinner on "Use This" button */
			setSelectBtnLoading( $selectBtn );

			/* Also show loading on the footer insert button */
			setBtnLoading( $popup.find( '.sits-tpl-insert-btn' ), s.inserting || 'Inserting template...' );

			doInsert( currentPostId, templateId, currentType, $popup, $popup.find( '.sits-tpl-insert-btn' ) );
		} );

		/* ── Insert & Edit with Elementor (footer button) ── */
		$popup.on( 'click', '.sits-tpl-insert-btn', function () {
			if ( ! selectedTemplateId ) {
				goToEditor();
				return;
			}
			var $btn = $( this );
			setBtnLoading( $btn, s.inserting || 'Inserting template...' );
			doInsert( currentPostId, selectedTemplateId, currentType, $popup, $btn );
		} );
	}

	/* ------------------------------------------------------------------ */
	/* AJAX: insert template                                               */
	/* ------------------------------------------------------------------ */

	function doInsert( postId, templateId, type, $popup, $btn ) {
		$.ajax( {
			url:  cfg.ajaxurl,
			type: 'POST',
			data: {
				action:        'sits_insert_template',
				post_id:       postId,
				template_id:   templateId,
				template_type: type,
				nonce:         cfg.nonce
			},
			success: function ( response ) {
				if ( response.success && response.data.elementor_url ) {
					closeNoRedirect( $popup );
					window.location.href = response.data.elementor_url;
				} else {
					restoreInsertBtn( $btn );
					restoreSelectBtn( $popup );
					// eslint-disable-next-line no-alert
					alert( ( response.data && response.data.message ) ? response.data.message : ( s.errorInserting || 'Error inserting template.' ) );
				}
			},
			error: function () {
				restoreInsertBtn( $btn );
				restoreSelectBtn( $popup );
				// eslint-disable-next-line no-alert
				alert( s.errorInserting || 'Error inserting template.' );
			}
		} );
	}

	function restoreInsertBtn( $btn ) {
		$btn.prop( 'disabled', false )
			.removeClass( 'sits-tpl-btn--loading' )
			.addClass( 'sits-tpl-insert-btn--ready' )
			.html( '<span class="sits-tpl-btn-check" aria-hidden="true">&#10003;</span> ' + ( s.createAndEdit || 'Insert &amp; Edit with Elementor' ) );
	}

	function restoreSelectBtn( $popup ) {
		$popup.find( '.sits-tpl-select-btn--loading' )
			.prop( 'disabled', false )
			.removeClass( 'sits-tpl-btn--loading sits-tpl-select-btn--loading' )
			.html( 'Use This' );
	}

	/* ------------------------------------------------------------------ */
	/* Navigation                                                           */
	/* ------------------------------------------------------------------ */

	function goToEditor() {
		if ( currentPostId ) {
			window.location.href = cfg.editUrlBase + currentPostId;
		}
	}

	/* ------------------------------------------------------------------ */
	/* Close helpers                                                        */
	/* ------------------------------------------------------------------ */

	function closeAndSkip( $popup ) {
		animateClose( $popup, goToEditor );
	}

	function closeNoRedirect( $popup ) {
		animateClose( $popup, null );
	}

	function animateClose( $popup, callback ) {
		$popup.removeClass( 'sits-tpl-overlay--visible' );
		setTimeout( function () {
			$popup.remove();
			if ( 'function' === typeof callback ) {
				callback();
			}
		}, 300 );
	}

}( jQuery ) );
