---
import Layout from "../layouts/Layout.astro";

import Taskbar from "../components/taskbar.astro";
import App from "../components/app.astro";
import Aboutme from "../components/aboutme.astro";
import Redirect from "../components/redirect.astro";
import Contact from "../components/contact.astro";
import Pgp from "../components/pgp.astro";
import Projects from "../components/projects.astro";
import Duolingo from "../components/duolingo.astro";
import GitHubGraph from "../components/githubgraph.astro";

// Projects
import Summize from "../components/projects/summize.astro";
import Notion from "../components/projects/notion.astro";
import Imdb from "../components/projects/imdb.astro";

import "../styles/global.css";

import me from "../assets/apps/me.png";
import github from "../assets/apps/github.png";
import pastwork from "../assets/apps/pastWork.png";
import projects from "../assets/apps/projects.png";
import blog from "../assets/apps/blog.png";
import contact from "../assets/apps/contact.png";
import pgp from "../assets/apps/pgp.png";

function dragElement(elmnt) {
	var pos1 = 0,
		pos2 = 0,
		pos3 = 0,
		pos4 = 0;

	// Skip dragging for fullscreen PGP window
	if (elmnt.id === "PGP Key" || elmnt.classList.contains("pgp-fullscreen")) {
		return;
	}

	if (document.getElementById(elmnt.id + "header")) {
		// If present, the header is where you move the DIV from:
		document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
		document.getElementById(elmnt.id + "header").ontouchstart = dragMouseDown;
	} else {
		// Otherwise, move the DIV from anywhere inside the DIV:
		elmnt.onmousedown = dragMouseDown;
		elmnt.ontouchstart = dragMouseDown;
	}

	function dragMouseDown(e) {
		// e.preventDefault();
		raiseUpSpec(elmnt.id);
		// Get the initial touch point for touch events
		if (e.type == "touchstart") {
			pos3 = e.touches[0].clientX;
			pos4 = e.touches[0].clientY;
		} else {
			pos3 = e.clientX;
			pos4 = e.clientY;
		}
		document.onmouseup = closeDragElement;
		document.ontouchend = closeDragElement;
		document.onmousemove = elementDrag;
		document.ontouchmove = elementDrag;
	}

	function elementDrag(e) {
		// e.preventDefault();
		if (e.type == "touchmove") {
			// Calculate the new cursor position for touch
			pos1 = pos3 - e.touches[0].clientX;
			pos2 = pos4 - e.touches[0].clientY;
			pos3 = e.touches[0].clientX;
			pos4 = e.touches[0].clientY;
		} else {
			// Calculate the new cursor position for mouse
			pos1 = pos3 - e.clientX;
			pos2 = pos4 - e.clientY;
			pos3 = e.clientX;
			pos4 = e.clientY;
		}
		// Set the element's new position
		elmnt.style.top = elmnt.offsetTop - pos2 + "px";
		elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
	}

	function closeDragElement() {
		// Stop moving when mouse button or touch is released
		document.onmouseup = null;
		document.ontouchend = null;
		document.onmousemove = null;
		document.ontouchmove = null;
	}
}

/** Raise up window with given ID */
function raiseUpSpec(id: string) {
	let els = document.getElementsByClassName("window");
	let elArray = Array.from(els as HTMLCollectionOf<HTMLElement>);

	// find the highest z-index
	let highestIndex = 0;

	for (let element in elArray) {
		let zindexStr = elArray[element].style.zIndex;
		let zindex = parseInt(zindexStr) || 0;
		if (zindex > highestIndex) {
			highestIndex = zindex;
		}
	}

	// set the highest z-index plus one using ID
	const windowEl = document.getElementById(id) as HTMLElement | null;
	if (windowEl) {
		windowEl.style.zIndex = (highestIndex + 1).toString();
	}
}

function updateRedirectMessage() {
	const redirectElement = document.getElementById("Redirect");

	const redirectUrl = redirectElement.dataset.redirecturl; // Access the data attribute

	const messageElement = redirectElement.querySelector("h2");
	messageElement.innerHTML = `You are about to be redirected to <a class="redirUrl" style="  cursor: pointer;
    color: blue;
    text-decoration: underline; " href="${redirectUrl}"">${redirectUrl.replace("https://", "")}</a>`;

	const buttonElement = redirectElement.querySelector("#okButton");
	// open redirect url
	buttonElement.setAttribute(
		"onclick",
		`window.location.href = "${redirectUrl}"`
	);
}

