const cards = document.querySelectorAll('div.ficha');

for (const card of cards)
{
	card.addEventListener('click', handleCardClick);
}

const eastereggContainers = document.querySelectorAll('div.ficha:has(.easteregg), div.ficha.easteregg');

const messageBox = document.getElementById('message-box');

let clickCount = 0;
let lastClickTime = 0;
const clickThreshold = 800;
const expandDuration = 5000;

let hideTimeoutId = null;

function hideEastereggs() {
	for (const div of eastereggContainers)
	{
		div.classList.remove('easteregg-visible');
	}
}

function expandEastereggs() {
	for (const div of eastereggContainers)
	{
		div.classList.add('easteregg-visible');
	}

	// Clear any existing timeout and set a new one
	if (hideTimeoutId) {
		clearTimeout(hideTimeoutId);
	}

	hideTimeoutId = setTimeout(
		() => { hideEastereggs(); },
		expandDuration
	);

	clickCount = 0;
}

function handleCardClick(event) {
	const now = Date.now();

	let element = event.target;

	while (!element.classList.contains("ficha"))
	{ element = element.parentElement }

	element.classList.add('animate-shake');

	setTimeout(
		() => { element.classList.remove('animate-shake'); },
		300
	);

	// Determine if the click is 'in a row'
	if (now - lastClickTime < clickThreshold)
	{ clickCount++; }
	else
	{
		clickCount = 1;
		if (element.classList.contains('easteregg-visible'))
		{ hideEastereggs(); }
	}
	
	lastClickTime = now;

	// Check for the 3-click trigger
	if (clickCount >= 3)
	{ expandEastereggs(); }
}