import { useEffect } from "react";
import { useWordpressData } from "../hooks/WordpressFetchData";
import { useState } from "react";

import Menu from "../components/Menu";
import Modal from "../components/Modal";

export default function Game() {
	const [isModalOpen, setIsModalOpen] = useState(false);

	const screenData = useWordpressData("/search-and-find");
	const [isDragging, setIsDragging] = useState(false);
	const [startX, setStartX] = useState(0);

	// HANDLE DRAGGING
	function handleMouseDown(e) {
		const container = document.querySelector(".lhoist-blocks-search-and-find");
		setIsDragging(true);
		setStartX(e.clientX + container.scrollLeft);
	}

	function handleMouseMove(e) {
		if (!isDragging) return;
		const container = document.querySelector(".lhoist-blocks-search-and-find");
		const newScrollLeft = startX - e.clientX;
		container.scrollLeft = newScrollLeft;
	}

	function handleMouseUp() {
		setIsDragging(false);
	}
	function handleObjectClick() {
		console.log("object clicked");
	}

	function initGame(container) {
		if (!container) return;

		const objects = container.querySelectorAll(".lhoist-blocks-focus-object");

		objects.forEach((object) => {
			object.addEventListener("click", () => {
				handleObjectClick();
			});
		});
	}

	function cleanGame(container) {
		if (!container) return;

		const objects = container.querySelectorAll(".lhoist-blocks-focus-object");
		objects.forEach((object) => {
			object.removeEventListener("click", () => {
				handleObjectClick();
			});
		});
	}

	useEffect(() => {
		if (!screenData) return;
		const container = document.querySelector(".lhoist-blocks-search-and-find");

		initGame(container);

		return () => {
			cleanGame(container);
		};
	}, [screenData]);

	if (!screenData) return;

	return (
		<>
			<button onClick={() => setIsModalOpen(true)}>show modal</button>
			<Modal open={isModalOpen} onClose={() => setIsModalOpen(false)}>
				<p>salut</p>
			</Modal>

			<div className='page-container page-container--play'>
				<div className='screen'>
					<Menu />
					{screenData && (
						<div
							onMouseDown={handleMouseDown}
							onMouseMove={handleMouseMove}
							onMouseUp={handleMouseUp}
							dangerouslySetInnerHTML={{
								__html: screenData[0].content.rendered,
							}}
						/>
					)}
				</div>
			</div>
		</>
	);
}