let apps: app[] = [
	{
		name: "About Me",
		logo: me.src,
		onclick: () => {
			raiseUpSpec("About Me");
			const windowEl = document.getElementById("About Me") as HTMLElement | null;
			if (windowEl) windowEl.style.display = "block";
		},
		row: 1,
	},
	{
		name: "Blog",
		logo: blog.src,
		onclick: () => {
			raiseUpSpec("Redirect");
			const windowEl = document.getElementById("Redirect") as HTMLElement | null;
			if (windowEl) windowEl.style.display = "block";
			if (windowEl) (windowEl as any).dataset.redirecturl = "https://blog.simo.ng/";
			updateRedirectMessage();
		},
		row: 1,
	},
	{
		name: "Projects",
		logo: projects.src,
		onclick: () => {
			raiseUpSpec("Projects ");
			const windowEl = document.getElementById("Projects ") as HTMLElement | null;
			if (windowEl) windowEl.style.display = "block";
		},
		row: 1,
	},
	// {
	// 	name: "Past Work",
	// 	logo: pastwork.src,
	// 	row: 1,
	// },
	{
		name: "Github",
		logo: github.src,
		onclick: () => {
			// ignore
			raiseUpSpec("Redirect");
			const windowEl = document.getElementById("Redirect") as HTMLElement | null;
			if (windowEl) windowEl.style.display = "block";
			if (windowEl) (windowEl as any).dataset.redirecturl = "https://github.com/s1monlol/";
			updateRedirectMessage();
		},
		row: 2,
	},
	{
		name: "Contact",
		logo: contact.src,
		row: 2,
		onclick: () => {
			raiseUpSpec("Contact");
			const windowEl = document.getElementById("Contact") as HTMLElement | null;
			if (windowEl) windowEl.style.display = "block";
		},
	},
	{
		name: "PGP Key",
		logo: pgp.src,
		row: 2,
		onclick: () => {
			raiseUpSpec("PGP Key");
			const windowEl = document.getElementById("PGP Key") as HTMLElement | null;
			if (windowEl) {
				windowEl.classList.add("fullscreen");
				windowEl.style.display = "block";
			}
		},
	},
];

let projectsArr: project[] = [
	{
		title: "Summize",
		id: "summize",
	},
	{
		title: "Notion2Canvas",
		id: "notion",
	},
	{
		title: "PGPCord",
		id: "pgpcord",
	},
	{
		title: "IMDB Frontend",
		id: "imdb",
	},
];

const row1Items = apps.filter((item) => item.row === 1);
const row2Items = apps.filter((item) => item.row === 2);

let clientFunctions: Function[] | String[] = [
	raiseUpSpec,
	updateRedirectMessage,
	dragElement,
	updateRedirectMessage,
];

clientFunctions = clientFunctions.map((item) => String(item));

apps = apps.map((item) => {
	item.onclick = String(item.onclick);

	return item;
});
---

<Layout title="Simo">
	<div style="width: 100%; height: calc(100vh - 3.5rem); ">
		<Pgp />

		<div style="display: flex;">
			<div
				style="height: 20rem; display: flex; flex-direction: column; align-items: flex-start;"
			>
				{row1Items.map((item) => <App {item} />)}
			</div>

			<div
				style="height: 20rem; display: flex; flex-direction: column; align-items: flex-start;"
			>
				{row2Items.map((item) => <App {item} />)}
			</div>
		</div>

		<Aboutme />
		<Redirect />
		<Contact />
		<Projects projects={projectsArr} />
		<Summize />
		<Notion />
		<Imdb />
		<Duolingo />
		<GitHubGraph />
	</div>
	<Taskbar />
</Layout>

