/**
 * Zoomeet Recording Archive JavaScript
 *
 * Handles information modal functionality for recording archive display.
 *
 * @package Zoomeet
 * @since   1.0.0
 */

(function ($) {
	'use strict';

	/**
	 * Recording Archive Modal Handler
	 */
	var ZmeetRecordingArchive = {

		/**
		 * Initialize the modal functionality.
		 */
		init: function () {
			this.bindEvents();
		},

		/**
		 * Bind event listeners.
		 */
		bindEvents: function () {
			var self = this;

			// Recording card click - open modal
			$(document).on('click', '.zmeet-recording-card', function (e) {
				e.preventDefault();

				var $card = $(this);

				// Don't open if processing
				if ($card.find('.zmeet-recording-processing-badge').length > 0) {
					return;
				}

				var playUrl = $card.data('play-url');
				var downloadUrl = $card.data('download-url');
				var shareUrl = $card.data('share-url');
				var passcode = $card.data('passcode');
				var title = $card.data('title');
				var date = $card.data('date');
				var duration = $card.data('duration');

				self.openModal(playUrl, downloadUrl, shareUrl, passcode, title, date, duration);
			});

			// Featured card click - open modal
			$(document).on('click', '.zmeet-featured-card', function (e) {
				e.preventDefault();

				var $card = $(this);
				var playUrl = $card.data('play-url');
				var downloadUrl = $card.data('download-url');
				var shareUrl = $card.data('share-url');
				var passcode = $card.data('passcode');
				var title = $card.data('title');
				var date = $card.data('date');
				var duration = $card.data('duration');

				self.openModal(playUrl, downloadUrl, shareUrl, passcode, title, date, duration);
			});

			// Archive sidebar item click - open modal
			$(document).on('click', '.zmeet-archive-sidebar-item', function (e) {
				e.preventDefault();

				var $item = $(this);
				var playUrl = $item.data('play-url');
				var downloadUrl = $item.data('download-url');
				var shareUrl = $item.data('share-url');
				var passcode = $item.data('passcode');
				var title = $item.data('title');
				var date = $item.data('date');
				var duration = $item.data('duration');

				self.openModal(playUrl, downloadUrl, shareUrl, passcode, title, date, duration);
			});

			// Close button click
			$(document).on('click', '.zmeet-recording-modal-close', function (e) {
				e.preventDefault();
				self.closeModal();
			});

			// Overlay click - close modal
			$(document).on('click', '.zmeet-recording-modal-overlay', function (e) {
				e.preventDefault();
				self.closeModal();
			});

			// ESC key - close modal
			$(document).on('keydown', function (e) {
				if (e.keyCode === 27 && $('.zmeet-recording-modal').is(':visible')) {
					self.closeModal();
				}
			});

			// Prevent clicks inside modal content from closing
			$(document).on('click', '.zmeet-recording-modal-content', function (e) {
				e.stopPropagation();
			});

			// Copy passcode to clipboard
			$(document).on('click', '.zmeet-recording-copy-passcode', function (e) {
				e.preventDefault();
				e.stopPropagation();
				var $btn = $(this);
				var passcode = $btn.closest('.zmeet-recording-modal-passcode').find('.zmeet-recording-modal-passcode-value').text();
				if (!passcode) return;

				var copySuccess = function () {
					$btn.find('.zmeet-copy-icon').hide();
					$btn.find('.zmeet-check-icon').show();
					$btn.find('.zmeet-copy-text').text('Copied!');
					$btn.addClass('copied');
					setTimeout(function () {
						$btn.find('.zmeet-copy-icon').show();
						$btn.find('.zmeet-check-icon').hide();
						$btn.find('.zmeet-copy-text').text('Copy');
						$btn.removeClass('copied');
					}, 2000);
				};

				if (navigator.clipboard && window.isSecureContext) {
					navigator.clipboard.writeText(passcode).then(copySuccess);
				} else {
					// Fallback for HTTP sites
					var textarea = document.createElement('textarea');
					textarea.value = passcode;
					textarea.style.position = 'fixed';
					textarea.style.opacity = '0';
					document.body.appendChild(textarea);
					textarea.select();
					try {
						document.execCommand('copy');
						copySuccess();
					} catch (err) {
						// Silent fail
					}
					document.body.removeChild(textarea);
				}
			});
		},

		/**
		 * Open the information modal.
		 *
		 * @param {string} playUrl Zoom play URL.
		 * @param {string} downloadUrl Zoom download URL.
		 * @param {string} shareUrl Zoom share URL (bypasses passcode).
		 * @param {string} passcode Recording passcode.
		 * @param {string} title Recording title.
		 * @param {string} date Recording date.
		 * @param {string} duration Recording duration.
		 */
		openModal: function (playUrl, downloadUrl, shareUrl, passcode, title, date, duration) {
			var $modal = $('.zmeet-recording-modal');

			// Set title
			$modal.find('.zmeet-recording-modal-title').text(title);

			// Set date
			$modal.find('.zmeet-recording-modal-date').text(date);

			// Set duration
			$modal.find('.zmeet-recording-modal-duration').text(duration);

			// Set button URLs - use specific class names
			var $watchBtn = $modal.find('.zmeet-recording-watch-btn');
			var $downloadBtn = $modal.find('.zmeet-recording-download-btn');

			// For "Watch on Zoom" button: prefer share_url (bypasses passcode)
			// Fallback order: shareUrl > playUrl > downloadUrl
			var watchUrl = shareUrl || playUrl || downloadUrl;
			var downloadOnlyUrl = downloadUrl || playUrl;

			// Set watch button URL - always show if we have any URL
			if (watchUrl) {
				$watchBtn.attr('href', watchUrl).show();
			} else {
				$watchBtn.hide();
			}

			// Set download button URL - always show if we have any URL
			if (downloadOnlyUrl) {
				$downloadBtn.attr('href', downloadOnlyUrl).show();
			} else {
				$downloadBtn.hide();
			}

			// Show passcode if available AND show_passcode setting is enabled
			var $passcodeSection = $modal.find('.zmeet-recording-modal-passcode');
			var showPasscodeSetting = $modal.data('show-passcode') === true || $modal.data('show-passcode') === 'true';
			if (passcode && showPasscodeSetting) {
				$passcodeSection.find('.zmeet-recording-modal-passcode-value').text(passcode);
				$passcodeSection.show();
			} else {
				$passcodeSection.hide();
			}

			// Show modal with flex display
			$modal.css('display', 'flex').hide().fadeIn(300);

			// Trap focus within modal
			this.trapFocus($modal);

			// Prevent body scroll
			$('body').css('overflow', 'hidden');
		},

		/**
		 * Close the modal.
		 */
		closeModal: function () {
			var $modal = $('.zmeet-recording-modal');

			// Hide modal
			$modal.fadeOut(300);

			// Restore body scroll
			$('body').css('overflow', '');
		},

		/**
		 * Trap focus within the modal for accessibility.
		 *
		 * @param {jQuery} $container Modal container element.
		 */
		trapFocus: function ($container) {
			var focusableElements = $container.find('button, a, [tabindex]:not([tabindex="-1"])');
			var firstFocusable = focusableElements.first();
			var lastFocusable = focusableElements.last();

			// Focus first element
			firstFocusable.focus();

			// Handle tab key
			$container.off('keydown.focustrap').on('keydown.focustrap', function (e) {
				if (e.keyCode !== 9) return; // Not tab key

				if (e.shiftKey) {
					// Shift + Tab
					if (document.activeElement === firstFocusable[0]) {
						e.preventDefault();
						lastFocusable.focus();
					}
				} else {
					// Tab
					if (document.activeElement === lastFocusable[0]) {
						e.preventDefault();
						firstFocusable.focus();
					}
				}
			});
		}
	};

	/**
	 * Initialize on document ready.
	 */
	$(document).ready(function () {
		ZmeetRecordingArchive.init();
	});

})(jQuery);
