/**
 * Frontend script for STW Block
 * Dynamically loads the iframe URL based on linked STW item
 * Handles both WooCommerce product pages and regular pages
 */

(function () {
	"use strict";

	function getPostId() {
		const bodyClasses = document.body.className;
		// Prefer postid for product contexts, but fall back to page-id for standard pages
		let match = bodyClasses.match(/postid-(\d+)/);
		if (match) {
			return parseInt(match[1], 10);
		}
		match = bodyClasses.match(/page-id-(\d+)/);
		if (match) {
			return parseInt(match[1], 10);
		}
		return null;
	}

	function isSingleProductPage() {
		const bodyClasses = document.body.className || "";
		// Direct body class checks
		if (
			/\b(single-product|post-type-product|post_type_product)\b/.test(
				bodyClasses,
			)
		) {
			return true;
		}
		// Some themes add 'single' + 'product' separately
		if (bodyClasses.includes("single") && bodyClasses.includes("product")) {
			return true;
		}
		// DOM-based heuristics: presence of a product container on a singular page
		try {
			if (
				document.querySelector(".product") &&
				/postid-\d+/.test(bodyClasses)
			) {
				return true;
			}
			// Check for schema.org Product markup
			if (document.querySelector('[itemtype*="Product"]')) {
				return true;
			}
		} catch (e) {
			// ignore DOM access errors
		}
		return false;
	}

	const postId = getPostId();

	if (!postId) {
		console.error("[STW Block] Unable to detect post ID");
		return;
	}

	console.log(`[STW Block] Detected post ID: ${postId}`);

	// Determine the correct API endpoint based on page type
	const isProductPage = isSingleProductPage();
	const apiUrl = isProductPage
		? `/index.php?rest_route=/3d-scan-and-show/v1/iframe-url&product_id=${postId}`
		: `/index.php?rest_route=/3d-scan-and-show/v1/page-iframe-url&page_id=${postId}`;

	console.log(`[STW Block] Page type: ${isProductPage ? "Product" : "Page"}`);

	// Fetch iframe URL from REST API
	fetch(apiUrl)
		.then((response) => response.json())
		.then((data) => {
			const embedBlocks = document.querySelectorAll(".stw-embed-block");

			if (!data.success || !data.iframe_url) {
				console.log(
					"[STW Block] No iframe URL found - page/product not linked to STW item",
				);
				embedBlocks.forEach((block) => {
					// Remove all attributes safely
					const attributeNames = Array.from(block.attributes).map(
						(attr) => attr.name,
					);
					attributeNames.forEach((name) => block.removeAttribute(name));
					// Clear innerHTML
					block.innerHTML = "";
				});
				return;
			}

			// Create iframe dynamically for linked products/pages
			embedBlocks.forEach((block) => {
				const aspectRatio = block.getAttribute("data-aspect-ratio") || "auto";

				const iframe = document.createElement("iframe");
				iframe.src = data.iframe_url;
				iframe.frameBorder = "0";
				iframe.allowFullscreen = true;
				iframe.title = "Scan the World 3D Model";
				iframe.style.border = "none";
				iframe.style.borderRadius = "4px";

				if (aspectRatio === "auto") {
					iframe.style.position = "absolute";
					iframe.style.top = "0";
					iframe.style.left = "0";
					iframe.style.width = "100%";
					iframe.style.height = "100%";
				} else {
					iframe.style.width = "100%";
					iframe.style.aspectRatio = aspectRatio;
				}

				block.appendChild(iframe);
			});
		})
		.catch((error) => {
			console.error("[STW Block] Error loading iframe:", error);
			// Remove all attributes and classes on error, make it completely empty <div></div>
			const embedBlocks = document.querySelectorAll(".stw-embed-block");
			embedBlocks.forEach((block) => {
				// Remove all attributes safely
				const attributeNames = Array.from(block.attributes).map(
					(attr) => attr.name,
				);
				attributeNames.forEach((name) => block.removeAttribute(name));
				// Clear innerHTML
				block.innerHTML = "";
			});
		});
})();
