/**
 * Settings Page JavaScript
 * Displays subscription info, quota, and settings
 * Handles authentication (login/register)
 */

(function ($) {
	"use strict";

	const STW_Settings = {
		initialized: false,

		init: function () {
			// Always check auth status on init to get latest connection status
			checkAuthStatus();

			// Only setup once
			if (!this.initialized) {
				const $authSection = $("#auth-section");
				const $settingsContent = $("#settings-content");

				if ($authSection.length) {
					$authSection.show();
				}
				if ($settingsContent.length) {
					$settingsContent.hide();
				}

				setupEventListeners();
				this.initialized = true;
			}
		},
	};

	function setupEventListeners() {
		// Auth tab switching
		$(document)
			.off("click", ".stw-auth-tab")
			.on("click", ".stw-auth-tab", function () {
				const tab = $(this).data("tab");

				// Update active tab styling
				$(".stw-auth-tab").removeClass("active");
				$(this).addClass("active");

				// Hide all forms
				$(".stw-auth-form").hide();

				// Show selected form
				$("#" + tab + "-form").show();
			});

		// Form submissions
		$(document)
			.off("submit", "#login-form")
			.on("submit", "#login-form", handleLogin);
		$(document)
			.off("submit", "#register-form")
			.on("submit", "#register-form", handleRegister);

		// Settings page buttons
		$(document)
			.off("click", "#upgrade-plan-btn")
			.on("click", "#upgrade-plan-btn", upgradePlan);
		$(document)
			.off("click", "#purchase-credits-btn")
			.on("click", "#purchase-credits-btn", upgradePlan);
		$(document)
			.off("click", "#go-to-dashboard-btn")
			.on("click", "#go-to-dashboard-btn", goToSTWDashboard);
		$(document)
			.off("click", "#link-privacy")
			.on("click", "#link-privacy", goToSTWPrivacy);
		$(document)
			.off("click", "#link-about")
			.on("click", "#link-about", goToSTWAbout);
		$(document)
			.off("click", "#link-contact")
			.on("click", "#link-contact", goToSTWContact);
	}

	function checkAuthStatus() {
		const $settingsPage = $("#stw-settings-page");
		if (!$settingsPage.length) {
			return;
		}

		$.ajax({
			url: scanshowAdmin.restUrl + "connection",
			method: "GET",
			success: function (response) {
				if (response && response.connected) {
					$("#auth-section").hide();
					$("#settings-content").show();
					loadUserData();
				} else {
					$("#auth-section").show();
					$("#settings-content").hide();
				}
			},
			error: function () {
				$("#auth-section").show();
				$("#settings-content").hide();
			},
		});
	}

	/**
	 * Handle login form submission
	 */
	function handleLogin(e) {
		e.preventDefault();

		const email = $("#login-email").val().trim();
		const password = $("#login-password").val();
		const submitBtn = $("#login-submit-btn");

		// Basic validation
		if (!email || !password) {
			showMessage("Please fill in all fields", "error");
			return;
		}

		submitBtn.prop("disabled", true).text("Logging in...");

		$.ajax({
			url: scanshowAdmin.restUrl + "auth/login",
			method: "POST",
			contentType: "application/json",
			data: JSON.stringify({
				email: email,
				password: password,
			}),
			success: function (response) {
				if (response.success || response.data) {
					showMessage("Login successful! Loading your settings...", "success");

					// Switch to settings view
					setTimeout(function () {
						$("#auth-section").hide();
						$("#settings-content").show();
						loadUserData();
					}, 1000);
				} else {
					showMessage(response.message || "Login failed", "error");
					submitBtn.prop("disabled", false).text("Login");
				}
			},
			error: function (xhr) {
				let errorMsg = "Login failed. Please try again.";

				// Try to get error message from response
				let errorSource = xhr.responseJSON;
				if (!errorSource && xhr.responseText) {
					try {
						errorSource = JSON.parse(xhr.responseText);
					} catch (e) {
						// If not JSON, use the text as-is if it's not too long
						if (xhr.responseText.length < 200) {
							errorMsg = xhr.responseText;
						}
					}
				}

				// Handle shop already connected error (409 Conflict)
				if (
					xhr.status === 409 &&
					errorSource &&
					errorSource.code === "SHOP_ALREADY_CONNECTED"
				) {
					// Show the shop conflict dialog
					showShopConflictDialog(
						errorSource.existing_shop,
						errorSource.message,
					);
					submitBtn.prop("disabled", false).text("Login");
					return;
				}

				if (errorSource) {
					errorMsg =
						errorSource.message ||
						errorSource.error ||
						(errorSource.data &&
							(errorSource.data.message || errorSource.data.error)) ||
						errorMsg;
				}

				showMessage(errorMsg, "error");
				submitBtn.prop("disabled", false).text("Login");
			},
		});
	}

	/**
	 * Show dialog for shop already connected conflict
	 * Directs user to STW platform settings to disconnect
	 */
	function showShopConflictDialog(existingShop, message) {
		const shopName =
			existingShop?.name || existingShop?.domain || "Unknown shop";
		const platform = existingShop?.platform || "Unknown";

		// Remove existing dialog if any
		$("#stw-shop-conflict-dialog").remove();

		const dialogHtml = `
			<div id="stw-shop-conflict-dialog" class="stw-modal-overlay">
				<div class="stw-modal-content">
					<div class="stw-modal-header">
						<span class="dashicons dashicons-warning"></span>
						<h3>Shop Already Connected</h3>
					</div>
					<div class="stw-modal-body">
						<p class="stw-conflict-message"></p>
						<div class="stw-existing-shop-info">
							<strong>Currently Connected Shop:</strong>
							<div class="stw-shop-details">
								<span class="dashicons dashicons-store"></span>
								<span class="stw-shop-name"></span>
							</div>
						</div>
						<div class="stw-instruction-text">
							<span class="dashicons dashicons-info"></span>
							<div>
								<strong>To connect this WordPress site:</strong>
								<ol>
									<li>Go to STW Platform Settings</li>
									<li>Find the <strong>"Connected Shop"</strong> section</li>
									<li>Click <strong>"Disconnect"</strong> to unlink the existing shop</li>
									<li>Return here and login again</li>
								</ol>
							</div>
						</div>
					</div>
					<div class="stw-modal-footer">
						<button type="button" class="button" id="stw-conflict-cancel">Cancel</button>
						<button type="button" class="button button-primary" id="stw-conflict-go-settings">
							Go to STW Settings
						</button>
					</div>
				</div>
			</div>
		`;

		const $dialog = $(dialogHtml);

		// Safely set text content to prevent XSS
		$dialog
			.find(".stw-conflict-message")
			.text(message || "Your account is already connected to another shop.");
		$dialog.find(".stw-shop-name").text(`${platform} - ${shopName}`);

		$("body").append($dialog);

		// Handle cancel
		$("#stw-conflict-cancel").on("click", function () {
			$("#stw-shop-conflict-dialog").remove();
		});

		// Handle go to settings
		$("#stw-conflict-go-settings").on("click", function () {
			window.STW_CONFIG.openExternal(
				window.STW_CONFIG.EXTERNAL_URLS.STW_SETTINGS,
			);
		});

		// Close on overlay click
		$("#stw-shop-conflict-dialog").on("click", function (e) {
			if (e.target === this) {
				$(this).remove();
			}
		});
	}

	/**
	 * Handle register form submission - opens registration page in new window like linking dashboard
	 */
	function handleRegister(e) {
		e.preventDefault();

		const registerUrl = window.STW_CONFIG.EXTERNAL_URLS.STW_REGISTER;
		const registerWindow = window.open(
			registerUrl,
			"STW_Register",
			"width=1200,height=800",
		);

		if (!registerWindow) {
			showMessage(
				"Unable to open window. Please check your popup blocker.",
				"error",
			);
			return;
		}

		// Check if window is closed and show completion message
		const checkWindowClosed = setInterval(() => {
			if (registerWindow.closed) {
				clearInterval(checkWindowClosed);
				showMessage(
					"Registration window closed. If you've registered, you can now login with your credentials.",
					"success",
				);
				// Switch to login tab after 2 seconds
				setTimeout(function () {
					$(".stw-auth-tab[data-tab='login']").click();
				}, 2000);
			}
		}, 500);
	}

	/**
	 * Load user data when authenticated
	 */
	function loadUserData() {
		$.ajax({
			url: scanshowAdmin.restUrl + "quota",
			method: "GET",
			success: function (data) {
				if (data.error) {
					$("#logged-in-email").text("Not connected");
					$("#user-details-container").html(
						`<p style="color: #dc3232;">${data.error}</p>`,
					);
					$("#plan-info").html(`<p style="color: #dc3232;">Not connected</p>`);
					$("#subscription-status").html("");
					$("#quota-details").html(
						`<p style="color: #dc3232;">Not connected</p>`,
					);
					return;
				}

				const user = data.user || {};
				const subscription = user.subscription || {};
				const plan = subscription.plan || {};

				// Display email
				$("#logged-in-email").text(user.email_address || "N/A");

				// Display user details
				const billingCycleEnd = subscription.billing_cycle_end
					? new Date(subscription.billing_cycle_end).toLocaleDateString()
					: "N/A";
				const billingInterval = subscription.billing_interval || "monthly";

				$("#user-details-container").html(`
					<div class="p-4 bg-gray-50 rounded">
						<strong class="block mb-1 text-gray-800">Email:</strong>
						<span class="text-gray-600">${user.email_address || "N/A"}</span>
					</div>
					<div class="p-4 bg-gray-50 rounded">
						<strong class="block mb-1 text-gray-800">Top-up Credits:</strong>
						<span class="text-gray-600">${user.topup_scan_credit || 0}</span>
					</div>
					<div class="p-4 bg-gray-50 rounded">
						<strong class="block mb-1 text-gray-800">Plan:</strong>
						<span class="text-gray-600">${plan.name || "Free Plan"}</span>
					</div>
					<div class="p-4 bg-gray-50 rounded">
						<strong class="block mb-1 text-gray-800">Billing Interval:</strong>
						<span class="text-gray-600">${capitalizeFirst(billingInterval)}</span>
					</div>
					<div class="p-4 bg-gray-50 rounded">
						<strong class="block mb-1 text-gray-800">Next Billing:</strong>
						<span class="text-gray-600">${billingCycleEnd}</span>
					</div>
				`);

				// Display plan info
				$("#plan-info").html(`
					<div class="text-xl font-semibold mb-2.5 text-blue-600">${
						plan.name || "Free Plan"
					}</div>
					<div class="mt-2 text-gray-600 text-sm">
						<div class="my-1">Scan Quota: ${
							plan.scan_quota || 0
						} scans / ${billingInterval}</div>
						<div class="my-1">Link Quota: ${
							plan.link_quota || 0
						} products / ${billingInterval}</div>
					</div>
				`);

				// Display subscription status
				if (billingCycleEnd !== "N/A") {
					$("#subscription-status").html(`
						<div class="flex items-center gap-2 p-3 bg-gray-50 rounded">
							<span class="dashicons dashicons-update text-green-600"></span>
							Your subscription is active. Next billing on ${billingCycleEnd}.
						</div>
					`);
				} else {
					$("#subscription-status").html("");
				}

				// Display quota details (using legacy format for compatibility)
				const scanCount = data.scan_count || 0;
				const scanQuota = plan.scan_quota || data.scan_quota || 0;
				const linkCount = data.link_count || 0;
				const linkQuota = plan.link_quota || data.link_quota || 0;

				$("#quota-details").html(`
					<div class="flex flex-col gap-2">
						<div class="py-2 border-b border-gray-200">
							<strong>Scan Quota:</strong>
							<span>${scanCount} / ${scanQuota} remaining</span>
						</div>
						<div class="py-2 border-b border-gray-200">
							<strong>Product Link Quota:</strong>
							<span>${linkCount} / ${linkQuota} remaining</span>
						</div>
						<div class="py-2">
							<strong>Top-up Scan Credits:</strong>
							<span>${user.topup_scan_credit || 0} credits</span>
						</div>
					</div>
				`);
			},
			error: function () {
				$("#logged-in-email").text("Error loading data");
				showMessage("Error loading user data", "error");
			},
		});
	}

	function upgradePlan() {
		window.STW_CONFIG.openExternal(window.STW_CONFIG.EXTERNAL_URLS.STW_PRICING);
	}

	function goToSTWDashboard() {
		window.STW_CONFIG.openExternal(
			window.STW_CONFIG.EXTERNAL_URLS.STW_DASHBOARD,
		);
	}

	function goToSTWAbout() {
		window.STW_CONFIG.openExternal(window.STW_CONFIG.EXTERNAL_URLS.STW_ABOUT);
	}

	function goToSTWPrivacy() {
		window.STW_CONFIG.openExternal(window.STW_CONFIG.EXTERNAL_URLS.STW_PRIVACY);
	}

	function goToSTWContact() {
		window.STW_CONFIG.navigateToRoute("/contact");
	}

	function capitalizeFirst(str) {
		return str ? str.charAt(0).toUpperCase() + str.slice(1) : "";
	}

	function showMessage(message, type) {
		const noticeClass = type === "success" ? "notice-success" : "notice-error";
		$("#message-container").html(`
			<div class="notice ${noticeClass} is-dismissible">
				<p>${message}</p>
			</div>
		`);

		setTimeout(() => {
			$("#message-container").find(".notice").fadeOut();
		}, 5000);
	}

	window.STW_Settings = STW_Settings;
})(jQuery);
