import React, { useCallback, useState } from "react";
import styles from "../styles/Background.module.css";
import Tower from "./Tower";
import Army from "./Army";
import MarchingBand from "./MarchingBand";
import MusicPlayer from "./MusicPlayer";
import Leaderboard from "./Leaderboard";
import { usePlayer } from "../providers/PlayerProvider";
import Boss from "./Boss";
import BossInfo from "./BossInfo";

const bossToMountainsClass = {
  0: styles.mountains0,
  1: styles.mountains1,
  2: styles.mountains2,
  3: styles.mountains3,
  4: styles.mountains4,
  5: styles.mountains5,
  6: styles.mountains6,
};

const Scene = () => {
  const { isRegistered, boss, player } = usePlayer();
  const [isLeaderboardOpen, setIsLeaderboardOpen] = useState(false);

  const handleMusicReady = useCallback(
    (unmute: () => void) => {
      if (isRegistered) {
        unmute();
      }
    },
    [isRegistered]
  );
  const variant = boss?.variants[boss.level] || 0;

  return (
    <div className={styles.frame}>
      <div className={`${styles.air} ${styles.background_asset}`} />
      <div className={`${styles.clouds_large} ${styles.background_asset}`} />
      <Boss />
      <Tower />
      <div className={`${styles.clouds_small} ${styles.background_asset}`} />
      <div
        className={`${styles.mountains} ${styles.background_asset} ${bossToMountainsClass[variant]}`}
      />
      <div className={`${styles.village} ${styles.background_asset}`} />
      {isRegistered && player?.has_active_session && <BossInfo />}
      <MarchingBand />
      <div className={`${styles.bonfire} ${styles.background_asset}`} />
      <Army />
      <MusicPlayer onReady={handleMusicReady} />
      <button
        onClick={() => setIsLeaderboardOpen(true)}
        className={styles.leaderboardButton}
        title="Leaderboard"
      >
        🏆
      </button>
      {isLeaderboardOpen && (
        <div className={styles.leaderboardOverlay}>
          <div className={styles.leaderboardContent}>
            <button
              className={styles.closeButton}
              onClick={() => setIsLeaderboardOpen(false)}
            >
              ×
            </button>
            <Leaderboard />
          </div>
        </div>
      )}
    </div>
  );
};

export default Scene;
