/**
 * IGIT Related Posts – Admin JavaScript
 *
 * Handles:
 *  - Settings sections DOM restructuring (wrap sections in cards with icons)
 *  - wp.media image picker for the default/fallback image field
 */
/* global wp */
( function ( $ ) {
	'use strict';

	// ── Theme definitions ────────────────────────────────────────────────────
	var IGIT_THEMES = [
		// ─ Dark ──────────────────────────────────────────────────────────────
		{ id: 'indigo',   name: 'Indigo Night',  from: '#4f46e5', to: '#06b6d4' },
		{ id: 'violet',   name: 'Violet Dusk',   from: '#7c3aed', to: '#ec4899' },
		{ id: 'ocean',    name: 'Ocean Blue',    from: '#0369a1', to: '#06b6d4' },
		{ id: 'emerald',  name: 'Emerald Dark',  from: '#059669', to: '#84cc16' },
		{ id: 'sunset',   name: 'Sunset',        from: '#dc2626', to: '#f59e0b' },
		{ id: 'rose',     name: 'Rose Noir',     from: '#be123c', to: '#f472b6' },
		{ id: 'gold',     name: 'Gold Rush',     from: '#b45309', to: '#fbbf24' },
		{ id: 'aurora',   name: 'Aurora',        from: '#7c3aed', to: '#14b8a6' },
		{ id: 'cherry',   name: 'Cherry Dark',   from: '#9f1239', to: '#f43f5e' },
		{ id: 'nordic',   name: 'Nordic',        from: '#4c6a8a', to: '#88c0d0' },
		// ─ Light ─────────────────────────────────────────────────────────────
		{ id: 'sky',      name: 'Sky Light',     from: '#0284c7', to: '#14b8a6', light: true },
		{ id: 'blossom',  name: 'Blossom',       from: '#e11d48', to: '#f97316', light: true },
		{ id: 'sage',     name: 'Sage Light',    from: '#16a34a', to: '#84cc16', light: true },
		{ id: 'lavender', name: 'Lavender',      from: '#7c3aed', to: '#d946ef', light: true },
		{ id: 'sand',     name: 'Sandy Shores',  from: '#c2410c', to: '#f59e0b', light: true },
		{ id: 'mint',     name: 'Mint Fresh',    from: '#0d9488', to: '#06b6d4', light: true },
		{ id: 'powder',   name: 'Powder Blue',   from: '#3b82f6', to: '#6366f1', light: true },
		{ id: 'coral',    name: 'Coral Glow',    from: '#f4511e', to: '#fbbf24', light: true },
		{ id: 'citrus',   name: 'Citrus',        from: '#65a30d', to: '#ca8a04', light: true },
		{ id: 'quartz',   name: 'Rose Quartz',   from: '#db2777', to: '#9333ea', light: true },
	];
	var IGIT_THEME_KEY = 'igit_rpwt_theme';
	var IGIT_TAB_KEY   = 'igit_rpwt_tab';

	// ── Slugify a string for use as a URL hash ───────────────────────────────
	function slugify( str ) {
		return str.toLowerCase().replace( /[^a-z0-9]+/g, '-' ).replace( /^-+|-+$/g, '' );
	}

	// ── Apply a theme ─────────────────────────────────────────────────────────
	function applyTheme( id, persist ) {
		document.body.setAttribute( 'data-igit-theme', id );
		$( '.igit-rpwt-theme-swatch' ).removeClass( 'is-active' );
		$( '.igit-rpwt-theme-swatch[data-theme="' + id + '"]' ).addClass( 'is-active' );
		try { localStorage.setItem( IGIT_THEME_KEY, id ); } catch ( e ) {}
		// Persist to usermeta so the preference survives across browsers/devices.
		if ( persist && typeof igitRpwtAdmin !== 'undefined' ) {
			$.post( igitRpwtAdmin.ajaxUrl, {
				action:      'igit_rpwt_save_theme',
				theme:       id,
				_ajax_nonce: igitRpwtAdmin.nonce,
			} );
		}
	}

	// ── Build and insert the theme switcher (sidebar card) ───────────────────
	function renderThemeSwitcher() {
		var $slot = $( '.igit-rpwt-theme-slot' );
		if ( ! $slot.length || $slot.find( '.igit-rpwt-theme-grid' ).length ) { return; }

		var darkSwatches  = '';
		var lightSwatches = '';

		$.each( IGIT_THEMES, function ( i, theme ) {
			var grad      = 'linear-gradient(135deg,' + theme.from + ' 0%,' + theme.to + ' 100%)';
			var tickColor = theme.light ? '#0f172a' : '#fff';
			var extraCls  = theme.light ? ' is-light-swatch' : '';
			var swatch =
				'<button type="button" class="igit-rpwt-theme-swatch' + extraCls + '"' +
				' data-theme="' + theme.id + '" style="--swatch-gradient:' + grad + '"' +
				' title="' + theme.name + '" aria-label="' + theme.name + '">' +
				'<span class="igit-rpwt-swatch-tick">' +
				'<svg width="9" height="7" viewBox="0 0 10 8" fill="none">' +
				'<path d="M1 4l3 3 5-6" stroke="' + tickColor + '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
				'</svg></span></button>';
			if ( theme.light ) {
				lightSwatches += swatch;
			} else {
				darkSwatches += swatch;
			}
		} );

		var $grid = $(
			'<div class="igit-rpwt-theme-grid">' +
			'<div class="igit-rpwt-theme-group">' +
			'<div class="igit-rpwt-theme-group-label">Dark</div>' +
			'<div class="igit-rpwt-swatches">' + darkSwatches + '</div>' +
			'</div>' +
			'<div class="igit-rpwt-theme-group">' +
			'<div class="igit-rpwt-theme-group-label">Light</div>' +
			'<div class="igit-rpwt-swatches">' + lightSwatches + '</div>' +
			'</div>' +
			'</div>'
		);

		$slot.append( $grid );

		$slot.on( 'click', '.igit-rpwt-theme-swatch', function () {
			applyTheme( $( this ).data( 'theme' ), true );
		} );
	}

	// ── Section icons (Display, Thumbnail, Query, Cache, Performance, Analytics) ──
	var sectionIcons = [
		'<svg width="16" height="16" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="1.5" y="2.5" width="15" height="10" rx="2" stroke="currentColor" stroke-width="1.5"/><path d="M6 15h6M9 12.5V15" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',
		'<svg width="16" height="16" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="1.5" y="1.5" width="15" height="15" rx="2" stroke="currentColor" stroke-width="1.5"/><circle cx="6.5" cy="6.5" r="1.5" stroke="currentColor" stroke-width="1.5"/><path d="M2 14l4-4 3 3 2.5-2.5L16 15" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
		'<svg width="16" height="16" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M3 5h12M3 9h8M3 13h5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><circle cx="14.5" cy="13" r="2" stroke="currentColor" stroke-width="1.5"/></svg>',
		'<svg width="16" height="16" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M9 1.5A7.5 7.5 0 1 1 1.5 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M1.5 4V9H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
		'<svg width="16" height="16" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M3 13L7 8l3 3 2.5-3.5L15 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="15" cy="5" r="1.5" fill="currentColor"/></svg>',
		'<svg width="16" height="16" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="10" width="3" height="6" rx="1" stroke="currentColor" stroke-width="1.5"/><rect x="7.5" y="6.5" width="3" height="9.5" rx="1" stroke="currentColor" stroke-width="1.5"/><rect x="13" y="2" width="3" height="14" rx="1" stroke="currentColor" stroke-width="1.5"/></svg>',
	];

	// ── Build vertical tab layout for settings sections ───────────────────────
	function structureSections() {
		var $main = $( '.igit-rpwt-settings-main' );
		if ( ! $main.length ) { return; }

		var $form     = $main.find( 'form' );
		var iconIndex = 0;
		var tabs      = []; // { btnEl: rawDOMNode, panelEl: rawDOMNode }

		// Detach p.submit BEFORE scanning sections — the last section's nextUntil()
		// would otherwise capture it (since Integrations has no form-table sibling).
		var $submit = $form.find( 'p.submit' ).detach();

		var $tabNav    = $( '<nav class="igit-rpwt-tab-nav" aria-label="Settings sections"></nav>' );
		var $tabPanels = $( '<div class="igit-rpwt-tab-panels"></div>' );

		$form.children( 'h2' ).each( function ( i ) {
			var $h2             = $( this );
			var $table          = $h2.nextUntil( 'h2' ).filter( 'table.form-table' ).first();
			// Collect section-callback output (between this h2 and the next h2 or form-table).
			var $sectionContent = $h2.nextUntil( 'h2, table.form-table' );
			// Skip only if the section is truly empty (no callback output AND no fields).
			if ( ! $table.length && ! $sectionContent.length ) { return; }

			var title = $.trim( $h2.text() );
			var icon  = sectionIcons[ iconIndex ] || sectionIcons[ 0 ];
			iconIndex++;

			// Detect Pro-only sections by the presence of the upgrade notice.
			var isProSection = (
				$sectionContent.filter( '.igit-rpwt-pro-notice' ).length ||
				$sectionContent.find( '.igit-rpwt-pro-notice' ).length
			);
			var proTagHtml   = isProSection
				? '<span class="igit-rpwt-tab-pro-tag">PRO</span>'
				: '';

			var $btn = $(
				'<button type="button" class="igit-rpwt-tab-btn' + ( isProSection ? ' has-pro-tag' : '' ) + '">' +
				'<span class="igit-rpwt-tab-icon">' + icon + '</span>' +
				'<span class="igit-rpwt-tab-label">' + $( '<span>' ).text( title ).html() + '</span>' +
				proTagHtml +
				'</button>'
			);
			$tabNav.append( $btn );

			var $panel = $( '<div class="igit-rpwt-tab-panel"></div>' );
			$panel.append(
				'<div class="igit-rpwt-panel-header">' +
				'<span class="igit-rpwt-panel-icon">' + icon + '</span>' +
				'<span class="igit-rpwt-panel-title">' + $( '<span>' ).text( title ).html() + '</span>' +
				proTagHtml +
				'<input type="submit" class="igit-rpwt-panel-save-btn" value="Save Settings">' +
				'</div>'
			);
			if ( $sectionContent.length ) {
				$panel.append( $sectionContent.detach() );
			}
			if ( $table.length ) {
				$panel.append( $table.detach() );
			}
			$tabPanels.append( $panel );
			$h2.remove();

			// Keep raw DOM references – avoids jQuery/WP timing issues in handlers
			tabs.push( { btnEl: $btn[ 0 ], panelEl: $panel[ 0 ], slug: slugify( title ) } );
		} );

		if ( ! tabs.length ) {
			// No tabs built — restore the submit button to the form and bail.
			if ( $submit.length ) { $submit.appendTo( $form ); }
			return;
		}

		var $tabsWrap = $( '<div class="igit-rpwt-tabs"></div>' )
			.append( $tabNav )
			.append( $tabPanels );

		$form.append( $tabsWrap );
		if ( $submit.length ) {
			var $footer = $( '<div class="igit-rpwt-form-footer"></div>' );
			$footer.appendTo( $form );
			$submit.appendTo( $footer );
		}

		// Activate using native classList on raw DOM nodes – no jQuery involved
		function activateTab( index ) {
			for ( var j = 0; j < tabs.length; j++ ) {
				tabs[ j ].btnEl.classList.toggle( 'is-active', j === index );
				tabs[ j ].panelEl.classList.toggle( 'is-active', j === index );
			}
		}

		// native addEventListener on raw DOM nodes – immune to jQuery/WP delegation issues
		for ( var k = 0; k < tabs.length; k++ ) {
			( function ( idx ) {
				tabs[ idx ].btnEl.addEventListener( 'click', function () {
					activateTab( idx );
					try { localStorage.setItem( IGIT_TAB_KEY, tabs[ idx ].slug ); } catch ( e ) {}
					history.replaceState( null, '', location.pathname + location.search + '#' + tabs[ idx ].slug );
				} );
			} )( k );
		}

		// Resolve initial tab: URL hash → localStorage → first tab
		function findBySlug( slug ) {
			for ( var m = 0; m < tabs.length; m++ ) {
				if ( tabs[ m ].slug === slug ) { return m; }
			}
			return -1;
		}

		var initialIdx = 0;
		var hashSlug   = ( window.location.hash || '' ).replace( /^#/, '' );
		if ( hashSlug ) {
			var hi = findBySlug( hashSlug );
			if ( hi !== -1 ) { initialIdx = hi; }
		} else {
			try {
				var storedSlug = localStorage.getItem( IGIT_TAB_KEY );
				if ( storedSlug ) {
					var si = findBySlug( storedSlug );
					if ( si !== -1 ) { initialIdx = si; }
				}
			} catch ( e ) {}
		}
		activateTab( initialIdx );
	}

	// ── Conditional field visibility ─────────────────────────────────────────
	// ── Relate-by description ─────────────────────────────────────────────────
	function setupRelateByDescription() {
		var descs = {
			both:     'Matches posts sharing at least one category <em>or</em> tag with the current post.<br>Best general-purpose choice — recommended for most sites.',
			category: 'Finds posts that belong to <em>the same category</em> as the current post.<br>Good for structured, category-heavy sites where categories define topics.',
			tag:      'Finds posts that share <em>at least one tag</em> with the current post.<br>Works best when posts are consistently and meaningfully tagged.',
			fulltext: 'Uses MySQL <em>FULLTEXT search</em> on post title &amp; content for semantic similarity.<br>Requires a FULLTEXT index on wp_posts; falls back to keyword search if absent.',
			author:   'Returns other posts written by <em>the same author</em> as the current post.<br>Useful for author-focused blogs and multi-author publications.',
			series:   'Groups posts into a <em>manually curated series</em> using a custom taxonomy.<br>Assign posts to a series via the Series meta box in the post editor.',
		};
		var $select = $( '#relate_by' );
		var $desc   = $( '#igit-rpwt-relate-by-desc' );
		if ( ! $select.length || ! $desc.length ) { return; }
		function update() { $desc.html( descs[ $select.val() ] || '' ); }
		$select.on( 'change', update );
		update();
	}

	function setupConditionalFields() {
		// excerpt_length row: visible only when show_excerpt is checked.
		var $excerptRow = $( '#excerpt_length' ).closest( 'tr' );
		var $excerptToggle = $( '#show_excerpt' );
		function syncExcerpt() {
			$excerptRow.toggle( $excerptToggle.is( ':checked' ) );
		}
		if ( $excerptToggle.length ) {
			syncExcerpt();
			$excerptToggle.on( 'change', syncExcerpt );
		}

		// grid_columns rows: visible only when layout === 'grid'.
		var $colRows = $( '#grid_columns_desktop, #grid_columns_tablet, #grid_columns_mobile' ).closest( 'tr' );
		var $layoutSelect = $( '#layout' );
		function syncColumns() {
			$colRows.toggle( 'grid' === $layoutSelect.val() );
		}
		if ( $layoutSelect.length ) {
			syncColumns();
			$layoutSelect.on( 'change', syncColumns );
		}
	}

	// ── Layout preview ────────────────────────────────────────────────────────
	function setupLayoutPreview() {
		var $select = $( '#layout' );
		if ( ! $select.length ) { return; }

		var card = '<div style="flex:1;border:1px solid #ddd;border-radius:4px;overflow:hidden;min-width:0">' +
			'<div style="background:#e8e8e8;height:40px"></div>' +
			'<div style="padding:5px">' +
			'<div style="background:#d0d0d0;height:7px;border-radius:2px;margin-bottom:3px"></div>' +
			'<div style="background:#e0e0e0;height:6px;border-radius:2px;width:65%"></div>' +
			'</div></div>';

		var row = function ( thumb ) {
			return '<div style="display:flex;align-items:center;gap:6px;border-bottom:1px solid #f0f0f0;padding:5px 0">' +
				( thumb ? '<div style="width:36px;height:27px;background:#e0e0e0;border-radius:3px;flex-shrink:0"></div>' : '' ) +
				'<div style="flex:1"><div style="background:#d0d0d0;height:7px;border-radius:2px;width:90%"></div></div>' +
				'</div>';
		};

		var col = function ( h1, h2 ) {
			return '<div style="flex:1;display:flex;flex-direction:column;gap:6px">' +
				'<div style="border:1px solid #ddd;border-radius:4px;height:' + h1 + 'px;background:#f5f5f5"></div>' +
				'<div style="border:1px solid #ddd;border-radius:4px;height:' + h2 + 'px;background:#f5f5f5"></div>' +
				'</div>';
		};

		var pill = function ( text ) {
			return '<span style="background:#e0e0e0;border-radius:20px;padding:3px 10px;font-size:11px">' + text + '</span>';
		};

		var carouselCard = '<div style="flex:0 0 38%;border:1px solid #ddd;border-radius:4px;overflow:hidden">' +
			'<div style="background:#e8e8e8;height:40px"></div>' +
			'<div style="padding:4px"><div style="background:#d0d0d0;height:6px;border-radius:2px"></div></div></div>';

		var previews = {
			grid:     '<div style="display:flex;gap:8px">' + card + card + card + '</div>',
			list:     '<div>' + row( true ) + row( true ) + row( true ) + '</div>',
			compact:  '<div>' + row( false ) + row( false ) + row( false ) + '</div>',
			masonry:  '<div style="display:flex;gap:8px;align-items:flex-start">' + col( 65, 45 ) + col( 50, 60 ) + col( 70, 40 ) + '</div>',
			carousel: '<div style="display:flex;align-items:center;gap:6px">' +
				'<div style="width:22px;height:22px;border:1px solid #bbb;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;color:#555;flex-shrink:0">&#8249;</div>' +
				'<div style="flex:1;display:flex;gap:6px;overflow:hidden">' + carouselCard + carouselCard +
				'<div style="flex:0 0 38%;border:1px solid #ddd;border-radius:4px;overflow:hidden;opacity:0.35">' +
				'<div style="background:#e8e8e8;height:40px"></div>' +
				'<div style="padding:4px"><div style="background:#d0d0d0;height:6px;border-radius:2px"></div></div></div>' +
				'</div>' +
				'<div style="width:22px;height:22px;border:1px solid #bbb;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;color:#555;flex-shrink:0">&#8250;</div>' +
				'</div>',
			chip:     '<div style="display:flex;flex-wrap:wrap;gap:6px">' +
				pill( 'Post title 1' ) + pill( 'Post title 2' ) + pill( 'Another post' ) +
				pill( 'Related article' ) + pill( 'Fifth post' ) +
				'</div>',
		};

		// Per-layout hint: recommended post count range + key behaviour notes.
		var hints = {
			grid:     'Best for 3–12 posts. Uniform card grid — column count is set by the Grid Columns fields below.',
			list:     'Best for 3–8 posts. Thumbnail + title displayed in a horizontal row per post.',
			compact:  'Best for 5–10 posts. Text-only list — thumbnails are hidden.',
			masonry:  'Best for 6–12 posts. Variable-height cards in a Pinterest-style column layout.',
			carousel: 'Best for 4–10 posts. Horizontal scroll strip — visitors swipe or use the arrow buttons.',
			chip:     'Best for 5–20 posts. Compact inline pills (title only) — thumbnails are ignored.',
		};

		var $preview = $( '<div class="igit-rpwt-layout-preview" style="margin-top:8px;padding:10px 12px;border:1px dashed #ccc;border-radius:4px;background:#fafafa"></div>' );
		var $hint    = $( '#igit-rpwt-layout-hint' );
		$select.closest( 'td' ).append( $preview );

		function updatePreview() {
			var val = $select.val() || 'grid';
			$preview.html( previews[ val ] || '' );
			$hint.text( hints[ val ] || '' );
		}

		$select.on( 'change', updatePreview );
		updatePreview();
	}

	// ── AJAX Save ────────────────────────────────────────────────────────
	function ajaxSave() {
		var $form = $( '.igit-rpwt-settings-main form' );
		if ( ! $form.length || typeof igitRpwtAdmin === 'undefined' ) { return; }

		var $btns = $( '.igit-rpwt-panel-save-btn, .igit-rpwt-form-footer input[type="submit"], .igit-rpwt-floating-save' );
		$btns.prop( 'disabled', true ).addClass( 'is-saving' );

		var data = $form.serialize() + '&action=igit_rpwt_save_settings&_ajax_nonce=' + igitRpwtAdmin.nonce;

		$.post( igitRpwtAdmin.ajaxUrl, data )
			.done( function ( response ) {
				if ( response && response.success ) {
					showToast( ( response.data && response.data.message ) || igitRpwtAdmin.i18n.saved, 'success' );
				} else {
					showToast( ( response.data && response.data.message ) || igitRpwtAdmin.i18n.error, 'error' );
				}
			} )
			.fail( function () {
				showToast( igitRpwtAdmin.i18n.error, 'error' );
			} )
			.always( function () {
				$btns.prop( 'disabled', false ).removeClass( 'is-saving' );
			} );
	}

	function showToast( message, type ) {
		var $toast = $( '#igit-rpwt-toast' );
		if ( ! $toast.length ) {
			$toast = $( '<div id="igit-rpwt-toast" role="status" aria-live="polite"></div>' ).appendTo( 'body' );
		}
		clearTimeout( $toast.data( 'timer' ) );
		$toast
			.attr( 'data-type', type || 'success' )
			.text( message )
			.removeClass( 'is-hiding' )
			.addClass( 'is-visible' );
		$toast.data( 'timer', setTimeout( function () {
			$toast.addClass( 'is-hiding' );
			setTimeout( function () { $toast.removeClass( 'is-visible is-hiding' ); }, 350 );
		}, 3000 ) );
	}

	$( document ).ready( function () {
		structureSections();
		setupConditionalFields();
		setupRelateByDescription();
		setupLayoutPreview();
		renderThemeSwitcher();

		// Sticky save bar — appended at the bottom of the main settings column.
		var $bar      = $( '<div class="igit-rpwt-sticky-save-bar"></div>' ).appendTo( '.igit-rpwt-settings-main' );
		var $floatSave = $( '<button type="button" class="igit-rpwt-floating-save">Save Settings</button>' ).appendTo( $bar );
		$floatSave.on( 'click', function () { ajaxSave(); } );

		// Move any WP/third-party admin notices out of the hero into our slot.
		// setTimeout(0) ensures this runs after wp-admin/js/common.js has already
		// relocated notices to after the first h1 (which sits inside our hero).
		setTimeout( function () {
			var $slot = $( '#igit-rpwt-notices' );
			if ( $slot.length ) {
				$( '.igit-rpwt-settings-wrap .notice, .igit-rpwt-settings-wrap .updated, .igit-rpwt-settings-wrap .error, .igit-rpwt-settings-wrap .settings-error' )
					.not( '.inline' )
					.appendTo( $slot );
			}
		}, 0 );
		// Server-stored usermeta takes priority (cross-device sync),
		// then fall back to localStorage (legacy / not yet synced), then the default.
		var savedTheme = ( typeof igitRpwtAdmin !== 'undefined' && igitRpwtAdmin.theme )
			? igitRpwtAdmin.theme
			: 'indigo';
		try { savedTheme = localStorage.getItem( IGIT_THEME_KEY ) || savedTheme; } catch ( e ) {}
		applyTheme( savedTheme );

		// Intercept form submit for AJAX save.
		$( '.igit-rpwt-settings-main' ).on( 'submit', 'form', function ( e ) {
			if ( typeof igitRpwtAdmin !== 'undefined' && igitRpwtAdmin.ajaxUrl ) {
				e.preventDefault();
				ajaxSave();
			}
		} );

		// ── Clear analytics ───────────────────────────────────────────────────
		$( document ).on( 'click', '#igit-rpwt-clear-analytics', function () {
			if ( typeof igitRpwtAdmin === 'undefined' ) { return; }
			if ( ! window.confirm( igitRpwtAdmin.i18n.clearConfirm ) ) { return; }

			var $btn     = $( this );
			var origText = $btn.text().trim();
			$btn.prop( 'disabled', true ).text( igitRpwtAdmin.i18n.clearing );

			$.post( igitRpwtAdmin.ajaxUrl, {
				action: 'igit_rpwt_clear_analytics',
				nonce:  igitRpwtAdmin.clearNonce,
			} )
			.done( function ( response ) {
				if ( response && response.success ) {
					$( '#igit-rpwt-data-size-val' ).text( response.data.sizeLabel );
					$( '#igit-rpwt-data-row-count' ).text( '(0 rows)' );
					showToast( response.data.message || igitRpwtAdmin.i18n.cleared, 'success' );
					setTimeout( function () { location.reload(); }, 1500 );
				} else {
					showToast( ( response && response.data && response.data.message ) || igitRpwtAdmin.i18n.error, 'error' );
					$btn.prop( 'disabled', false ).text( origText );
				}
			} )
			.fail( function () {
				showToast( igitRpwtAdmin.i18n.error, 'error' );
				$btn.prop( 'disabled', false ).text( origText );
			} );
		} );

		// Signal JS is active – CSS uses this to hide the fallback footer button.
		document.body.classList.add( 'igit-rpwt-js-loaded' );
	} );

	// ── wp.media image picker ─────────────────────────────────────────────────
	var mediaFrame;

	$( document ).on( 'click', '.igit-rpwt-upload-btn', function ( e ) {
		e.preventDefault();

		var targetSelector = $( this ).data( 'target' );
		var $input         = $( targetSelector );

		// Reuse existing frame if already opened.
		if ( mediaFrame ) {
			mediaFrame.open();
			return;
		}

		mediaFrame = wp.media( {
			title:    'Select or Upload a Fallback Image',
			button:   { text: 'Use this image' },
			multiple: false,
			library:  { type: 'image' },
		} );

		mediaFrame.on( 'select', function () {
			var attachment = mediaFrame.state().get( 'selection' ).first().toJSON();
			$input.val( attachment.url );

			// Live-preview: update or create the preview <img>.
			var $preview = $input.closest( '.igit-rpwt-image-picker' ).find( '.igit-rpwt-preview' );
			if ( $preview.length ) {
				$preview.attr( 'src', attachment.url );
			} else {
				$( '<img>' )
					.attr( { src: attachment.url, class: 'igit-rpwt-preview' } )
					.css( { maxWidth: '120px', marginTop: '6px', borderRadius: '4px', display: 'block' } )
					.insertAfter( $( this ) );
			}
		}.bind( this ) ); // preserve correct `this` context

		mediaFrame.open();
	} );

} )( jQuery );
