(function ($) {
	"use strict";

	let allProducts = [];
	let linkedItemsMap = {};
	let currentFilter = "all";
	let currentSort = "name-asc";
	let currentCategory = "";
	let categories = [];

	const STW_Dashboard = {
		initialized: false,

		init: function () {
			// Always refresh data on init to get latest connection status
			loadConnectionStatus();
			loadPlanAndQuota();
			loadLinkedItems();

			// Only setup once
			if (!this.initialized) {
				loadProducts();
				loadCategories();
				setupEventListeners();
				this.initialized = true;
			}
		},

		// Allow external refresh (e.g., after login)
		refresh: function () {
			loadConnectionStatus();
			loadPlanAndQuota();
			loadLinkedItems();
		},
	};

	function setupEventListeners() {
		// Actions
		$(document)
			.off("click", "#product-theme-editor-btn")
			.on("click", "#product-theme-editor-btn", goToThemeEditor);
		$(document)
			.off("click", "#add-product-btn")
			.on("click", "#add-product-btn", addProduct);
		$(document)
			.off("click", "#go-to-dashboard-btn")
			.on("click", "#go-to-dashboard-btn", goToSTWDashboard);

		// More actions dropdown
		$(document)
			.off("click", "#more-actions-btn")
			.on("click", "#more-actions-btn", function (e) {
				e.stopPropagation();
				$("#more-dropdown").slideToggle(200);
			});

		// Close dropdown when clicking outside
		$(document).on("click", function (e) {
			if (!$(e.target).closest(".stw-more-menu").length) {
				$("#more-dropdown").slideUp(200);
			}
		});

		// Search and Sort
		$(document)
			.off("input", "#product-search")
			.on("input", "#product-search", filterAndRenderProducts);
		$(document)
			.off("click", "#sort-by-name")
			.on("click", "#sort-by-name", toggleSort);

		// Filter
		$(document)
			.off("click", "#filter-btn")
			.on("click", "#filter-btn", toggleFilterPanel);
		$(document)
			.off("change", "#category-filter")
			.on("change", "#category-filter", function () {
				currentCategory = $(this).val();
				filterAndRenderProducts();
			});
		$(document)
			.off("click", "#clear-filters-btn")
			.on("click", "#clear-filters-btn", clearFilters);

		// Modal
		$(document)
			.off("click", "#close-modal-btn")
			.on("click", "#close-modal-btn", closeModal);
	}

	function toggleFilterPanel() {
		$("#filter-panel").slideToggle(200);
	}

	function clearFilters() {
		currentCategory = "";
		$("#category-filter").val("");
		$("#product-search").val("");
		filterAndRenderProducts();
	}

	function loadConnectionStatus() {
		$.ajax({
			url: scanshowAdmin.restUrl + "connection",
			method: "GET",
			success: function (response) {
				if (response.connected) {
					$("#connection-display").html(`
						<span>Connected to STW as: <strong>${response.user_email}</strong></span>
						<button class="button" id="go-to-dashboard-btn">Go to My Dashboard</button>
					`);
					// Event delegation already handled in setupEventListeners
				} else {
					$("#connection-display").html(`
					<span style="color: #dc3232;">Not connected to STW Platform</span>
					<button class="button button-primary" id="login-now-btn">Login Now</button>
				`);
					$(document)
						.off("click", "#login-now-btn")
						.on("click", "#login-now-btn", goToSettings);
				}
			},
		});
	}

	function loadPlanAndQuota() {
		$.ajax({
			url: scanshowAdmin.restUrl + "quota",
			method: "GET",
			success: function (data) {
				if (data.error) {
					$("#plan-quota-display").html(
						`<p style="color: #dc3232;">${data.error}</p>`,
					);
					return;
				}

				// Extract data from new structure
				const quotas = data.quotas || {};
				const subscription = data.subscription || {};
				const plan = subscription.plan || {};
				const user = data.user || {};

				// Get quota values from the quotas object
				const linkQuota = quotas.link_quota || 0;
				const linkCredit = quotas.link_credit || 0;
				const scanQuota = quotas.scan_quota || 0;
				const scanCredit = quotas.scan_credit || 0;
				const topupScanCredit = quotas.topup_scan_credit || 0;
				const totalScanCredit =
					quotas.total_scan_credit || scanCredit + topupScanCredit;
				const annotationQuota = quotas.annotation_quota || 0;
				const embedQuota = quotas.embed_quota || 0;
				const embedCredit = quotas.embed_credit || 0;

				// Calculate used credits
				const linkUsed = linkQuota - linkCredit;
				const scanUsed = scanQuota - scanCredit;

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

				// Display user info
				const username = user.username || "User";
				const email = user.email_address || "";

				$("#plan-quota-display").html(`
					<div class="stw-dashboard-info-compact">
						<div class="stw-user-plan-section">
							<div class="stw-user-info-inline">
								<span class="dashicons dashicons-admin-users"></span>
								<div>
									<div class="stw-username">${username}</div>
									<div class="stw-user-email">${email}</div>
								</div>
							</div>
							<div class="stw-plan-info-inline">
								<div class="stw-plan-name">${plan.name || "Free Plan"}</div>
								<div class="stw-plan-meta">
									<span>Billing: ${billingInterval.toUpperCase()}</span>
									<span>•</span>
									<span>Next billing: ${billingCycleEnd}</span>
								</div>
							</div>
						</div>
						<div class="stw-quota-section-compact">
							<div class="stw-quota-item-compact">
								<span>3D Scan Quota</span>
								<div class="stw-quota-value-compact">${scanUsed}/${scanQuota}</div>
								<div class="stw-quota-sub-compact">${
									topupScanCredit > 0
										? `+${topupScanCredit} top-up credits (Total: ${totalScanCredit})`
										: `${scanCredit} remaining`
								}</div>
							</div>
							<div class="stw-quota-item-compact">
								<span>Product Link Quota</span>
								<div class="stw-quota-value-compact">${linkUsed}/${linkQuota}</div>
								<div class="stw-quota-sub-compact">${linkCredit} remaining</div>
							</div>
							<div class="stw-quota-item-compact">
								<span>Annotation Quota</span>
								<div class="stw-quota-value-compact">${annotationQuota}</div>
								<div class="stw-quota-sub-compact">available</div>
							</div>
							<div class="stw-quota-item-compact">
								<span>Embed Quota</span>
								<div class="stw-quota-value-compact">${
									embedQuota - embedCredit
								}/${embedQuota}</div>
								<div class="stw-quota-sub-compact">${embedCredit} remaining</div>
							</div>
						</div>
					</div>
				`);
			},
			error: function () {
				$("#plan-quota-display").html(
					`<p style="color: #dc3232;">Error loading plan information</p>`,
				);
			},
		});
	}

	function loadCategories() {
		$.ajax({
			url: scanshowAdmin.restUrl + "categories",
			method: "GET",
			success: function (response) {
				if (response.error) {
					console.error("Error loading categories:", response.error);
					return;
				}

				categories = response;
				const categorySelect = $("#category-filter");
				categorySelect.find("option:not(:first)").remove(); // Keep "All Categories"

				categories.forEach((cat) => {
					categorySelect.append(
						`<option value="${cat.id}">${cat.name} (${cat.count})</option>`,
					);
				});
			},
			error: function () {
				console.error("Failed to load categories");
			},
		});
	}

	function loadProducts() {
		$.ajax({
			url: scanshowAdmin.restUrl + "products",
			method: "GET",
			success: function (response) {
				if (response.error) {
					showMessage(response.error, "error");
					return;
				}
				allProducts = response;
				filterAndRenderProducts();
			},
			error: function () {
				showMessage("Error loading products", "error");
			},
		});
	}

	function filterAndRenderProducts() {
		// Ensure allProducts is an array
		if (!Array.isArray(allProducts)) {
			return;
		}

		let filtered = allProducts;

		// Filter by status (removed draft/archived tabs, only "all" now)
		if (currentFilter !== "all") {
			filtered = filtered.filter((p) => p.status === currentFilter);
		}

		// Filter by category
		if (currentCategory) {
			filtered = filtered.filter((p) => {
				if (!p.categories || p.categories.length === 0) {
					return false;
				}
				return p.categories.some((cat) => cat.id == currentCategory);
			});
		}

		// Filter by search (with null check)
		const searchInput = $("#product-search").val();
		const searchTerm = searchInput ? searchInput.toLowerCase() : "";
		if (searchTerm) {
			filtered = filtered.filter(
				(p) =>
					(p.name && p.name.toLowerCase().includes(searchTerm)) ||
					(p.id && p.id.toString().includes(searchTerm)),
			);
		}

		// Sort (with null checks for name)
		if (currentSort === "name-asc") {
			filtered.sort((a, b) => (a.name || "").localeCompare(b.name || ""));
		} else {
			filtered.sort((a, b) => (b.name || "").localeCompare(a.name || ""));
		}

		renderProducts(filtered);
	}

	function renderProducts(products) {
		const container = $("#products-container");

		if (products.length === 0) {
			container.html("<p>No products found.</p>");
			return;
		}

		let html = `
			<table class="stw-products-table">
				<thead>
					<tr>
						<th style="width: 25%;">Product</th>
						<th style="width: 12%;">Status</th>
						<th style="width: 18%;">Category</th>
						<th style="width: 45%;">Linked 3D Model</th>
					</tr>
				</thead>
				<tbody>
		`;

		products.forEach((product) => {
			const categoryNames =
				product.categories && product.categories.length > 0
					? product.categories.map((c) => c.name).join(", ")
					: "Uncategorized";

			const linkedItem = linkedItemsMap[product.id];
			let linkedModelHtml = "";

			if (linkedItem) {
				// Product is linked - show item info and change button
				linkedModelHtml = `
					<div class="stw-linked-model-content">
						<div class="stw-linked-item-info">
							${
								linkedItem.thumbnail_url
									? `<img src="${linkedItem.thumbnail_url}" alt="${linkedItem.name}" class="stw-linked-thumbnail" />`
									: '<div class="stw-linked-icon">🎨</div>'
							}
							<div>
								<strong>${linkedItem.name}</strong>
								<small style="display: block; color: #666; font-size: 11px;">${
									linkedItem.id
								}</small>
							</div>
						</div>
						<button class="stw-change-btn button button-small" data-product-id="${
							product.id
						}" title="Change linked model">
							<span class="dashicons dashicons-update"></span> Change
						</button>
					</div>
				`;
			} else {
				// Product is not linked - show link button
				linkedModelHtml = `
					<div class="stw-unlinked-model">
						<p style="margin: 0; color: #666; font-size: 12px;">No model linked</p>
						<button class="stw-link-btn button button-small button-primary" data-product-id="${product.id}">
							<span class="dashicons dashicons-plus-alt"></span> Link
						</button>
					</div>
				`;
			}

			html += `
				<tr>
					<td>
						<div class="stw-product-cell">
							<div class="stw-product-icon">
								${product.image ? `<img src="${product.image}" alt="${product.name}" />` : "📦"}
							</div>
							<div>
								<strong>${product.name}</strong>
								<div class="stw-product-id">ID: ${product.id}</div>
							</div>
						</div>
					</td>
					<td>
						<span class="stw-status stw-status-${product.status.toLowerCase()}">
							${product.status.toUpperCase()}
						</span>
					</td>
					<td>${categoryNames}</td>
					<td>
						${linkedModelHtml}
					</td>
				</tr>
			`;
		});

		html += "</tbody></table>";
		container.html(html);

		// Attach click handlers for link and change buttons
		$(".stw-link-btn, .stw-change-btn").on("click", function () {
			const productId = $(this).data("product-id");
			openLinkModal(productId);
		});
	}

	function toggleSort() {
		currentSort = currentSort === "name-asc" ? "name-desc" : "name-asc";
		const arrow = currentSort === "name-asc" ? "↑" : "↓";
		$("#sort-by-name").text(`${arrow} Name`);
		filterAndRenderProducts();
	}

	function loadLinkedItems() {
		$.ajax({
			url: scanshowAdmin.restUrl + "linked-items",
			method: "GET",
			success: function (response) {
				linkedItemsMap = {};
				if (Array.isArray(response)) {
					// Create a map of product_id to item info
					response.forEach((item) => {
						if (item.product_id) {
							linkedItemsMap[item.product_id] = {
								id: item.id,
								name: item.name,
								thumbnail_url: item.thumbnail_url,
							};
						}
					});
					// Refresh the product display to show updated links
					filterAndRenderProducts();
				} else if (response.error) {
					console.error("Error loading linked items:", response.error);
				}
			},
			error: function () {
				console.error("Failed to load linked items");
			},
		});
	}

	function openLinkModal(productId) {
		// Get the link URL from the server
		$.ajax({
			url: scanshowAdmin.restUrl + "product-link-url",
			method: "GET",
			beforeSend: function (xhr) {
				xhr.setRequestHeader("X-WP-Nonce", scanshowAdmin.nonce);
			},
			data: {
				product_id: productId,
			},
			success: function (response) {
				if (response.error) {
					showMessage("Error: " + response.error, "error");
					return;
				}

				if (!response.url) {
					showMessage(
						"Unable to generate link URL. Please check your connection.",
						"error",
					);
					return;
				}

				// Open the link window
				const linkWindow = window.open(
					response.url,
					"_blank",
					"width=1200,height=800",
				);

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

				// Check if window is closed and refresh dashboard
				const checkWindowClosed = setInterval(() => {
					if (linkWindow.closed) {
						clearInterval(checkWindowClosed);
						setTimeout(() => {
							loadPlanAndQuota();
							loadLinkedItems();
						}, 1000);
					}
				}, 500);
			},
			error: function () {
				showMessage(
					"Error happened while loading link URL. Please make sure you have connected to STW Platform.",
					"error",
				);
			},
		});
	}

	function closeModal() {
		$("#stw-items-modal").fadeOut();
	}

	function goToSettings() {
		window.STW_CONFIG.navigateToRoute("/settings");
	}

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

	function goToThemeEditor() {
		const editorUrl = window.STW_CONFIG.getSingleProductEditorUrl();
		window.open(editorUrl, "_blank");
	}

	function addProduct() {
		window.STW_CONFIG.navigateToAdmin(window.STW_CONFIG.ADMIN_URLS.ADD_PRODUCT);
	}

	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();
		}, 3000);
	}

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