---
import Layout from '../../layouts/Layout.astro';
---
<Layout title="Drag Game">
	<main>
		<div>
      <div>
        
        <!-- <img style="width: 100%; height: 150px;" src="/assets/topbar1.jpg" alt=""> -->
        <div class="flex justify-center">
          <div class="container mx-auto px-4">
            <!-- <div class="flex flex-row place-content-between xl:px-40 pt-10">
              <img src="/assets/top_match.jpg" alt="" />
              <img src="/assets/top_logo.jpg" alt="" />
            </div> -->
          </div>
          <!-- <h2>{data.name}</h2> -->
          <!-- <h2 class="text-center text-4xl font-bold text-[#7c4c23] xl:w-2/3">Match the words on the left side with their rhyming words on the right by drawing lines</h2> -->
        </div>
      </div>
      <div id="overlap">
        <!-- <div id="result"></div> -->
        <div id="verryGood" class="displayNone "> 
          <!-- <p>Congratulations!</p>
          <p>You win the Game!</p> -->
          <!-- <img class="" src="/assets/party-feestje.gif" alt=""  style="width: 200px; height: 200px;" /> -->
          <!-- <div class="flex flex-row">
            <a href="" >
              <svg fill="#7c4c23" height="64px" width="64px" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 74.999 74.999" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M33.511,71.013c15.487,0,28.551-10.563,32.375-24.859h9.113L61.055,22L47.111,46.151h8.006 c-3.44,8.563-11.826,14.628-21.605,14.628c-12.837,0-23.28-10.443-23.28-23.28c0-12.836,10.443-23.28,23.28-23.28 c6.604,0,12.566,2.768,16.809,7.196l5.258-9.108c-5.898-5.176-13.619-8.32-22.065-8.32C15.034,3.987,0,19.019,0,37.5 C-0.002,55.981,15.03,71.013,33.511,71.013z"></path> </g> </g></svg>
            </a>
            <a href="" >
              <svg width="64px" height="64px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <circle cx="12" cy="12" r="10" stroke="#7c4c23" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></circle> <path d="M17 12H7M17 12L13 8M17 12L13 16" stroke="#7c4c23" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>
            </a>
          </div>
          <div>
          </div> -->
        </div>
        <div id="good" class="displayNone">
          <!-- <p>Oops!</p>
          <p>You Lost the Game!</p>
          <img class="" src="/assets/output-onlinegiftools.gif" alt=""  style="width: 200px; height: 200px;" />
          <a href="" >
            <svg fill="#7c4c23" height="64px" width="64px" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 74.999 74.999" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M33.511,71.013c15.487,0,28.551-10.563,32.375-24.859h9.113L61.055,22L47.111,46.151h8.006 c-3.44,8.563-11.826,14.628-21.605,14.628c-12.837,0-23.28-10.443-23.28-23.28c0-12.836,10.443-23.28,23.28-23.28 c6.604,0,12.566,2.768,16.809,7.196l5.258-9.108c-5.898-5.176-13.619-8.32-22.065-8.32C15.034,3.987,0,19.019,0,37.5 C-0.002,55.981,15.03,71.013,33.511,71.013z"></path> </g> </g></svg>
          </a> -->
        </div>
        <div id="lost" class="displayNone"></div>
      </div>
		</div>
		<script is:inline src="/assets/js/phaser_3.60.0.js"></script>
	</main>
</Layout>
<script is:inline>
const targetZones = [
  {
    x: 0,
    y: 170,
    name: "target1",
    block: null,
  },
  {
    x: 0,
    y: 340,
    name: "target2",
    block: null,
  },
  {
    x: 0,
    y: 510,
    name: "target3",
    block: null,
  },
  {
    x: 0,
    y: 680,
    name: "target4",
    block: null,
  },
];
const blockMatches = [
  {
    blockName: "blocks1",
    targetName: "target1",
  },
  {
    blockName: "blocks2",
    targetName: "target2",
  },
  {
    blockName: "blocks3",
    targetName: "target3",
  },
  {
    blockName: "blocks4",
    targetName: "target4",
  },
];
// console.log(blockMatches.blockName, blockMatches.targetName)
var assetsList = {}
const params = new URLSearchParams(window.location.search);
    const paramsID = params.get('id');
    const data =       fetch(`https://management.beanstalkedu.com/items/game_drag/${encodeURIComponent(paramsID)}`)
    .then(response => response.json())
    .then(({data}) => {
      const {left_image1, left_image2, left_image3, left_image4, right_image1, right_image2, right_image3, right_image4} = data;
      assetsList.left_image1 = "https://management.beanstalkedu.com/assets/" + left_image1    + "?width=100";
      assetsList.left_image2 = "https://management.beanstalkedu.com/assets/" + left_image2    + "?width=100";
      assetsList.left_image3 = "https://management.beanstalkedu.com/assets/" + left_image3    + "?width=100";
      assetsList.left_image4 = "https://management.beanstalkedu.com/assets/" + left_image4    + "?width=100";
      assetsList.right_image1 = "https://management.beanstalkedu.com/assets/" + right_image1  + "?width=100";
      assetsList.right_image2 = "https://management.beanstalkedu.com/assets/" + right_image2  + "?width=100";
      assetsList.right_image3 = "https://management.beanstalkedu.com/assets/" + right_image3  + "?width=100";
      assetsList.right_image4 = "https://management.beanstalkedu.com/assets/" + right_image4  + "?width=100";
      const config = {
        type: Phaser.AUTO,
        width: window.innerWidth,
        height: window.innerHeight,
        backgroundColor: '#ffffff',
        parent: "phaser-example",
        scale: {
          mode: Phaser.Scale.FIT,
          autoCenter: Phaser.Scale.CENTER_HORIZONTALLY,
          },
        scene: MyGame,
      };
      const game = new Phaser.Game(config);    
      
    })
    .catch(error => {

      console.error('Error fetching initial data:', error);
    });
