/**
 * BubblaV Chat Widget - Admin JavaScript
 *
 * @package BubblaV_Chat
 */

/* global bubblavAdmin */

(function ($) {
	'use strict';

	// On document ready
	$(document).ready(function () {
		initAdmin();
	});

	/**
	 * Initialize admin functionality
	 */
	function initAdmin() {
		// Handle OAuth callback
		handleOAuthCallback();

		// Handle connection status
		updateConnectionStatus();

		// Add event listeners
		bindEvents();
	}

	/**
	 * Handle OAuth callback from URL parameters
	 */
	function handleOAuthCallback() {
		const urlParams = new URLSearchParams(window.location.search);
		const websiteId = urlParams.get('website_id');
		const status = urlParams.get('status');
		const state = urlParams.get('state');
		const error = urlParams.get('error');

		if (error) {
			showError(error);
			// Clean URL
			cleanUrl();
			return;
		}

		if (status === 'connected' && websiteId) {
			// Auto-submit the connection form
			submitConnectionForm(websiteId, state);
		}
	}

	/**
	 * Submit connection form programmatically
	 */
	function submitConnectionForm(websiteId, state) {
		const $form = $('<form>', {
			'method': 'POST',
			'action': bubblavAdmin.ajaxUrl
		});

		$form.append($('<input>', {
			'type': 'hidden',
			'name': 'action',
			'value': 'bubblav_save_settings'
		}));

		$form.append($('<input>', {
			'type': 'hidden',
			'name': 'bubblav_nonce',
			'value': bubblavAdmin.nonce
		}));

		$form.append($('<input>', {
			'type': 'hidden',
			'name': 'bubblav_website_id',
			'value': websiteId
		}));

		if (state) {
			$form.append($('<input>', {
				'type': 'hidden',
				'name': 'state',
				'value': state
			}));
		}

		$form.appendTo('body').submit();
	}

	/**
	 * Update connection status UI
	 */
	function updateConnectionStatus() {
		if (bubblavAdmin.isConnected) {
			showConnectedState();
		} else {
			showDisconnectedState();
		}
	}

	/**
	 * Show connected state
	 */
	function showConnectedState() {
		// Add connected class to body
		$('body').addClass('bubblav-connected');

		// Show success message if just connected
		const urlParams = new URLSearchParams(window.location.search);
		if (urlParams.get('bubblav_success') === '1') {
			showSuccess('Connected successfully!');
			cleanUrl();
		}
	}

	/**
	 * Show disconnected state
	 */
	function showDisconnectedState() {
		// Add disconnected class to body
		$('body').addClass('bubblav-disconnected');
	}

	/**
	 * Bind event listeners
	 */
	function bindEvents() {
		// Connect button
		$('.bubblav-connect-btn').on('click', function (e) {
			// Button submits form directly, no JS needed
		});

		// Disconnect button
		$('.bubblav-disconnect-btn').on('click', function (e) {
			if (!confirm('Are you sure you want to disconnect? This will remove the chat widget from your site.')) {
				e.preventDefault();
				return false;
			}
		});

		// Refresh connection button (if exists)
		$('.bubblav-refresh-btn').on('click', function (e) {
			e.preventDefault();
			refreshConnection();
		});
	}

	/**
	 * Refresh connection status
	 */
	function refreshConnection() {
		// Show loading state
		$('.bubblav-refresh-btn').prop('disabled', true).text('Refreshing...');

		// Ajax call to refresh
		$.ajax({
			url: bubblavAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'bubblav_refresh_connection',
				nonce: bubblavAdmin.nonce
			},
			success: function (response) {
				if (response.success) {
					showSuccess('Connection refreshed successfully');
					setTimeout(function () {
						location.reload();
					}, 1000);
				} else {
					showError(response.data || 'Failed to refresh connection');
				}
			},
			error: function () {
				showError('Failed to refresh connection');
			},
			complete: function () {
				$('.bubblav-refresh-btn').prop('disabled', false).text('Refresh');
			}
		});
	}

	/**
	 * Show success message
	 */
	function showSuccess(message) {
		const $notice = $('<div>', {
			'class': 'notice notice-success is-dismissible',
			'html': '<p>' + message + '</p>'
		});

		$('.wrap').prepend($notice);

		// Auto-hide after 5 seconds
		setTimeout(function () {
			$notice.fadeOut(function () {
				$(this).remove();
			});
		}, 5000);

		// Make dismissible
		$notice.on('click', '.notice-dismiss', function () {
			$notice.fadeOut(function () {
				$(this).remove();
			});
		});
	}

	/**
	 * Show error message
	 */
	function showError(message) {
		const $notice = $('<div>', {
			'class': 'notice notice-error is-dismissible',
			'html': '<p><strong>Error:</strong> ' + message + '</p>'
		});

		$('.wrap').prepend($notice);

		// Make dismissible
		$notice.on('click', '.notice-dismiss', function () {
			$notice.fadeOut(function () {
				$(this).remove();
			});
		});
	}

	/**
	 * Clean URL parameters
	 */
	function cleanUrl() {
		const url = new URL(window.location);
		url.searchParams.delete('website_id');
		url.searchParams.delete('status');
		url.searchParams.delete('state');
		url.searchParams.delete('error');
		url.searchParams.delete('bubblav_success');
		window.history.replaceState({}, '', url);
	}

})(jQuery);
