jQuery(document).ready(function($) {
	'use strict';

	// Cache selectors
	const $form          = $('#rtp-station-form');
	const $formTitle     = $('#rtp-form-title');
	const $submitBtn     = $('#rtp-submit-station-btn');
	const $cancelEditBtn = $('#rtp-cancel-edit-btn');
	const $stationIndex  = $('#rtp-station-index');
	const $stationBand   = $('#rtp-station-band');

	const $inputName     = $('#rtp-station-name');
	const $inputFreq     = $('#rtp-station-frequency');
	const $inputUrl      = $('#rtp-station-url');
	const $inputGenre    = $('#rtp-station-genre');
	const $inputImgUrl   = $('#rtp-station-image-url');
	const $logoPreview   = $('#rtp-logo-preview');
	const $inputBitrate  = $('#rtp-station-bitrate');

	const $searchInput   = $('#rtp-api-search-input');
	const $searchBtn     = $('#rtp-api-search-btn');
	const $searchResults = $('#rtp-search-results-box');

	const defaultLogo    = plugtuner_admin_vars.default_image || (plugtuner_admin_vars.plugin_url + 'public/images/tuner-image.jpg');
	const totalStationsCount = parseInt(plugtuner_admin_vars.total_stations_count) || 0;

	// Stream Preview Player
	let previewAudio = null;
	const $previewPlayBtn = $('#rtp-preview-play-btn');

	function stopPreview() {
		if (previewAudio) {
			previewAudio.pause();
			previewAudio = null;
		}
		$previewPlayBtn.removeClass('playing buffering')
			.html('<i class="fa-solid fa-play"></i> <span>Play Preview</span>');
	}

	$previewPlayBtn.on('click', function(e) {
		e.preventDefault();

		const streamUrl = $inputUrl.val().trim();
		if (!streamUrl) {
			alert('Please enter or select an Audio Stream URL first.');
			return;
		}

		// If already playing this stream, pause it
		if (previewAudio && previewAudio.src === streamUrl) {
			if (!previewAudio.paused) {
				stopPreview();
			} else {
				$previewPlayBtn.removeClass('playing').addClass('buffering')
					.html('<i class="fa-solid fa-spinner fa-spin"></i> <span>Buffering...</span>');
				previewAudio.play().catch(function(err) {
					alert('Playback failed: ' + err.message);
					stopPreview();
				});
			}
			return;
		}

		// Stop any existing preview
		stopPreview();

		// Start new preview
		$previewPlayBtn.addClass('buffering')
			.html('<i class="fa-solid fa-spinner fa-spin"></i> <span>Buffering...</span>');

		try {
			previewAudio = new Audio(streamUrl);
			previewAudio.addEventListener('canplay', function() {
				$previewPlayBtn.removeClass('buffering').addClass('playing')
					.html('<i class="fa-solid fa-stop"></i> <span>Stop Preview</span>');
			});
			previewAudio.addEventListener('playing', function() {
				$previewPlayBtn.removeClass('buffering').addClass('playing')
					.html('<i class="fa-solid fa-stop"></i> <span>Stop Preview</span>');
			});
			previewAudio.addEventListener('error', function() {
				alert('Playback failed. The stream might be offline, invalid, or blocked by CORS.');
				stopPreview();
			});
			previewAudio.play().catch(function(err) {
				alert('Playback failed: ' + err.message);
				stopPreview();
			});
		} catch (err) {
			alert('Playback failed: ' + err.message);
			stopPreview();
		}
	});

	$inputUrl.on('input', function() {
		$inputBitrate.val('');
		$('#rtp-station-quality-info').hide();
		stopPreview();
	});

	/* -------------------------------------------------------------
	 * 1. WordPress Media Library Uploader
	 * ------------------------------------------------------------- */
	let mediaFrame;

	$('#rtp-media-select-btn').on('click', function(e) {
		e.preventDefault();

		// If the frame already exists, re-open it.
		if (mediaFrame) {
			mediaFrame.open();
			return;
		}

		// Create the media frame.
		mediaFrame = wp.media({
			title: plugtuner_admin_vars.media_title,
			button: {
				text: plugtuner_admin_vars.media_button
			},
			multiple: false  // Set to true to allow multiple files to be selected
		});

		// When an image is selected in the media frame...
		mediaFrame.on('select', function() {
			// Get media attachment details
			const attachment = mediaFrame.state().get('selection').first().toJSON();

			// Populate input, attachment ID, and preview image
			$inputImgUrl.val(attachment.url);
			$('#rtp-station-image-id').val(attachment.id);
			$logoPreview.attr('src', attachment.url);
		});

		// Finally, open the modal
		mediaFrame.open();
	});

	// Clear logo selection
	$('#rtp-media-clear-btn').on('click', function(e) {
		e.preventDefault();
		$inputImgUrl.val('');
		$('#rtp-station-image-id').val('');
		$logoPreview.attr('src', defaultLogo);
	});

	/* -------------------------------------------------------------
	 * 2. API Global Radio Search
	 * ------------------------------------------------------------- */
	function performSearch() {
		const query = $searchInput.val().trim();
		const source = 'free';

		if (!query) {
			$searchResults.removeClass('active').html('');
			return;
		}

		$searchResults.addClass('active').html(
			'<div class="rtp-search-loading"><i class="fa-solid fa-spinner fa-spin"></i> Searching global database...</div>'
		);

		$.post(plugtuner_admin_vars.ajax_url, {
			action: 'plugtuner_search_stations',
			nonce: plugtuner_admin_vars.nonce,
			query: query,
			source: source
		}, function(response) {
			let data = response;
			if (typeof response === 'string') {
				try {
					const jsonStart = response.indexOf('{');
					if (jsonStart !== -1) {
						data = JSON.parse(response.substring(jsonStart));
					} else {
						data = { success: false, data: { message: response } };
					}
				} catch (err) {
					data = { success: false, data: { message: response } };
				}
			}

			if (data && data.success) {
				const results = data.data;
				$searchResults.html('');

				if (results.length === 0) {
					$searchResults.html(
						$('<div class="rtp-search-no-results"></div>').text('No stations found for "' + query + '"')
					);
					return;
				}

				results.forEach(function(station) {
					const logo = station.favicon ? station.favicon : defaultLogo;
					const $row = $('<div class="rtp-search-row"></div>');
					const bitrateText = station.bitrate ? ' | Quality: ' + station.bitrate + ' kbps' : '';

					// Build the row with text()/attr() so API data is never parsed as HTML.
					const $logo = $('<img class="rtp-search-logo">')
						.attr('src', logo)
						.on('error', function() {
							$(this).off('error').attr('src', defaultLogo);
						});
					const $meta = $('<div class="rtp-search-meta"></div>')
						.append($('<div class="rtp-search-name"></div>').text(station.name))
						.append($('<div class="rtp-search-desc"></div>').text(station.tagline + bitrateText));
					$row.append($logo).append($meta);

					// When a search result is clicked, autofill form
					$row.on('click', function() {
						stopPreview();
						$inputName.val(station.name);
						$inputUrl.val(station.url);
						$inputGenre.val(station.tagline.split('|').pop().trim());
						if (station.favicon) {
							$inputImgUrl.val(station.favicon);
							$logoPreview.attr('src', station.favicon);
						} else {
							$inputImgUrl.val('');
							$logoPreview.attr('src', defaultLogo);
						}
						
						if (station.bitrate && station.bitrate > 0) {
							$inputBitrate.val(station.bitrate);
							$('#rtp-quality-value').text(station.bitrate + ' kbps');
							$('#rtp-station-quality-info').css('display', 'inline-flex');
						} else {
							$inputBitrate.val('');
							$('#rtp-station-quality-info').hide();
						}

						// Close dropdown
						$searchResults.removeClass('active').html('');
						$searchInput.val('');
					});

					$searchResults.append($row);
				});
			} else {
				const errMsg = (data && data.data && data.data.message) ? data.data.message : 'Unknown search error.';
				$searchResults.html(
					$('<div class="rtp-search-no-results" style="color:#d63638;"></div>').text('Error: ' + errMsg)
				);
			}
		}).fail(function() {
			$searchResults.html('<div class="rtp-search-no-results" style="color:#d63638;">Connection failed.</div>');
		});
	}

	$searchInput.on('keypress', function(e) {
		if (e.which === 13) {
			e.preventDefault();
			performSearch();
		}
	});

	$searchBtn.on('click', function(e) {
		e.preventDefault();
		performSearch();
	});

	// Close search box clicking outside
	$(document).on('click', function(e) {
		if (!$(e.target).closest('.rtp-form-search-wrapper').length) {
			$searchResults.removeClass('active');
		}
	});

	/* -------------------------------------------------------------
	 * 3. Station CRUD Logic
	 * ------------------------------------------------------------- */
	
	// Add/Edit Form Submit
	$form.on('submit', function(e) {
		e.preventDefault();

		const indexVal  = $stationIndex.val();
		const name      = $inputName.val().trim();
		
		// Clean and parse frequency to handle commas used as decimal separators in some locales
		const freqRaw   = $inputFreq.val() ? $inputFreq.val().toString().replace(',', '.') : '';
		const frequency = parseFloat(freqRaw);
		
		const url       = $inputUrl.val().trim();
		const genre     = $inputGenre.val().trim();
		const image     = $inputImgUrl.val().trim();
		const imageId   = $('#rtp-station-image-id').val() || 0;
		const bitrate   = parseInt($inputBitrate.val()) || 0;

		$submitBtn.prop('disabled', true).find('span').text('Saving...');

		$.post(plugtuner_admin_vars.ajax_url, {
			action: 'plugtuner_save_station',
			nonce: plugtuner_admin_vars.nonce,
			index: indexVal,
			name: name,
			frequency: frequency,
			url: url,
			genre: genre,
			image: image,
			image_id: imageId,
			bitrate: bitrate,
			band: $stationBand.val()
		}, function(response) {
			let data = response;
			if (typeof response === 'string') {
				try {
					const jsonStart = response.indexOf('{');
					if (jsonStart !== -1) {
						data = JSON.parse(response.substring(jsonStart));
					} else {
						data = { success: false, data: { message: response } };
					}
				} catch (err) {
					data = { success: false, data: { message: response } };
				}
			}

			if (data && data.success) {
				window.location.reload();
			} else {
				const errMsg = (data && data.data && data.data.message) ? data.data.message : 'Unknown error occurred during save.';
				alert(errMsg);
				$submitBtn.prop('disabled', false).find('span').text(indexVal === '' ? 'Add Station' : 'Save Changes');
			}
		}).fail(function() {
			alert('Connection failed. Please try again.');
			$submitBtn.prop('disabled', false).find('span').text(indexVal === '' ? 'Add Station' : 'Save Changes');
		});
	});

	// Trigger Edit Mode
	$('.rtp-edit-station-btn').on('click', function(e) {
		e.preventDefault();
		stopPreview();
		$('#rtp-station-quality-info').hide();
		const station = $(this).data('station');
		const index = $(this).data('index');

		// Populate inputs
		$stationIndex.val(index);
		$inputName.val(station.name);
		$inputFreq.val(station.frequency);
		$inputUrl.val(station.url);
		$inputGenre.val(station.genre);
		$inputImgUrl.val(station.image);
		$('#rtp-station-image-id').val(station.image_id || '');
		$inputBitrate.val(station.bitrate || 0);

		if (station.bitrate && station.bitrate > 0) {
			$('#rtp-quality-value').text(station.bitrate + ' kbps');
			$('#rtp-station-quality-info').css('display', 'inline-flex');
		} else {
			$('#rtp-station-quality-info').hide();
		}

		const logo = station.resolved_image ? station.resolved_image : defaultLogo;
		$logoPreview.attr('src', logo);

		// Switch UI to edit mode
		$formTitle.text('Edit Radio Station: ' + station.name);
		$submitBtn.removeClass('button-primary').addClass('button-primary').find('span').text('Save Changes');
		$submitBtn.find('i').removeClass('fa-square-plus').addClass('fa-circle-check');
		$cancelEditBtn.show();

		// Scroll to form nicely
		$('html, body').animate({
			scrollTop: $form.offset().top - 100
		}, 300);
	});

	// Cancel Edit Mode
	$cancelEditBtn.on('click', function(e) {
		e.preventDefault();
		resetForm();
	});

	function resetForm() {
		stopPreview();
		$('#rtp-station-quality-info').hide();
		$stationIndex.val('');
		$inputBitrate.val('');
		$form[0].reset();
		$('#rtp-station-image-id').val('');
		$logoPreview.attr('src', defaultLogo);

		$formTitle.text('Add Custom Radio Station');
		$submitBtn.find('span').text('Add Station');
		$submitBtn.find('i').removeClass('fa-circle-check').addClass('fa-square-plus');
		$cancelEditBtn.hide();
	}

	// Delete Station
	$('.rtp-delete-station-btn').on('click', function(e) {
		e.preventDefault();
		const index = $(this).data('index');
		const band  = $(this).data('band') || 'FM';

		if (confirm('Are you sure you want to delete this radio station from your dial?')) {
			const $row = $(this).closest('tr');
			$row.css('opacity', '0.5');

			$.post(plugtuner_admin_vars.ajax_url, {
				action: 'plugtuner_delete_station',
				nonce: plugtuner_admin_vars.nonce,
				index: index,
				band: band
			}, function(response) {
				let data = response;
				if (typeof response === 'string') {
					try {
						const jsonStart = response.indexOf('{');
						if (jsonStart !== -1) {
							data = JSON.parse(response.substring(jsonStart));
						} else {
							data = { success: false, data: { message: response } };
						}
					} catch (err) {
						data = { success: false, data: { message: response } };
					}
				}

				if (data && data.success) {
					window.location.reload();
				} else {
					const errMsg = (data && data.data && data.data.message) ? data.data.message : 'Unknown error occurred during delete.';
					alert(errMsg);
					$row.css('opacity', '1');
				}
			}).fail(function() {
				alert('Connection failed.');
				$row.css('opacity', '1');
			});
		}
	});

	/* -------------------------------------------------------------
	 * 4. Design Theme Customizer & Live Typography Preview
	 * ------------------------------------------------------------- */
	const $bgInput = $('.rtp-customize-form-table input[type="color"]').first();
	const $accentInput = $('.rtp-customize-form-table input[type="color"]').last();
	const $opacityInput = $('.rtp-customize-form-table input[type="range"]').first();
	const $blurInput = $('.rtp-customize-form-table input[type="range"]').last();
	const $fontFamilySelect = $('.rtp-customize-form-table select');
	const $fontSizeInput = $('.rtp-font-size-row input[type="range"]');
	const $customFontUrlInput = $('.rtp-custom-font-row input[type="text"]');
	
	const $previewCard = $('.rtp-digital-tuner-preview-card');
	const $previewDigits = $('.rtp-digital-tuner-preview-digits');
	const $previewSuffix = $('.rtp-digital-tuner-preview-suffix');

	// Determine active design type (light or dark)
	const designType = $bgInput.attr('id') && $bgInput.attr('id').indexOf('dark') !== -1 ? 'dark' : 'light';

	function hexToRgb(hex) {
		const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		return result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : { r: 255, g: 255, b: 255 };
	}

	function updateLivePreview() {
		if ($previewCard.length === 0) return;

		const bgColor = $bgInput.val();
		const accentColor = $accentInput.val();
		const opacityVal = parseFloat($opacityInput.val()) / 100;
		const blurVal = parseInt($blurInput.val());
		const fontFamily = $fontFamilySelect.val();
		const fontSize = parseInt($fontSizeInput.val());
		const customFontUrl = $customFontUrlInput.val();

		// Update colors
		$previewDigits.css('color', accentColor);
		$previewSuffix.css('color', accentColor);

		// Update card background, opacity and blur
		const rgb = hexToRgb(bgColor);
		if (designType === 'dark') {
			$previewCard.css({
				'background-color': 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + opacityVal + ')',
				'backdrop-filter': 'blur(' + blurVal + 'px)',
				'-webkit-backdrop-filter': 'blur(' + blurVal + 'px)'
			});
		} else {
			$previewCard.css({
				'background-color': 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + opacityVal + ')',
				'backdrop-filter': 'blur(' + blurVal + 'px)',
				'-webkit-backdrop-filter': 'blur(' + blurVal + 'px)'
			});
		}

		// Update font size
		$previewDigits.css('font-size', fontSize + 'px');

		// Update font family
		if (fontFamily === 'default') {
			$previewDigits.css('font-family', "'Outfit', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif");
		} else if (fontFamily === 'Arial, sans-serif' || fontFamily === 'Courier New, monospace') {
			$previewDigits.css('font-family', fontFamily);
		} else if (fontFamily === 'Orbitron' || fontFamily === 'Roboto Mono') {
			$previewDigits.css('font-family', "'" + fontFamily + "', sans-serif");
		} else if (fontFamily === 'custom') {
			if (customFontUrl) {
				// Inject or update dynamic font-face block
				let $style = $('#rtp-preview-custom-font');
				if ($style.length === 0) {
					$style = $('<style id="rtp-preview-custom-font"></style>').appendTo('head');
				}
				$style.html(
					'@font-face {\n' +
					"  font-family: 'plugtuner_preview_font';\n" +
					"  src: url('" + customFontUrl + "') format('truetype');\n" +
					'  font-weight: 800;\n' +
					'}'
				);
				$previewDigits.css('font-family', "'plugtuner_preview_font', sans-serif");
			} else {
				$previewDigits.css('font-family', "'Outfit', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif");
			}
		}
	}

	// Update Hex color text label on color change dynamically
	$('.rtp-customize-form-table input[type="color"]').on('input', function() {
		$(this).closest('.rtp-color-input-wrapper').find('.rtp-color-hex-label').text($(this).val());
		updateLivePreview();
	});

	// Update Opacity percentage or Blur px text label on range change dynamically
	$('.rtp-customize-form-table input[type="range"]').on('input', function() {
		const val = $(this).val();
		const id = $(this).attr('id');
		let unit = '%';
		if (id.indexOf('blur') !== -1) {
			unit = 'px';
		} else if (id.indexOf('font_size') !== -1) {
			unit = 'px';
		}
		$(this).closest('.rtp-range-input-wrapper').find('.rtp-range-value-label').text(val + unit);
		updateLivePreview();
	});

	// Handle dropdown value changes to toggle custom font upload row
	$fontFamilySelect.on('change', function() {
		const val = $(this).val();
		if (val === 'custom') {
			$('.rtp-custom-font-row').fadeIn(200);
		} else {
			$('.rtp-custom-font-row').fadeOut(200);
		}
		updateLivePreview();
	});

	// Custom TTF Font File Media Library Uploader
	let fontFrame;
	$('#rtp-font-select-btn').on('click', function(e) {
		e.preventDefault();

		if (fontFrame) {
			fontFrame.open();
			return;
		}

		fontFrame = wp.media({
			title: 'Select or Upload TTF Font File',
			button: {
				text: 'Use this font'
			},
			library: {
				type: 'application/x-font-ttf,font/ttf,application/x-font-truetype'
			},
			multiple: false
		});

		fontFrame.on('select', function() {
			const attachment = fontFrame.state().get('selection').first().toJSON();
			
			// Validate file extension
			if (attachment.url && !attachment.url.toLowerCase().endsWith('.ttf')) {
				alert('Please select a valid TrueType font (.ttf) file.');
				return;
			}

			$customFontUrlInput.val(attachment.url);
			$('#rtp-font-clear-btn').fadeIn(200);
			updateLivePreview();
		});

		fontFrame.open();
	});

	// Remove Custom Font File
	$('#rtp-font-clear-btn').on('click', function(e) {
		e.preventDefault();
		$customFontUrlInput.val('');
		$(this).fadeOut(200);
		updateLivePreview();
	});

	// Reset Design Settings to factory defaults
	$('#rtp-reset-design-btn').on('click', function(e) {
		e.preventDefault();
		if (confirm('Are you sure you want to reset all design settings for this theme to factory defaults?')) {
			const bgId = $bgInput.attr('id');
			if (bgId) {
				const prefix = bgId.replace('_bg_color', '');
				const isDark = prefix.indexOf('dark') !== -1;
				const defaultBg = isDark ? '#0b0b0c' : '#ffffff';

				$('#' + prefix + '_bg_color').val(defaultBg).trigger('input');
				$('#' + prefix + '_accent_color').val('#ff6f00').trigger('input');
				$('#' + prefix + '_opacity').val(100).trigger('input');
				$('#' + prefix + '_blur').val(20).trigger('input');
				$('#' + prefix + '_digit_font_family').val('default').trigger('change');
				$('#' + prefix + '_digit_font_size').val(65).trigger('input');
				$customFontUrlInput.val('');
				$('#rtp-font-clear-btn').hide();
			}
			updateLivePreview();
		}
	});

	// Trigger initial preview load
	updateLivePreview();
});
