// Preload Scene: Loads all assets and shows loading bar
class PreloadScene extends Phaser.Scene {
  constructor() {
    super({ key: 'PreloadScene' });
  }
  preload() {
    // Add loading bar background
    const loadingBarBg = this.add.graphics();
    loadingBarBg.fillStyle(0x222222, 1);
    loadingBarBg.fillRect(200, 220, 240, 50);

    // Add loading bar
    const loadingBar = this.add.graphics();

    // Display loading text
    const loadingText = this.add.text(320, 200, 'Loading...', { fontSize: '20px', fill: '#ffffff' });
    loadingText.setOrigin(0.5, 0.5);

    // Update loading bar as assets are loaded
    this.load.on('progress', (value) => {
      loadingBar.clear();
      loadingBar.fillStyle(0xffffff, 1);
      loadingBar.fillRect(200, 220, 240 * value, 50);
    });

    // Remove loading bar once complete
    this.load.on('complete', () => {
      loadingBar.destroy();
      loadingBarBg.destroy();
      loadingText.destroy();
    });

    const leftButtonDataURI = 'data:image/svg+xml;base64,' + btoa(`
    <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
      <rect x="5" y="5" width="90" height="90" fill="#333333" stroke="#ffffff" stroke-width="5"/>
      <polygon points="60,30 40,50 60,70" fill="#ffffff"/>
    </svg>
    `);

    const rightButtonDataURI = 'data:image/svg+xml;base64,' + btoa(`
    <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
      <rect x="5" y="5" width="90" height="90" fill="#333333" stroke="#ffffff" stroke-width="5"/>
      <polygon points="40,30 60,50 40,70" fill="#ffffff"/>
    </svg>
    `);

    // Load assets
    this.load.image('mainMenu', 'assets/images/main-menu.png');
    this.load.image('playButton', 'assets/images/play-button.png');
    this.load.image('ghostHouse', 'assets/images/ghost-house.jpg');
    this.load.image('ghostHouseOutside', 'assets/images/ghost-house-outside.jpg');
    this.load.image('ghost', 'assets/images/ghost.webp');
    this.load.image('the-ghost', 'assets/images/the-ghost.png');
    this.load.image('weapon', 'assets/images/weapon.png');
    this.load.audio('bgMusic', ['assets/audio/background-music.wav']);
    this.load.image('leftButton', leftButtonDataURI);
    this.load.image('rightButton', rightButtonDataURI);
  }
  create() {
    // Start Main Menu Scene after loading
    this.scene.start('MainMenuScene');
  }
}

// Main Menu Scene: Displays main menu with play button and background music
class MainMenuScene extends Phaser.Scene {
  constructor() {
    super({ key: 'MainMenuScene' });
  }
  create() {
    // Add main menu background image
    this.add.image(320, 240, 'mainMenu').setDisplaySize(640, 480); // Centered

    // Create a drop shadow for the play button
    const shadow = this.add.graphics();
    shadow.fillStyle(0x000000, 0.5); // Black color with some transparency
    shadow.fillEllipse(320, 430, 200, 60); // Draw shadow ellipse (x, y, width, height)

    // Add play button
    const playButton = this.add.image(320, 390, 'playButton').setInteractive();

    // Scale play button to make it much smaller
    playButton.setScale(0.25); // Adjust the scale for a smaller button

    // Add click listener to play button
    playButton.on('pointerdown', () => {
      console.log('Play button clicked!');
      this.scene.start('InGhostHouseScene'); // Start In Ghost House Scene on button click
    });

    // Add background music
    this.bgMusic = this.sound.add('bgMusic', { loop: true, volume: 0.5 });
    this.bgMusic.play();
  }
  // Optional: Stop music when scene is shutdown
  shutdown() {
    if (this.bgMusic) {
      this.bgMusic.stop();
    }
  }
}

// In Ghost House Scene: Shows the ghost's house and allows user interaction with the ghost
class InGhostHouseScene extends Phaser.Scene {
  constructor() {
    super({ key: 'InGhostHouseScene' });
  }

