const pairs = 8; // Total number of pairs
const gameContainer = d3.select("#game");
const timerElement = document.getElementById("timer");
const restartButton = document.getElementById("restart");

let cardData, timer, flippedCards, matches, timeElapsed;

// Start the game
function startGame() {
    cardData = d3.shuffle([...Array(pairs).keys()].flatMap((d) => [d, d]));
    flippedCards = [];
    matches = 0;
    timeElapsed = 0;

    updateTimer();
    clearInterval(timer);
    timer = setInterval(() => {
        timeElapsed++;
        updateTimer();
    }, 1000);

    renderCards();
}

// Update timer display
function updateTimer() {
    timerElement.textContent = `Time: ${timeElapsed}s`;
}

// Render cards dynamically
function renderCards() {
    gameContainer.selectAll("*").remove();

    gameContainer.style(
        "grid-template-columns",
        `repeat(${Math.sqrt(cardData.length)}, 1fr)`
    );

    const cards = gameContainer
        .selectAll(".card")
        .data(cardData)
        .enter()
        .append("div")
        .attr("class", "card")
        .on("click", handleCardClick);

    cards.append("div").attr("class", "front").html("<span class='heart'>❤️</span>");
    cards.append("div").attr("class", "back");
}

// Handle card clicks
function handleCardClick(event, d) {
    const card = d3.select(this);

    if (card.classed("flipped") || flippedCards.length === 2) return;

    // Flip card
    card.classed("flipped", true);
    flippedCards.push({ card, value: d });

    // Check for match
    if (flippedCards.length === 2) {
        const [first, second] = flippedCards;
        if (first.value === second.value) {
            first.card.classed("matched", true);
            second.card.classed("matched", true);
            matches++;
            flippedCards = [];

            if (matches === pairs) {
                clearInterval(timer);
                setTimeout(() => alert(`You Win! Time: ${timeElapsed}s`), 500);
            }
        } else {
            setTimeout(() => {
                first.card.classed("flipped", false);
                second.card.classed("flipped", false);
                flippedCards = [];
            }, 1000);
        }
    }
}

// Restart game on button click
restartButton.addEventListener("click", startGame);

// Initialize game on load
startGame();
