(function ($) {
	// Use localized settings first, fallback to wpApiSettings, then hardcoded path
	const KAVEH_API_URL = (typeof kavehLibrarySettings !== 'undefined' && kavehLibrarySettings.apiUrl) 
		? kavehLibrarySettings.apiUrl 
		: (typeof wpApiSettings !== 'undefined' && wpApiSettings.root) 
			? wpApiSettings.root + 'kaveh-library/templates'
			: '/wp-json/kaveh-library/templates';

	const addCustomButton = () => {
		const $container = window.elementor?.$previewContents?.find('.elementor-add-new-section');
		if (!$container || !$container.length) return;
		if ($container.find('.custom-kaveh-elementor-button').length > 0) return;

		const $customButton = $(`
			<button type="button" class="elementor-add-section-area-button custom-kaveh-elementor-button" title="کتابخانه کاوه" aria-label="کتابخانه کاوه" style="padding:9px;background-color:#a058e03d;">
			  <img src="https://s21.uupload.ir/files/moein757/kaveh-logo.svg" alt="Kaveh Icon" />
			</button>
		`);
		$customButton.on('click', openKavehPopup);
		$container.find('.elementor-add-template-button').after($customButton);
	};

	const openKavehPopup = () => {
		const $popup = $('#kaveh-template-library-modal');
		const $popupContent = $popup.find('.dialog-lightbox-widget-content');
		const $loader = $popup.find('.kaveh-template-library-loading');
		const $content = $('#kaveh-template-library-content');
		const $tabNavContainer = $('#kaveh-template-library-header-menu');
		const $btn = $('.custom-kaveh-elementor-button');
		const btnOffset = $btn.offset() || { left: 360 };
		const adjustedTop = $(window).scrollTop() + 18;

		$popupContent.css({
			top: `${adjustedTop}px`,
			left: `${btnOffset.left}px`,
			position: 'absolute',
			zIndex: 999999,
			transform: 'none'
		});

		$('#kaveh-template-library-preview').hide();
		$('.kaveh-header-preview-tools').hide();
		$('.elementor-templates-modal__header__logo-area').show();
		$content.show();
		$tabNavContainer.show();
		$popup.fadeIn(200);
		$loader.show();
		$content.empty();
		$tabNavContainer.empty();

		if (!$popup.find('.kaveh-header-preview-tools').length) {
			const $tools = $(`
				<div class="kaveh-header-preview-tools elementor-templates-modal__header__items-area" style="display:none;">
					<div class="elementor-templates-modal__header__item kaveh-preview-back" style="cursor:pointer;">
						<i class="eicon-angle-left"></i><span style="margin-right:5px;">بازگشت</span>
					</div>
					<div class="elementor-templates-modal__header__item kaveh-preview-live-wrapper">
						<a class="elementor-template-library-template-action kaveh-preview-live" href="#" target="_blank">
							<i class="eicon-editor-external-link"></i> <span class="elementor-button-title">مشاهده زنده</span>
						</a>
					</div>
					<div class="elementor-templates-modal__header__item kaveh-preview-insert-wrapper">
						<a class="elementor-template-library-template-action elementor-button kaveh-preview-insert" href="#">
							<i class="eicon-file-download"></i> <span class="elementor-button-title">درج</span>
						</a>
					</div>
				</div>
			`);
			$popup.find('.elementor-templates-modal__header').append($tools);
		}

		$.ajax({
			url: KAVEH_API_URL,
			method: 'GET',
			success: function (data) {
				if (!data?.taxonomies?.layout_tabs) {
					console.error('❌ داده‌ی لازم موجود نیست');
					$loader.hide();
					$content.html('<p style="padding:20px;">مشکلی در دریافت داده‌ها وجود دارد</p>');
					return;
				}

				const tabs = data.taxonomies.layout_tabs;
				const layouts = data.layouts;
				const $layoutsContainer = $('<div class="kaveh-layouts" style="padding:10px;display:flex;flex-wrap:wrap;gap:20px;"></div>');

				for (const tabKey in tabs) {
					const tab = tabs[tabKey];
					const $tabBtn = $(`<div class="elementor-component-tab elementor-template-library-menu-item" data-tab="${tabKey}">${tab.title}</div>`);
					$tabBtn.on('click', () => {
						$('.elementor-template-library-menu-item').removeClass('elementor-active');
						$tabBtn.addClass('elementor-active');
						renderLayouts(tabKey, layouts, $layoutsContainer);
					});
					$tabNavContainer.append($tabBtn);
				}

				const firstTab = Object.keys(tabs)[0];
				$tabNavContainer.find(`[data-tab="${firstTab}"]`).addClass('elementor-active');
				renderLayouts(firstTab, layouts, $layoutsContainer);
				$content.append($layoutsContainer);
				$loader.hide();
			},
			error: function (xhr) {
				console.error('❌ خطا در دریافت اطلاعات:', xhr);
				$loader.hide();
				$content.html('<p style="padding:20px;">دریافت اطلاعات با خطا مواجه شد</p>');
			}
		});
	};

	const renderLayouts = (tabKey, layouts, $container) => {
		$container.empty();

		const filteredLayouts = Object.values(layouts).filter(layout =>
			layout.category && layout.category.includes(tabKey)
		);

		if (!filteredLayouts.length) {
			$container.html('<p>هیچ آیتمی یافت نشد.</p>');
			return;
		}

		filteredLayouts.forEach(layout => {
			const $card = $(`
				<div class="kaveh-layout-card">
					<div class="kaveh-layout-thumb" data-json="${layout.json_url}" data-demo="${layout.live_demo_url}" data-preview="${layout.preview?.url}">
						<img src="${layout.thumbnail}" alt="${layout.title}" />
						<div class="kaveh-layout-zoom-icon"><i class="eicon-search"></i></div>
					</div>
					<h4>${layout.title}</h4>
					<div class="kaveh-layout-card-footer">
						<a href="${layout.live_demo_url}" target="_blank" style="margin-left:10px;">مشاهده زنده</a>
						<button class="kaveh-insert-btn" data-json="${layout.json_url}">درج</button>
					</div>
				</div>
			`);
			

			$card.find('.kaveh-insert-btn').on('click', function () {
				const jsonUrl = $(this).data('json');
				importKavehTemplate(jsonUrl);
			});

			$card.find('.kaveh-layout-thumb').on('click', function () {
				const preview = $(this).data('preview'); // 👈 آدرس تصویر پیش‌نمایش
				const demo = $(this).data('demo');
				const json = $(this).data('json');
			
				$('.kaveh-preview-image').attr('src', preview); // 👈 نمایش تصویر بزرگ‌تر
				$('.kaveh-preview-live').attr('href', demo);
				$('.kaveh-preview-insert').data('json', json);
			
				$('#kaveh-template-library-content').hide();
				$('#kaveh-template-library-header-menu').hide();
				$('.elementor-templates-modal__header__logo-area').hide();
				$('#kaveh-template-library-preview').fadeIn(200);
				$('.kaveh-header-preview-tools').fadeIn(200);
			});
			

			$container.append($card);
		});
	};
	const importKavehTemplate = (jsonUrl) => {
		const $popup = $('#kaveh-template-library-modal');
		const $loader = $popup.find('.kaveh-template-library-loading');
		const $content = $popup.find('#kaveh-template-library-content');
		const $preview = $popup.find('#kaveh-template-library-preview');
		const $tools = $popup.find('.kaveh-header-preview-tools');
	
		// نمایش لودر و مخفی‌سازی محتوا
		$content.hide();
		$preview.hide();
		$tools.hide();
		$loader.show();
	
		elementorCommon.ajax.addRequest('get_kaveh_template_data', {
			data: {
				editor_post_id: elementor.config.document.id,
				template_id: jsonUrl
			},
			success: function (data) {
				$e.run('document/elements/import', {
					model: elementor.elementsModel,
					data: data,
					options: { edit: true }
				});
	
				elementor.notifications.showToast({ message: '✅ قالب با موفقیت درج شد!' });
				$popup.fadeOut(200);
				$loader.hide();
			},
			error: function () {
				alert('❌ درج قالب با خطا مواجه شد.');
				$loader.hide();
				$content.show();
				$tools.show();
			}
		});
	};
	
	
	

	const setupPopupClose = () => {
		$(document).on('click', '.kaveh-template-library-close', function () {
			$('#kaveh-template-library-modal').fadeOut(200);
		});

		$(document).on('click', '.kaveh-preview-back', function () {
			$('#kaveh-template-library-preview').hide();
			$('.kaveh-header-preview-tools').hide();
			$('.elementor-templates-modal__header__logo-area').show();
			$('#kaveh-template-library-header-menu').show();
			$('#kaveh-template-library-content').fadeIn(200);
		});

		$(document).on('click', '.kaveh-preview-insert', function () {
			const jsonUrl = $(this).data('json');
			importKavehTemplate(jsonUrl);
		});
	};

	$(window).on('elementor:init', function () {
		elementor.on('preview:loaded', function () {
			const interval = setInterval(() => {
				const $found = window.elementor?.$previewContents?.find('.elementor-add-template-button');
				if ($found && $found.length) {
					clearInterval(interval);
					addCustomButton();
					setupPopupClose();
				}
			}, 300);
		});
	});


	$(`<style>
		.kaveh-layout-card {
			border: 1px solid #ccc;
			padding: 10px;
			width: 200px;
			position: relative;
		}
		.kaveh-layout-thumb {
			position: relative;
			overflow: hidden;
			cursor: pointer;
		}
		.kaveh-layout-thumb img {
			width: 100%;
			height: auto;
			border-radius: 4px;
			transition: filter 0.3s ease;
		}
		.kaveh-layout-thumb:hover img {
			filter: brightness(0.5);
		}
		.kaveh-layout-zoom-icon {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			color: #fff;
			font-size: 28px;
			opacity: 0;
			transition: opacity 0.3s ease;
		}
		.kaveh-layout-thumb:hover .kaveh-layout-zoom-icon {
			opacity: 1;
		}
		.kaveh-layout-card-footer {
			display: flex;
			justify-content: space-between;
			margin-top: 10px;
		}
		.kaveh-layout-card-footer a,
		.kaveh-layout-card-footer button {
			font-size: 12px;
			background: none;
			border: none;
			cursor: pointer;
			color: #4c4cff;
		}
		.kaveh-layout-card-footer button {
			color: #fff;
			background: #6200ea;
			padding: 5px 10px;
			border-radius: 4px;
		}
		#kaveh-template-library-preview {
			display: none;
			width: 100%;
		}
		.kaveh-preview-image-wrapper {
			width: 100%;
			text-align: center;
			background: #f8f8f8;
			padding: 30px;
			box-sizing: border-box;
		}
		.kaveh-preview-image-wrapper img {
			width: 100%;
			height: auto;
			border-radius: 4px;
			box-shadow: 0 0 10px rgba(0,0,0,0.1);
			object-fit: cover !important;
			max-height:unset !important;
		}
			.elementor-templates-modal__header__item {
				direction: ltr;
			}
			.elementor-templates-modal__header__item {
			margin: 10px;
			}
	</style>`).appendTo('head');

})(jQuery);