  create() {
    // Background: Ghost House
    this.add.image(320, 240, 'ghostHouse').setDisplaySize(640, 480);

    this.weapon = this.add.image(350, 325, 'weapon').setOrigin(0.5, 0.5);
    this.weapon.setScale(0.2);
    this.weapon.angle = 85;
    this.weaponPicked = false;

    // Ghost character setup in bed
    this.ghost = this.add.image(250, 300, 'ghost').setOrigin(0.5, 0.5);
    this.ghost.setScale(0.2); // Adjust size for small ghost
    this.ghost.angle = -90; // Rotate ghost to be lying down

    // Wake-up button setup
    this.wakeUpButton = this.add.text(320, 450, 'Wake Up', { fontSize: '20px', fill: '#ffffff' })
      .setOrigin(0.5)
      .setInteractive()
      .on('pointerdown', () => this.wakeUpGhost());

    // "Go Back to Sleep" button setup (initially hidden)
    this.sleepButton = this.add.text(320, 450, 'Go Back to Sleep', { fontSize: '20px', fill: '#ffffff' })
      .setOrigin(0.5)
      .setInteractive()
      .setVisible(false)
      .on('pointerdown', () => this.putGhostToSleep());

    this.pickWeaponButton = this.add.text(320, 450, 'Pick Weapon', { fontSize: '20px', fill: '#ffffff' })
      .setOrigin(0.5)
      .setInteractive()
      .setVisible(false)
      .on('pointerdown', () => this.pickWeapon());

    this.dropWeaponButton = this.add.text(320, 450, 'Drop Weapon', { fontSize: '20px', fill: '#ffffff' })
      .setOrigin(0.5)
      .setInteractive()
      .setVisible(false)
      .on('pointerdown', () => this.dropWeapon());
    
    this.openDoorButton = this.add.text(320, 450, 'Open Door', { fontSize: '20px', fill: '#ffffff' })
      .setOrigin(0.5)
      .setInteractive()
      .setVisible(false)
      .on('pointerdown', () => this.openDoor());

    // Keyboard controls for movement
    this.cursors = this.input.keyboard.createCursorKeys();

    // Left and Right buttons for touch input
    this.leftButton = this.add.image(100, 400, 'leftButton').setInteractive();
    this.rightButton = this.add.image(540, 400, 'rightButton').setInteractive();

    // Scale and transparency for the buttons
    this.leftButton.setScale(0.5).setAlpha(0.7);
    this.rightButton.setScale(0.5).setAlpha(0.7);

    // Button down events
    this.leftButton.on('pointerdown', () => {
      this.isMovingLeft = true;
    });
    this.rightButton.on('pointerdown', () => {
      this.isMovingRight = true;
    });

    // Button up events (stop movement when button is released)
    this.leftButton.on('pointerup', () => {
      this.isMovingLeft = false;
    });
    this.rightButton.on('pointerup', () => {
      this.isMovingRight = false;
    });

    // Track if ghost is awake
    this.isAwake = false;
    this.isMovingLeft = false;
    this.isMovingRight = false;
  }

  update() {
    // If the ghost is awake, enable movement
    if (this.isAwake) {
      // Check keyboard input
      if ((this.cursors.left.isDown || this.isMovingLeft) && this.ghost.x > 0) {
        this.ghost.x -= 2; // Move left
      } else if ((this.cursors.right.isDown || this.isMovingRight) && this.ghost.x < config.width) {
        this.ghost.x += 2; // Move right
      }

      // Check if the ghost is near the bed position to show the sleep button
      if (this.ghost.x > 170 && this.ghost.x < 270) {
        this.sleepButton.setVisible(true);
      } else {
        this.sleepButton.setVisible(false);
      }

      if (!this.weaponPicked) {
        // Check if the ghost is near the weapon table position to show the drop weapon button
        if (this.ghost.x > 300 && this.ghost.x < 400) {
          this.pickWeaponButton.setVisible(true);
        } else {
          this.pickWeaponButton.setVisible(false);
        }
      } else {
        // Check if the ghost is near the weapon table position to show the pick weapon button
        if (this.ghost.x > 300 && this.ghost.x < 400) {
          this.dropWeaponButton.setVisible(true);
        } else {
          this.dropWeaponButton.setVisible(false);
        }
      }

      // Check if the ghost is near the door position to show the open door button
      if (this.ghost.x > 430 && this.ghost.x < 530) {
        this.openDoorButton.setVisible(true);
      } else {
        this.openDoorButton.setVisible(false);
      }
    }
  }

