(function ($) {
	"use strict";

	/**
	 * All of the code for your public-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * $(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * $( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */
	$(document).ready(function () {
		initModelViewers();
		initModelViewerDimensions();
	});

	$(window).on("resize", function () {
		resizeModelViewerWrapper();
	});

	const resizeModelViewerWrapper = () => {
		const wrappers = document.querySelectorAll(".u3dmv-model-viewer-wrapper");

		wrappers.forEach(function (wrapper) {
			// Get the originally set height (from inline style or CSS)
			const originalHeight = wrapper.dataset.originalHeight || getComputedStyle(wrapper).height;

			// Store it in data-* so it’s preserved
			wrapper.dataset.originalHeight = originalHeight;

			const originalHeightFloat = parseFloat(originalHeight);
			const currentWidth = wrapper.offsetWidth;

			// Set height to the smaller of the width or original height
			const newHeight = Math.min(currentWidth, originalHeightFloat);
			wrapper.style.height = `${newHeight}px`;
		});
	};

	const initModelViewers = () => {
		const modelViewers = document.querySelectorAll("model-viewer");

		modelViewers.forEach((viewer) => {
			const wrapper = viewer.closest(".u3dmv-model-viewer-wrapper");

			const progressHandler = (event) => {
				if (!event?.detail) return;

				onMVWProgess(event, viewer);
			};

			viewer.addEventListener("progress", progressHandler);
		});
	};

	const initModelViewerDimensions = () => {
		const modelViewers = document.querySelectorAll("model-viewer[data-dim-mode]");
		if (!modelViewers || modelViewers.length === 0) return;

		modelViewers.forEach((viewer) => {
			const { dimX, dimY, dimZ, dimMode, scaleFactor } = viewer.dataset;

			// dimensions not set
			if (!dimX && !dimY && !dimZ && !scaleFactor && !dimMode) return;

			const scale = scaleFactor ? parseFloat(scaleFactor) : "1";
			const validScale = !isNaN(scale) && scale > 0 ? scale : 1;
			const useCustomDimensions = dimMode === "custom";
			const customDimensionsSet = dimX && dimY && dimZ;

			viewer.addEventListener("load", () => {
				const center = viewer.getBoundingBoxCenter();
				const realSize = viewer.getDimensions(); // Keep using real size for positions

				const x2 = realSize.x / 2;
				const y2 = realSize.y / 2;
				const z2 = realSize.z / 2;

				const dimXFloat = parseFloat(dimX);
				const dimYFloat = parseFloat(dimY);
				const dimZFloat = parseFloat(dimZ);

				// Position dots using REAL dimensions
				viewer.updateHotspot({
					name: "hotspot-dot+X-Y+Z",
					position: `${center.x + x2} ${center.y - y2} ${center.z + z2}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dot+X-Y-Z",
					position: `${center.x + x2} ${center.y - y2} ${center.z - z2}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dot+X+Y-Z",
					position: `${center.x + x2} ${center.y + y2} ${center.z - z2}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dot-X+Y-Z",
					position: `${center.x - x2} ${center.y + y2} ${center.z - z2}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dot-X-Y-Z",
					position: `${center.x - x2} ${center.y - y2} ${center.z - z2}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dot-X-Y+Z",
					position: `${center.x - x2} ${center.y - y2} ${center.z + z2}`,
				});

				// Position dimensions using real dimensions too
				viewer.updateHotspot({
					name: "hotspot-dim+X-Y",
					position: `${center.x + x2 * 1.2} ${center.y - y2 * 1.1} ${center.z}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dim+X-Z",
					position: `${center.x + x2 * 1.2} ${center.y} ${center.z - z2 * 1.2}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dim+Y-Z",
					position: `${center.x} ${center.y + y2 * 1.1} ${center.z - z2 * 1.1}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dim-X-Z",
					position: `${center.x - x2 * 1.2} ${center.y} ${center.z - z2 * 1.2}`,
				});
				viewer.updateHotspot({
					name: "hotspot-dim-X-Y",
					position: `${center.x - x2 * 1.2} ${center.y - y2 * 1.1} ${center.z}`,
				});

				viewer.querySelector('button[slot="hotspot-dim+X-Y"]').textContent =
					useCustomDimensions && customDimensionsSet ? `${dimZFloat.toFixed(2)} cm` : `${(realSize.z.toFixed(2) * validScale).toFixed(2)} cm`;

				viewer.querySelector('button[slot="hotspot-dim+X-Z"]').textContent =
					useCustomDimensions && customDimensionsSet ? `${dimYFloat.toFixed(2)} cm` : `${(realSize.y.toFixed(2) * validScale).toFixed(2)} cm`;

				viewer.querySelector('button[slot="hotspot-dim+Y-Z"]').textContent =
					useCustomDimensions && customDimensionsSet ? `${dimXFloat.toFixed(2)} cm` : `${(realSize.x.toFixed(2) * validScale).toFixed(2)} cm`;

				viewer.querySelector('button[slot="hotspot-dim-X-Z"]').textContent =
					useCustomDimensions && customDimensionsSet ? `${dimYFloat.toFixed(2)} cm` : `${(realSize.y.toFixed(2) * validScale).toFixed(2)} cm`;

				viewer.querySelector('button[slot="hotspot-dim-X-Y"]').textContent =
					useCustomDimensions && customDimensionsSet ? `${dimZFloat.toFixed(2)} cm` : `${(realSize.z.toFixed(2) * validScale).toFixed(2)} cm`;

				renderSVG();
				viewer.addEventListener("camera-change", renderSVG);
			});
		});
	};

	function drawLine(svgLine, dotHotspot1, dotHotspot2, dimensionHotspot) {
		if (dotHotspot1 && dotHotspot2) {
			svgLine.setAttribute("x1", dotHotspot1.canvasPosition.x);
			svgLine.setAttribute("y1", dotHotspot1.canvasPosition.y);
			svgLine.setAttribute("x2", dotHotspot2.canvasPosition.x);
			svgLine.setAttribute("y2", dotHotspot2.canvasPosition.y);

			// use provided optional hotspot to tie visibility of this svg line to
			if (dimensionHotspot && !dimensionHotspot.facingCamera) {
				svgLine.classList.add("hide");
			} else {
				svgLine.classList.remove("hide");
			}
		}
	}

	const renderSVG = () => {
		const modelViewers = document.querySelectorAll("model-viewer[data-dim-mode]");

		modelViewers.forEach((viewer) => {
			const dimLines = viewer.querySelectorAll("line");
			if (dimLines.length < 5) return; // not found expected number of lines, skip
			drawLine(dimLines[0], viewer.queryHotspot("hotspot-dot+X-Y+Z"), viewer.queryHotspot("hotspot-dot+X-Y-Z"), viewer.queryHotspot("hotspot-dim+X-Y"));
			drawLine(dimLines[1], viewer.queryHotspot("hotspot-dot+X-Y-Z"), viewer.queryHotspot("hotspot-dot+X+Y-Z"), viewer.queryHotspot("hotspot-dim+X-Z"));
			drawLine(dimLines[2], viewer.queryHotspot("hotspot-dot+X+Y-Z"), viewer.queryHotspot("hotspot-dot-X+Y-Z")); // always visible
			drawLine(dimLines[3], viewer.queryHotspot("hotspot-dot-X+Y-Z"), viewer.queryHotspot("hotspot-dot-X-Y-Z"), viewer.queryHotspot("hotspot-dim-X-Z"));
			drawLine(dimLines[4], viewer.queryHotspot("hotspot-dot-X-Y-Z"), viewer.queryHotspot("hotspot-dot-X-Y+Z"), viewer.queryHotspot("hotspot-dim-X-Y"));
		});
	};

	const onMVWProgess = (event, viewer) => {
		if (!event?.detail || !viewer) return;

		const progressBar = viewer.querySelector(".progress-bar");
		const updatingBar = viewer.querySelector(".update-bar");

		const progress = event.detail.totalProgress;

		if (updatingBar) {
			updatingBar.style.width = `${progress * 100}%`;
		}

		if (progressBar) {
			if (progress >= 1) {
				progressBar.classList.add("hide");
			} else {
				progressBar.classList.remove("hide");
			}
		}
	};
})(jQuery);
