---
import ItemCard from '../../components/ItemCard.astro';
import LoggedIn from '../../layouts/LoggedIn.astro';
import { Planet } from '../../lib/classes/managers/PlanetManager';
import SystemManager from '../../lib/classes/managers/SystemManager';
import { getAllBuildings } from '../../lib/db/buildings';
import { getName, getObj } from '../../lib/utils/langDriver';
import DBBuilding from '../../types/db/DBBuilding';

const { token, lang } = Astro.locals;
const active: SystemManager | Planet = Astro.locals.active;

if(active instanceof SystemManager) {
	return Astro.redirect('/game');
}

const buildingsList = await getAllBuildings();

if(Astro.request.method === "POST") {
    const selectedBuildingId = (await Astro.request.formData()).get('id') as string | null;

    const request = await (await fetch(Astro.url.origin + '/api/build/createBuilding', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify({
            planet: active._id,
            building: selectedBuildingId
        })
    })).json();

    console.log(request);
}

const modalSet: { [key: string]: { resources: Array<any>, research: Array<any>, buildings: Array<any>, energy: number } } = {};

for(const building of buildingsList) {
	modalSet[building.id] = {
		resources: building.requirements.resources.map(resource => {
			return {
				id: resource.id,
				amount: Math.pow(building.multiplier, (active.buildings.getBuildingById(building.id)?.level ?? 0) ) * resource.amount
			};
		}),
		research: building.requirements.research,
		buildings: building.requirements.buildings,
		energy: building.energy
	};
}

const buildingsByCategory = buildingsList.reduce((acc: { [key: string]: Array<DBBuilding & { level: number }> }, building) => {
	if(!acc[building.category]) acc[building.category] = [];
	acc[building.category].push({ ...building, level: active.buildings.getBuildingById(building.id)?.level ?? 0 });
	return acc;
}, {});
---

<LoggedIn id="buildings" title="Buildings">
	<div id="building-modal-background">
		<div id="building-modal-details" data-building-id="">
			<h3>Required resources</h3>
			<div class="building-modal-text" id="building-modal-req-resources">None</div>
			<h3>Required buildings</h3>
			<div class="building-modal-text" id="building-modal-req-buildings">None</div>
			<h3>Required research</h3>
			<div class="building-modal-text" id="building-modal-req-research">None</div>
		</div>
	</div>
	{Object.entries(buildingsByCategory).map(([category, buildings]) => <>
		<h1>{getName(lang, 'buildings', `cat-${category}`)}</h1>
		<div class="building-cat">
			{buildings.map(building => (
				<ItemCard
					category="buildings"
					id={building.id}
					level={building.level.toString()}
					name={getObj(lang, "buildings", building.id).name}
					description={getObj(lang, "buildings", building.id).description ?? ""}
					image={`/images/buildings/${building.id}.jpeg`}
					button_type="general"
					button_name="nav-build" />
			))}
		</div>
	</>)}
</LoggedIn>
<style>
.building-cat {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	row-gap: 40px;
	column-gap: 2%;
}

#building-modal-background {
	display: none;
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	z-index: 100;
}

#building-modal-details {
	display: none;
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 80%;
	max-width: 800px;
	background: rgba(0, 0, 0, 0.9);
	border-radius: 8px;
	padding: 1rem;
	z-index: 101;
	color: white;
}

h1 {
	font-size: 2rem;
	font-weight: 700;
	line-height: 1;
	text-align: center;
	margin-bottom: 1em;
	color: white;
}

.building-modal-text {
	font-size: 1.5rem;
}
</style>
<script define:vars={{ modalSet, lang }}>
	const modalResources = document.getElementById("building-modal-req-resources");
	const modalBuildings = document.getElementById("building-modal-req-buildings");
	const modalResearch = document.getElementById("building-modal-req-research");

	document.querySelectorAll('.item-card-info-button').forEach((el) => {
        el.addEventListener('click', () => {
            // modal
            const modalDiv = document.getElementById('building-modal-details');
            if(!modalDiv) return;
            modalDiv.style.display = 'block';

			const reqResources = modalSet[el.parentElement.parentElement.parentElement.dataset.id]?.resources ?? [];
			const reqBuildings = modalSet[el.parentElement.parentElement.parentElement.dataset.id]?.buildings ?? [];
			const reqResearch = modalSet[el.parentElement.parentElement.parentElement.dataset.id]?.research ?? [];

			modalResources.innerHTML = reqResources.length === 0 ? "None" : reqResources.map(resource => {
				return `${lang['resources'].find(r => r.id === resource.id).name}: ${resource.amount}`;
			}).join("<br />");

			modalBuildings.innerHTML = reqBuildings.length === 0 ? "None" : reqBuildings.map(building => {
				return `${lang['buildings'].find(b => b.id === building.id).name}: ${building.level}`;
			}).join("<br />");

			modalResearch.innerHTML = reqResearch.length === 0 ? "None" : reqResearch.map(research => {
				return `${lang['research'].find(r => r.id === research.id).name}: ${research.level}`;
			}).join("<br />");

            // background
            const backgroundDiv = document.getElementById('building-modal-background');
            if(!backgroundDiv) return;
            backgroundDiv.style.display = 'block';
        });
    });

    // close modal on background click
    const bg = document.getElementById('building-modal-background');
    
    bg?.addEventListener('click', () => {
        const modalDiv = document.getElementById('building-modal-details');
        if(!modalDiv) return;
        modalDiv.style.display = 'none';

        const backgroundDiv = document.getElementById('building-modal-background');
        if(!backgroundDiv) return;
        backgroundDiv.style.display = 'none';
    });
</script>