<script define:vars={{ apps, projectsArr, clientFunctions }}>
	let dino = `
	                	██████████████
                      ████░░████████████
                      ██████████████████
                      ██████████████████
                      ██████████████████
                      ████████
                      ██████████████░░
                      ██████
  ██              ██████████
  ██▒▒        ▒▒▒▒██████████▒▒▒▒
  ████▓▓      ██████████████  ▒▒
  ██████▒▒▒▒████████████████
  ██████████████████████████
    ██████████████████████
        ██████████████████
        ▒▒██████████████
          ▒▒██████▒▒██▓▓
            ████      ▓▓
            ██▒▒      ▓▓
            ██        ██
`;

	console.log(dino);

	for (func in clientFunctions) {
		eval(clientFunctions[func]);
	}

	Array.from(document.getElementsByClassName("project")).forEach((project) => {
		// console.log(projectsArr[0].id + "item");

		let id = projectsArr.find((i) => i.id + "item" == project.id).id;

		// console.log(id);

		if (id == "pgpcord") {
			project.onclick = () => {
				setTimeout(() => {
					raiseUpSpec("Redirect");
					const windowEl = document.getElementById("Redirect");
					if (windowEl) {
						windowEl.style.display = "block";
						windowEl.dataset.redirecturl = "https://blog.simo.ng/articles/WIP/pgpcord";
					}
					updateRedirectMessage();
				}, 1);
			};

			return;
		}
		project.onclick = () => {
			setTimeout(() => {
				const projectWindow = document.getElementById(id);
				if (projectWindow) {
					projectWindow.style.display = "block";
					raiseUpSpec(projectWindow.id);
				}
			}, 1);
		};
	});

	Array.from(document.getElementsByClassName("window")).forEach((window) => {
		dragElement(window);

		window.addEventListener("click", () => {
			raiseUpSpec(window.id);
		});

		Array.from(document.querySelectorAll(".projectwindow a")).forEach(
			(link) => {
				link.addEventListener("click", (e) => {
					document.getElementById("redirect").style.display = "block";
					document.getElementById("redirect").dataset.redirecturl = link.href;
					updateRedirectMessage();

					e.preventDefault();

					setTimeout(() => {
						raiseUpSpec("Redirect");
					}, 1);

					return false;
				});
			}
		);

		Array.from(window.getElementsByClassName("close")).forEach((button, index) => {
			if (index === 0) {
				button.addEventListener("click", () => {
					minimizeWindow(window.id);
				});
			} else {
				button.addEventListener("click", () => {
				window.classList.add("closed")

				setTimeout(() => {
				        window.classList.remove("closed")
						window.style.display = "none";
				}, 100)

					// window.style.display = "none";
					removeFromTaskbar(window.id);
				});
			}
		});
	});

	apps.forEach((app) => {
		let itemName = app.name.replace(" ", "");

		// console.log(itemName)

		if (app.onclick == "undefined") {
			return;
		}

		document.getElementById(itemName).addEventListener("click", () => {
			const appFunc = eval(app.onclick);
			appFunc();
		});
	});

	// Minimize and restore window functions
	function minimizeWindow(windowId) {
		const window = document.getElementById(windowId);

		// First add to taskbar to get the button position
		addToTaskbar(windowId);

		// Get window and target button positions
		const windowRect = window.getBoundingClientRect();
		const taskbarButton = document.getElementById(`taskbar-${windowId}`);
		const buttonRect = taskbarButton.getBoundingClientRect();

		// Calculate the translation needed
		const translateX = buttonRect.left - windowRect.left;
		const translateY = buttonRect.top - windowRect.top;

		// Create custom animation
		window.style.transition = "all 0.3s ease-out";
		window.style.transform = `translate(${translateX}px, ${translateY}px) scale(0.1)`;
		window.style.opacity = "0";

		setTimeout(() => {
			window.style.display = "none";
			window.style.transition = "";
			window.style.transform = "";
			window.style.opacity = "";
		}, 300);
	}

	function restoreWindow(windowId) {
		const window = document.getElementById(windowId);
		const taskbarButton = document.getElementById(`taskbar-${windowId}`);
		const buttonRect = taskbarButton.getBoundingClientRect();
		const windowRect = window.getBoundingClientRect();

		// Calculate starting position
		const translateX = buttonRect.left - windowRect.left;
		const translateY = buttonRect.top - windowRect.top;

		// Set initial state
		window.style.transform = `translate(${translateX}px, ${translateY}px) scale(0.1)`;
		window.style.opacity = "0";
		window.style.display = "block";

		// Remove from taskbar
		removeFromTaskbar(windowId);
		raiseUpSpec(windowId);

		// Trigger animation after a frame
		requestAnimationFrame(() => {
			window.style.transition = "all 0.3s ease-out";
			window.style.transform = "translate(0, 0) scale(1)";
			window.style.opacity = "1";

			setTimeout(() => {
				window.style.transition = "";
				window.style.transform = "";
				window.style.opacity = "";
			}, 300);
		});
	}

	function addToTaskbar(windowId) {
		const taskbarWindows = document.getElementById("taskbar-windows");

		// Check if already in taskbar
		if (document.getElementById(`taskbar-${windowId}`)) {
			return;
		}

		const window = document.getElementById(windowId);
		const titleBar = window.querySelector(".title-bar-text");
		const title = titleBar ? titleBar.textContent : windowId;

		// Get icon for the window
		const iconMap = {
			'aboutme': '👤',
			'contact': '📧',
			'pgp': '🔐',
			'projects': '📁',
			'duolingo': '🦉',
			'redirect': '🔗',
			'summize': '📝',
			'notion': '📋',
			'imdb': '🎬'
		};
		const icon = iconMap[windowId] || '📄';

		const button = document.createElement("button");
		button.id = `taskbar-${windowId}`;
		button.style.cssText = `
			min-width: 140px;
			max-width: 180px;
			height: 2.25rem;
			padding: 0 0.5rem;
			overflow: hidden;
			cursor: pointer;
			background-color: #c0c0c0;
			box-shadow: -2px -2px #e0dede, -2px 0 #e0dede, 0 -2px #e0dede, -4px -4px white, -4px 0 white, 0 -4px white, 2px 2px #818181, 0 2px #818181, 2px 0 #818181, 2px -2px #e0dede, -2px 2px #818181, -4px 2px white, -4px 4px black, 4px 4px black, 4px 0 black, 0 4px black, 2px -4px white, 4px -4px black;
			display: flex;
			align-items: center;
			gap: 0.35rem;
			border: none;
		`;

		// Create icon span
		const iconSpan = document.createElement("span");
		iconSpan.textContent = icon;
		iconSpan.style.cssText = `
			font-size: 18px;
			flex-shrink: 0;
			line-height: 1;
		`;

		// Create text span
		const textSpan = document.createElement("span");
		textSpan.textContent = title;
		textSpan.style.cssText = `
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			font-weight: bold;
			font-size: 11px;
			letter-spacing: 0.3px;
		`;

		button.appendChild(iconSpan);
		button.appendChild(textSpan);

		// Add active state styling
		button.addEventListener("mousedown", () => {
			button.style.boxShadow = "-2px -2px #818181, -2px 0 #818181, 0 -2px #818181, -4px -4px black, -4px 0 black, 0 -4px black, 2px 2px #e0dede, 0 2px #e0dede, 2px 0 #e0dede, 2px -2px #818181, -2px 2px #e0dede, -4px 2px black, -4px 4px white, 4px 4px white, 4px 0 white, 0 4px white, 2px -4px black, 4px -4px white";
		});

		button.addEventListener("mouseup", () => {
			button.style.boxShadow = "-2px -2px #e0dede, -2px 0 #e0dede, 0 -2px #e0dede, -4px -4px white, -4px 0 white, 0 -4px white, 2px 2px #818181, 0 2px #818181, 2px 0 #818181, 2px -2px #e0dede, -2px 2px #818181, -4px 2px white, -4px 4px black, 4px 4px black, 4px 0 black, 0 4px black, 2px -4px white, 4px -4px black";
		});

		button.addEventListener("click", () => {
			restoreWindow(windowId);
		});

		taskbarWindows.appendChild(button);
	}

	function removeFromTaskbar(windowId) {
		const button = document.getElementById(`taskbar-${windowId}`);
		if (button) {
			button.remove();
		}
	}


	// Function to show GitHub graph with animation
	function showGitHubGraph() {
		const githubWindow = document.getElementById("Top Languages");
		if (githubWindow) {
			githubWindow.style.display = "block";
			githubWindow.classList.add("show");
			raiseUpSpec("Top Languages");

			// Remove animation class after it completes
			setTimeout(() => {
				githubWindow.classList.remove("show");
			}, 400);
		}
	}

	// Track start button clicks
	let startButtonClicks = 0;
	const startButton = document.getElementById("start-button");
	if (startButton) {
		startButton.addEventListener("click", () => {
			startButtonClicks++;
			if (startButtonClicks === 1) {
			showGitHubGraph();

			}
		});
	}

	// Don't auto-show Duolingo anymore - wait for start button click
</script>