class MyGame extends Phaser.Scene {
  constructor() {
    super();
  }
  preload() {
    var progressBar = this.add.graphics();
            var progressBox = this.add.graphics();
            progressBox.fillStyle(0x222222, 0.8);
            progressBox.fillRect(240, 270, 320, 50);
            
            var width = this.cameras.main.width;
            var height = this.cameras.main.height;
            var loadingText = this.make.text({
                x: width / 2,
                y: height / 2 - 50,
                text: 'Loading...',
                style: {
                    font: '20px monospace',
                    fill: '#ffffff'
                }
            });
            loadingText.setOrigin(0.5, 0.5);
            var percentText = this.make.text({
                x: width / 2,
                y: height / 2 - 5,
                text: '0%',
                style: {
                    font: '18px monospace',
                    fill: '#ffffff'
                }
            });
            percentText.setOrigin(0.5, 0.5);
            var assetText = this.make.text({
                x: width / 2,
                y: height / 2 + 50,
                text: '',
                style: {
                    font: '18px monospace',
                    fill: '#ffffff'
                }
            });
            assetText.setOrigin(0.5, 0.5);
            this.load.on('progress', function (value) {
                percentText.setText(parseInt(value * 100) + '%');
                progressBar.clear();
                progressBar.fillStyle(0xffffff, 1);
                progressBar.fillRect(250, 280, 300 * value, 30);
            });
            this.load.on('fileprogress', function (file) {
                assetText.setText('Loading asset: ' + file.key);
            });
            this.load.on('complete', function () {
                progressBar.destroy();
                progressBox.destroy();
                loadingText.destroy();
                percentText.destroy();
                assetText.destroy();
            });
            // this.load.image('logo', 'zenvalogo.png');
            for (var i = 0; i < 5; i++) {
                this.load.image('logo'+i, '/assets/background.jpg');
            }
    this.load.image("topMatch", "/assets/top_match.jpg");
    this.load.image("topLogo", "/assets/top_logo.jpg");
    this.load.image("tick", '/assets/tick.png');
    // this.load.image("bg", '/assets/bgwhite.jpg');
    // this.load.image("target1", assetsList.right_image1);
    // this.load.image("target2", '/assets/hay.png');
    // this.load.image("target3", '/assets/mat.png');
    // this.load.image("target4", '/assets/star.png');
    this.load.image("border", '/assets/squar.png');

    this.load.spritesheet("target1", assetsList.right_image1,{
      frameWidth: 100,
      frameHeight: 100,
    });
    this.load.spritesheet("target2", assetsList.right_image2,{
      frameWidth: 100,
      frameHeight: 100,
    });
    this.load.spritesheet("target3", assetsList.right_image3,{
      frameWidth: 100,
      frameHeight: 100,
    });
    this.load.spritesheet("target4", assetsList.right_image4,{
      frameWidth: 100,
      frameHeight: 100,
    });

    this.load.spritesheet("blocks1", assetsList.left_image1,{
      frameWidth: 100,
      frameHeight: 100,
    });
    this.load.spritesheet("blocks2", assetsList.left_image2, {
      frameWidth: 100,
      frameHeight: 100,
    });
    this.load.spritesheet("blocks3", assetsList.left_image3, {
      frameWidth: 100,
      frameHeight: 100,
    });
    this.load.spritesheet("blocks4", assetsList.left_image4, {
      frameWidth: 100,
      frameHeight: 100,
    });
  }
  create() {
    const params = new URLSearchParams(window.location.search);
      const paramsID = params.get('id');
  
      fetch(`https://management.beanstalkedu.com/items/game_drag/${encodeURIComponent(paramsID)}`)
        .then(response => response.json())
        .then(({ data }) => {

          const screenCenterX = this.cameras.main.worldView.x + this.cameras.main.width / 2;

          // Base font size for your text
          const baseFontSize = 20;
          // Calculate responsive font size based on screen width
          const responsiveFontSize = (window.innerWidth / 950) * baseFontSize; // Adjust 800 to your desired reference width
          const descrptText = this.add.text(screenCenterX, 70, data.description, {
            font: `${responsiveFontSize}px quicksand`,
            fill: '#7c4c23',
          }).setOrigin(0.5);
      
          // Left Image Name
          this.add.text(displayW / 14, 240, data.left_image1_name).setTint(0x7c4c23);
          this.add.text(displayW / 14, 409, data.left_image2_name).setTint(0x7c4c23);      
          this.add.text(displayW / 14, 579, data.left_image3_name).setTint(0x7c4c23); 
          this.add.text(displayW / 14, 750, data.left_image4_name).setTint(0x7c4c23);
          
          //Right Image Name
          this.add.text(displayW * 0.9-50, 240, data.right_image1_name).setTint(0x7c4c23);
          this.add.text(displayW * 0.9-50, 409, data.right_image2_name).setTint(0x7c4c23);
          this.add.text(displayW * 0.9-50, 579, data.right_image3_name).setTint(0x7c4c23);
          this.add.text(displayW * 0.9-50, 750, data.right_image4_name).setTint(0x7c4c23);
        })
        .catch(error => {
          console.error('Error fetching initial data:', error);
        });
      const displayW = window.innerWidth;
      const displayH = window.innerHeight;
      // this.add.image(displayW / 2, displayH / 2, "bg").setScale(2.4);
      this.add.image(displayW / 6, 30, "topMatch").setScale();
      this.add.image(displayW * 0.80-5, 30, "topLogo").setScale();
      this.add.image(displayW * 0.9-32, 170, "target1"),
      this.add.image(displayW * 0.9-32, 170, "border").setAlpha(0.4).setScale(0.7),
      this.add.image(displayW * 0.9-32, 340, "target2"),
      this.add.image(displayW * 0.9-32, 340, "border").setAlpha(0.4).setScale(0.7),
      this.add.image(displayW * 0.9-32, 510, "target3"),
      this.add.image(displayW * 0.9-32, 510, "border").setAlpha(0.4).setScale(0.7),
      this.add.image(displayW * 0.9-32, 680, "target4"),
      this.add.image(displayW * 0.9-32, 680, "border").setAlpha(0.4).setScale(0.7);
    const blocks = [
      {
        x: displayW / 15 - 10,
        y: 120,
        textureKey: "blocks1",
        id: "block1",
      },
      {
        x: displayW / 15 - 10,
        y: 280,
        textureKey: "blocks2",
        id: "block2",
      },
      {
        x: displayW / 15 - 10,
        y: 460,
        textureKey: "blocks3",
        id: "block3",
      },
      {
        x: displayW / 15 - 10,
        y: 640,
        textureKey: "blocks4",
        id: "block4",
      },
    ];
    const droppedBlocks = [];
    const targetZoneBorders = [];
    targetZones.forEach((targetZone) => {
      const targetImage = this.add.image(targetZone.x, targetZone.y, targetZone.name).setAlpha(0);
      const targetBorder = this.add.image(targetZone.x = displayW * 0.9 - 172, targetZone.y, "border").setAlpha(0.2).setScale(0.7);
      targetZoneBorders.push(targetBorder);
      targetZone.block = null;
    }),
    blocks.forEach((block, index) => {
      const newBlock = this.add.sprite(block.x, block.y, block.textureKey, 1).setOrigin(0, 0).setInteractive({ draggable: true });
      this.add.sprite(block.x, block.y, block.textureKey, 1).setOrigin(0, 0).setAlpha(0.3);
      newBlock.on("drag", (pointer, dragX, dragY) => {
        newBlock.setScale(1.3);
        newBlock.x = dragX;
        newBlock.y = dragY;
      });
      newBlock.on("dragend", () => {
        newBlock.setScale(1.0);
        let droppedOnTargetZone = false;
        targetZones.forEach((targetZone, targetIndex) => {
          if (
            Phaser.Geom.Intersects.RectangleToRectangle(
              newBlock.getBounds(),
              new Phaser.Geom.Rectangle(targetZone.x, targetZone.y, 200, 100)
            )
          ) {
            if (targetZone.block === null) {
              newBlock.setPosition(targetZone.x - 50, targetZone.y - 50);
              newBlock.disableInteractive();
              targetZone.block = newBlock;
              droppedBlocks.push(newBlock);
              if (isMatch(newBlock.texture.key, targetZone.name)) {
                // console.log(isMatch(newBlock.texture.key, targetZone.name))
                
                // if(isMatch(newBlock.texture.key, targetZone.name)){
                //   score++;
                //   // console.log(score);
                //   if(score === 4){
                //       const overlap = document.getElementById("overlap");
                //       overlap.style.display = "block";
                //       let finalDom;
                //   }
                //   console.log(score)
                //   if(score >= 2){
                //     console.log("Win")
                //   } else{
                //     console.log("Loose")
                //   }
                // }
                //counter++; // Increment the counter when a match is found
              }
            } else {
              newBlock.setPosition(block.x, block.y);
            }
            droppedOnTargetZone = true;
            targetZoneBorders[targetIndex].setVisible(true);
            targetZoneBorders[targetIndex].setAlpha(1);
            return;
          }
        });

        if (!droppedOnTargetZone) {
          newBlock.setPosition(block.x, block.y);
        }
        if (droppedBlocks.length === targetZones.length) 
        {
          displayResult(droppedBlocks);
        }
      });
    })   
  }
}
const displayResult = (droppedBlocks) => {
  // const overlap = document.getElementById("overlap");
  // overlap.style.display = "block";
  // let finalDom;
  droppedBlocks.forEach((block) => {
    const targetZone =  targetZones.find((zone) => zone.name === block.texture.key);
  });
};
let score = 0;
let counter = 0;

