<?php
/**
 * Renders the inline JavaScript for the section builder modal and actions.
 */
function sifency_addons_render_section_builder_inline_js() {
	$nonce = wp_create_nonce( 'sifency_section_builder_nonce' );
	?>
	<script type="text/javascript">
	jQuery(document).ready(function ($) {
		'use strict';
		const SifencySectionBuilder = {
			modal: null,
			closeBtn: null,
			titleInput: null,
			saveBtn: null,
			editBtn: null,

			init() {
				this.modal = $('#sifency-new-section-modal');
				if (!this.modal.length) {
					console.warn('Sifency modal HTML not found in footer.');
					return;
				}

				this.closeBtn = this.modal.find('.sifency-modal-close');
				this.titleInput = this.modal.find('#sifency-section-title');
				this.saveBtn = this.modal.find('#sifency-save-section-draft');
				this.editBtn = this.modal.find('#sifency-create-section-elementor');

				this.bindEvents();
			},

			bindEvents() {
				$(document).on('click', '#sifency-open-new-section-modal', (e) => this.openModal(e));
				this.closeBtn.on('click', () => this.closeModal());
				this.modal.on('click', (e) => this.closeOnOverlay(e));
				this.saveBtn.on('click', (e) => this.createTemplate(e, 'draft'));
				this.editBtn.on('click', (e) => this.createTemplate(e, 'edit'));
				$(document).on('click', '.sifency-copy-btn', (e) => this.copyShortcode(e));
			},

			openModal(e) {
				e.preventDefault();
				this.modal.fadeIn(200).css('display', 'flex').addClass('is-visible');
				setTimeout(() => this.titleInput.trigger('focus'), 150);
			},

			closeModal() {
				this.modal.fadeOut(150, () => {
					this.modal.removeClass('is-visible');
					this.titleInput.val('');
					this.enableButtons();
				});
			},

			closeOnOverlay(e) {
				if ($(e.target).is(this.modal)) {
					this.closeModal();
				}
			},

			disableButtons(button) {
				this.saveBtn.prop('disabled', true);
				this.editBtn.prop('disabled', true);
				if (button) button.find('.spinner').addClass('is-active');
			},

			enableButtons() {
				this.saveBtn.prop('disabled', false);
				this.editBtn.prop('false', false);
				this.modal.find('.spinner').removeClass('is-active');
			},


			createTemplate(e, action) {
				e.preventDefault();

				const title = this.titleInput.val().trim();
				if (!title) {
					alert('Please enter a section name.');
					this.titleInput.trigger('focus');
					return;
				}

				const $button = $(e.currentTarget);
				this.disableButtons($button);

				$.ajax({
					url: ajaxurl,
					type: 'POST',
					dataType: 'json',
					data: {
						action: 'sifency_create_section_template',
						nonce: '<?php echo esc_js( $nonce ); ?>',
						title,
						redirect_action: action,
					},
					success: (res) => {
						if (res.success) {
							if (res.data.redirect_url) {
								window.location.href = res.data.redirect_url;
								return; 
							}

							if (res.data.new_row_html) {
								this.closeModal();
								
								const $tableBody = $('table.sifency-templates-table tbody');
								$tableBody.find('tr.no-items').remove();
								$(res.data.new_row_html)
									.prependTo($tableBody)
									.hide()
									.fadeIn(500);

							} else {
								alert('Draft saved, but an issue occurred updating the list. Reloading...');
								window.location.reload();
							}

						} else {
							alert('Error: ' + (res.data.message || 'An unknown error occurred.'));
							this.enableButtons();
						}
					},
					error: (jqXHR, textStatus) => {
						alert('An AJAX error occurred: ' + textStatus + '. Please check the console and try again.');
						console.error('Sifency AJAX Error:', textStatus, jqXHR.responseText);
						this.enableButtons();
					}
				});
			},

			copyShortcode(e) {
				e.preventDefault();
				const $btn = $(e.currentTarget);
				const shortcode = $btn.siblings('.sifency-shortcode-input').val();

				if (!shortcode) return;

				if (navigator.clipboard) {
					navigator.clipboard.writeText(shortcode).then(() => {
						this.showCopySuccess($btn);
					});
				} else {
					$btn.siblings('.sifency-shortcode-input').select();
					document.execCommand('copy');
					this.showCopySuccess($btn);
				}
			},

			showCopySuccess($btn) {
				const $icon = $btn.find('.dashicons');
				const originalColor = $btn.css('color');
				$icon.removeClass('dashicons-admin-page').addClass('dashicons-yes-alt');
				$btn.css('color', '#46b450');

				setTimeout(() => {
					$icon.removeClass('dashicons-yes-alt').addClass('dashicons-admin-page');
					$btn.css('color', originalColor);
				}, 2000);
			}
		};

		SifencySectionBuilder.init();
	});
	</script>
	<?php
}

add_action( 'admin_footer-sifency-addons_page_sifency-templates-shortcode', 'sifency_addons_render_section_builder_inline_js' );
?>