(function ($) {
        "use strict";
            var WidgetScrollSequenceHandler = function($scope, $) { 
                let is_editable = elementorFrontend?.isEditMode();
                // Set up Matter.js
const container = $scope[0].querySelector(".wdk-dice-game");

let getVal = container.querySelector(".dice-result-value");
let getLoader = container.querySelector(".dice-loader");
let canvas = container.querySelector("#canvas");

/* Area Styling */
let deskWidth = container.getAttribute("data-desktopw") || 600;
let tabWidth = container.getAttribute("data-tabletw") || 500;
let mobWidth = container.getAttribute("data-mobilew") || 300;

let deskHeight = container.getAttribute("data-desktoph") || 600;
let tabHeight = container.getAttribute("data-tableth") || 500;
let mobHeight = container.getAttribute("data-mobileh") || 300;

let areacolor = container.getAttribute("data-areacolor") || "#000";

/* Dice Styling */
let diceDWidth = container.getAttribute("data-dicedw") || 100;
let diceTWidth = container.getAttribute("data-dicetw") || 70;
let diceMWidth = container.getAttribute("data-dicemw") || 50;

let diceColor = container.getAttribute("data-dicecolor") || "#fff";
let diceDot = container.getAttribute("data-dicedot") || "#000";

let enableSlowMoEffect = container.getAttribute("data-slomo") === "yes";

/* Matter.js Imports */
const { Engine, Render, Runner, World, Bodies, Body, Events } = Matter;

// Global Variables
let engine, render, runner, world, boundaries;
let dice = [];
let diceX, diceY, dropAreaWidth, dropAreaHeight, diceSize;

// Clean up previous Matter.js instance
function cleanupMatter() {
  if (runner) {
    Runner.stop(runner);
    runner = null;
  }
  if (render) {
    Render.stop(render);
    render.canvas = null;
    render.context = null;
    render = null;
  }
  if (engine) {
    World.clear(engine.world);
    Engine.clear(engine);
    engine = null;
  }
}

// Update dimensions based on screen width
function updateDimensions() {
  let screenWidth = window.innerWidth;

  if (elementorFrontend.isEditMode()) {
    let editorWidth = document.querySelector(".elementor").offsetWidth;

    if (editorWidth >= 1024) {
      dropAreaWidth = deskWidth;
      dropAreaHeight = deskHeight;
      diceSize = diceDWidth;
    } else if (editorWidth < 1024 && editorWidth > 750) {
      dropAreaWidth = tabWidth;
      dropAreaHeight = tabHeight;
      diceSize = diceTWidth;
    } else {
      dropAreaWidth = mobWidth;
      dropAreaHeight = mobHeight;
      diceSize = diceMWidth;
    }
  } else {
    if (screenWidth >= 1024) {
      dropAreaWidth = deskWidth;
      dropAreaHeight = deskHeight;
      diceSize = diceDWidth;
    } else if (screenWidth < 1024 && screenWidth >= 768) {
      dropAreaWidth = tabWidth;
      dropAreaHeight = tabHeight;
      diceSize = diceTWidth;
    } else {
      dropAreaWidth = mobWidth;
      dropAreaHeight = mobHeight;
      diceSize = diceMWidth;
    }
  }

  diceX = dropAreaWidth / 2;
  diceY = 100; // Initial drop height
}

// Initialize Matter.js
function initMatter() {
  cleanupMatter(); // Clean up before reinitializing

  updateDimensions(); // Get updated dimensions

  // Create new engine and world
  engine = Engine.create();
  world = engine.world;

  // Set up renderer using existing canvas
  render = Render.create({
    canvas: canvas,
    engine: engine,
    options: {
      width: dropAreaWidth,
      height: dropAreaHeight,
      background: areacolor,
      wireframes: false,
    },
  });
  Render.run(render);

  runner = Runner.create();
  Runner.run(runner, engine);

  // Add boundaries (walls)
  boundaries = [
    Bodies.rectangle(dropAreaWidth / 2, dropAreaHeight, dropAreaWidth, 50, {
      isStatic: true,
      render: { fillStyle: "transparent" },
    }),
    Bodies.rectangle(dropAreaWidth / 2, 0, dropAreaWidth, 50, {
      isStatic: true,
      render: { fillStyle: "transparent" },
    }),
    Bodies.rectangle(0, dropAreaHeight / 2, 50, dropAreaHeight, {
      isStatic: true,
      render: { fillStyle: "transparent" },
    }),
    Bodies.rectangle(dropAreaWidth, dropAreaHeight / 2, 50, dropAreaHeight, {
      isStatic: true,
      render: { fillStyle: "transparent" },
    }),
  ];

  World.add(world, boundaries);

  // Initial roll
  rollDice();
}

// Create dice with dynamic size
function createDice(x, y) {
  const dice = Bodies.rectangle(x, y, diceSize, diceSize, {
    restitution: 0.6,
    render: {
      sprite: {
        texture: generateDiceTexture(),
        xScale: 1,
        yScale: 1,
      },
    },
  });

  World.add(world, dice);
  return dice;
}

// Generate dice texture dynamically
function generateDiceTexture(number) {
  if (number === undefined || number < 1 || number > 6) {
    return;
  }

  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  canvas.width = diceSize;
  canvas.height = diceSize;

  // Draw background
  ctx.fillStyle = diceColor;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // Set dot color
  ctx.fillStyle = diceDot;

  // Calculate proportional dot positions
  const center = diceSize / 2;
  const offset = diceSize * 0.25;
  const radius = diceSize * 0.08;

  // Helper function to draw a dot
  function drawDot(x, y) {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fill();
  }

  // Define dot positions
  const positions = {
    1: [[center, center]],
    2: [
      [center - offset, center - offset],
      [center + offset, center + offset],
    ],
    3: [
      [center - offset, center - offset],
      [center, center],
      [center + offset, center + offset],
    ],
    4: [
      [center - offset, center - offset],
      [center - offset, center + offset],
      [center + offset, center - offset],
      [center + offset, center + offset],
    ],
    5: [
      [center - offset, center - offset],
      [center - offset, center + offset],
      [center + offset, center - offset],
      [center + offset, center + offset],
      [center, center],
    ],
    6: [
      [center - offset, center - offset],
      [center - offset, center],
      [center - offset, center + offset],
      [center + offset, center - offset],
      [center + offset, center],
      [center + offset, center + offset],
    ],
  };

  // Draw the appropriate dots
  positions[number].forEach(([x, y]) => drawDot(x, y));

  return canvas.toDataURL();
}

// Roll Dice function
function rollDice() {
  getVal.innerText = "";
  getVal.classList.remove("active");
  getLoader.classList.add("active");

  // Clear old dice
  dice.forEach((d) => World.remove(world, d));
  dice = [];

  const rolledNumbers = [];

  for (let i = 0; i < 2; i++) {
    const number = Math.floor(Math.random() * 6) + 1;
    const newDice = createDice(
      diceX + i * Number(diceSize) - Number(diceSize / 2),
      diceY
    );

    // Assign generated number to the dice's texture
    newDice.render.sprite.texture = generateDiceTexture(number);
    newDice.dots = number;
    rolledNumbers.push(number);

    Body.setVelocity(newDice, {
      x: Math.random() * 10 - 5,
      y: Math.random() * 10,
    });
    Body.setAngularVelocity(newDice, Math.random() * 0.2 - 0.1);
    dice.push(newDice);
  }

  if (enableSlowMoEffect) {
    engine.timing.timeScale = 0.5;
    setTimeout(() => {
      engine.timing.timeScale = 1;
    }, 2000);
  }

  setTimeout(() => {
    getLoader.classList.remove("active");
    getVal.classList.add("active");
    getVal.innerText = `${rolledNumbers.join(" + ")}`;
  }, 2000);
}

// Handle window resize
function handleResize() {
  initMatter(); // Reinitialize on resize
}

window.addEventListener("resize", handleResize);

// Listen for Elementor editor changes if applicable
if (elementorFrontend.isEditMode()) {
    let newWidth = document.querySelector(".elementor").offsetWidth;
    if (newWidth !== dropAreaWidth) {
      handleResize();
    }
}

// Roll on button click
let btn = $scope[0].querySelector("#roll-button");
btn.addEventListener("click", rollDice);

// Initial initialization
initMatter();


  
            };	
        $(window).on('elementor/frontend/init', function () {
          elementorFrontend.hooks.addAction('frontend/element_ready/wb-gq297q25.default', WidgetScrollSequenceHandler);
        });
    })(jQuery);