const cards = document.querySelectorAll(".card");

let matched = 0;
let cardOne, cardTwo;
let disableDeck = false;

function flipCard({target: clickedCard}) {
    if(cardOne !== clickedCard && !disableDeck) {
        clickedCard.classList.add("flip");
        if(!cardOne) {
            return cardOne = clickedCard;
        }
        cardTwo = clickedCard;
        disableDeck = true;
        let cardOneImg = cardOne.querySelector(".back-view img").src,
        cardTwoImg = cardTwo.querySelector(".back-view img").src;
        matchCards(cardOneImg, cardTwoImg);
    }
}

function matchCards(img1, img2) {
    if(img1 === img2) {
        matched++;
        if(matched == 6) {
            setTimeout(() => {
                mostrarConfetiConTexto();
                shuffleCard();
            }, 1000);
        }
        cardOne.removeEventListener("click", flipCard);
        cardTwo.removeEventListener("click", flipCard);
        cardOne = cardTwo = "";
        return disableDeck = false;
    }
    setTimeout(() => {
        cardOne.classList.add("shake");
        cardTwo.classList.add("shake");
    }, 400);

    setTimeout(() => {
        cardOne.classList.remove("shake", "flip");
        cardTwo.classList.remove("shake", "flip");
        cardOne = cardTwo = "";
        disableDeck = false;
    }, 1200);
}

function shuffleCard() {
    matched = 0;
    disableDeck = false;
    cardOne = cardTwo = "";
    let arr = [1,1,2,2,3,3,4,4,5,5,6,6];
    arr.sort(() => Math.random() > 0.5 ? 1 : -1);
    cards.forEach((card, i) => {
        card.classList.remove("flip");
        let imgTag = card.querySelector(".back-view img");
        imgTag.src = `images/img-${arr[i]}.png`;
        card.addEventListener("click", flipCard);
    });
}

shuffleCard();
    
cards.forEach(card => {
    card.addEventListener("click", flipCard);
});

function toggleFullScreen() {
  if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen().catch(err => {
          console.log(`Error al intentar activar pantalla completa: ${err.message}`);
      });
  } else {
      document.exitFullscreen();
  }
}

document.addEventListener("DOMContentLoaded", function () {
  document.getElementById("fullscreen-btn").addEventListener("click", toggleFullScreen);
});

// Mostrar confeti con texto
function mostrarConfetiConTexto(texto) {
    const duration = 5 * 1000;
    const end = Date.now() + duration;
  
    (function frame() {
      confetti({
        particleCount: 7,
        angle: 60,
        spread: 55,
        origin: { x: 0 },
        scalar: 1.2,
      });
      confetti({
        particleCount: 7,
        angle: 120,
        spread: 55,
        origin: { x: 1 },
        scalar: 1.2,
      });
  
      if (Date.now() < end) {
        requestAnimationFrame(frame);
      }
    })();
  
    console.log("¡Felicidades! Ganaste: " + texto);
  }