  wakeUpGhost() {
    if (!this.isAwake) {
      // Move ghost to bottom of screen (floor level)
      this.ghost.x = 260; // Center horizontally
      this.ghost.y = 340; // Bottom near floor
      this.ghost.angle = 0; // Set upright position
      this.ghost.setScale(0.25);
      this.isAwake = true; // Mark ghost as awake
      this.wakeUpButton.setVisible(false); // Hide wake-up button
    }
  }

  putGhostToSleep() {
    // Reset ghost position to bed and put it to sleep
    this.ghost.x = 250; // Bed's x position
    this.ghost.y = 300; // Bed's y position
    this.ghost.angle = -90; // Lie down position
    this.ghost.setScale(0.2); // Original size
    this.isAwake = false; // Mark ghost as asleep
    this.wakeUpButton.setVisible(true); // Show wake-up button again
    this.sleepButton.setVisible(false); // Hide sleep button
  
    // Reset ghost texture and weapon if weapon was picked up
    if (this.weaponPicked) {
      this.ghost.setTexture('ghost'); // Change back to original ghost texture
      this.weapon.setVisible(true); // Make weapon visible again
      this.weaponPicked = false; // Reset weapon picked state
    }
  }

  pickWeapon() {
    // Check if the weapon is already picked up
    if (this.weaponPicked) return;
    // Change ghost's image to "the-ghost"
    this.ghost.setTexture('the-ghost');
    // Hide weapon and pickWeaponButton permanently after picking up
    this.weapon.setVisible(false);
    this.pickWeaponButton.setVisible(false);
    this.dropWeaponButton.setVisible(true);
    // Set weapon picked state to true
    this.weaponPicked = true;
  }

  dropWeapon() {
    // Check if the weapon is already picked up
    if (!this.weaponPicked) return;
    // Change ghost's image to "the-ghost"
    this.ghost.setTexture('ghost');
    // Hide weapon and pickWeaponButton permanently after picking up
    this.weapon.setVisible(true);
    this.pickWeaponButton.setVisible(true);
    this.dropWeaponButton.setVisible(false);
    // Set weapon picked state to true
    this.weaponPicked = false;
  }

  openDoor() {
    // switch to `OutGhostHouseScene`
  }
}

// TODO: Define a new scene named `OutGhostHouseScene`, where the ghost is moved to a new environment. The background should display the exterior of the ghost house, and the ghost model and controls should be similar to those in the `InGhostHouseScene` environment. Use the ghost model that was active when the user clicked "open door" in the `OutGhostHouseScene`. Remember the specific ghost model used, and retain the model's position in each scene so that when the user returns to a scene from another, the ghost is in the same location.

// Configuration for the Phaser game
const config = {
  type: Phaser.AUTO,
  width: 640,
  height: 480,
  parent: 'game-container',
  scene: [PreloadScene, MainMenuScene, InGhostHouseScene],
  audio: {
    disableWebAudio: false
  }
};

// Initialize Phaser game
const game = new Phaser.Game(config);
window.addEventListener('resize', () => {
  const canvas = document.querySelector('canvas');
  if (canvas) {
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const scale = Math.min(windowWidth / 640, windowHeight / 480);
    canvas.style.transform = `scale(${scale})`;
    canvas.style.transformOrigin = 'top left';
  }
});