const isMatch = (blockName, targetName) => {
if(isMatch){
  counter++;
  // console.log(counter)


  if(counter === 4){
    
      const overlap = document.getElementById("overlap");
      overlap.style.display = "block";
      // console.log("Done")
  }
}
  const match = blockMatches.find((m) => m.blockName === blockName && m.targetName === targetName);

  let scoreTotal=0;
  if(match){
    scoreTotal++;
    // console.log(scoreTotal)
  }
  console.log(scoreTotal)
  // console.log(match)
  if(match){
    score++;
    console.log(score)
    let day;
    switch (score) {
      case 0:
        day = "Points - 1";
        break;
      case 2:
        day = "Points - 2";
        break;
      case 4:
        day = "Points - 4";

    }
    console.log(day)
      finalDom = document.getElementById("good");
      finalDom.classList.add("good");
      document.getElementById("good").innerHTML = day;
      document.getElementById("good").style.color = '#7c4c23'
// console.log(totalScore)
    // if(score === 2){
    //   finalDom = document.getElementById("good");
    //   finalDom.classList.add("good");
    //   document.getElementById("good").innerHTML = " Good";
    //   document.getElementById("good").style.color = '#7c4c23'


    //   // let img = document.createElement("img");
    //   // img.src = "/assets/party-feestje.gif";
    //   // img.width = 100;
    //   // document.getElementById('win').appendChild(img);
    // }
    // else if(score === 4) {
    //   finalDom = document.getElementById("verryGood");
    //   finalDom.classList.add("verryGood");
    //   document.getElementById("verryGood").innerHTML = "Verry Good";
    //   document.getElementById("verryGood").style.color = '#7c4c23'
    // }
    // else {
    //   // finalDom = document.getElementById("lost");
    //   // finalDom.classList.add("lost");
    //   // document.getElementById("lost").innerHTML = " Lost";
    //   // document.getElementById("lost").style.color = '#7c4c23'
    //   // console.log("Losttttt")
    // }

  } else{
    score = score
  }
  return match !== undefined;
};
</script>
<style href="https://fonts.googleapis.com/css?family=Quicksand&display=swap" rel="stylesheet" >
  * {
margin: 0;
padding: 0;
cursor: -webkit-grab; cursor: grab;
font-family: quicksand;
}
/* body {
margin: 0;
background: #020202;
cursor: crosshair;
} */
/* canvas{display:block} */
/* h1 {
position: absolute;
top: 20%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
font-family: "Source Sans Pro";
font-size: 5em;
font-weight: 900;
-webkit-user-select: none;
user-select: none;
} */
  #overlap {       
    display: none;
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #7c4c23;
    text-align: center;
    margin-top: 7%;
  }
  #overlap .verryGood{
    display: flex;
    flex-direction: column;
    place-items: center;
    font-size: 40px;
    font-weight: bolder;
    height: fit-content;
  }
  #overlap .good{
    display: flex;
    flex-direction: column;
    justify-content: center;
    place-items: center;
    font-size: 40px;
    font-weight: bolder;
  }
  #overlap .lost{
    display: flex;
    flex-direction: column;
    justify-content: center;
    place-items: center;
    font-size: 40px;
    font-weight: bolder;
  }
  .displayNone {
    display: none;
  }
  #result {
    font-size: 30px;
    font-weight: bold;
  }
</style>