/**
 * @fileoverview React component for GameArea.jsx
 * 
 * @module components.game.GameArea
 */


import { useEffect, useState, useRef } from "react";
import { useGameState, GAME_STATES } from "../../contexts/GameStateContext";
import { gameEventBus } from "../../utils/gameEvents";
import ConfettiOverlay from "./ConfettiOverlay";
import PropTypes from "prop-types";

export default function GameArea({
  children,
  blocksRemaining = null,
  phaseId = null,
  remainingBlocksLabel = null,
}) {
  const {
    executionState,
    generatedCode,
    finalizeWithSuccess,
    finalizeWithFailure,
    setFailureMessage,
  } = useGameState();

  const [showConfetti, setShowConfetti] = useState(false);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const previousPhaseId = useRef(phaseId);
  const effectivePhaseId = phaseId;
  const remainingBlocks = blocksRemaining;

  useEffect(() => {
    if (effectivePhaseId !== null && effectivePhaseId !== previousPhaseId.current) {
      setIsTransitioning(true);

      const timer = setTimeout(() => {
        setIsTransitioning(false);
        previousPhaseId.current = effectivePhaseId;
      }, 600);



      return () => clearTimeout(timer);
    }
  }, [effectivePhaseId]);

  useEffect(() => {
    const handleGameSuccess = () => {
      finalizeWithSuccess();
      setShowConfetti(true);
    };

    const handleGameFailure = (e) => {
      const reason = e.detail?.reason;
      if (reason) setFailureMessage(reason);
      finalizeWithFailure();
    };

    gameEventBus.addEventListener("gameSuccess", handleGameSuccess);
    gameEventBus.addEventListener("gameFailure", handleGameFailure);

    return () => {
      gameEventBus.removeEventListener("gameSuccess", handleGameSuccess);
      gameEventBus.removeEventListener("gameFailure", handleGameFailure);
    };
  }, [finalizeWithSuccess, finalizeWithFailure]);

  useEffect(() => {
    switch (executionState) {
      case GAME_STATES.EXECUTANDO:
        if (generatedCode) {
          const codigo =
            typeof generatedCode === "string"
              ? generatedCode
              : generatedCode.codigo;
          const ws =
            typeof generatedCode === "object" ? generatedCode.workspace : null;

          gameEventBus.executeCode(codigo, ws);
        }
        break;
      case GAME_STATES.PARADO:
        gameEventBus.resetGame();
        setShowConfetti(false);
        break;
    }
  }, [executionState, generatedCode]);

  const remainingLabel = remainingBlocksLabel ?? "Blocos restantes";

  return (
    <div
      className="w-full h-full overflow-hidden relative flex items-center justify-center game-area-container bg-gray-900"
      id="visualization"
    >
      {/* Confetti de sucesso de uma fase */}
      <ConfettiOverlay isActive={showConfetti} />

      {/* Overlay de transição */}
      <div
        className={`absolute inset-0 flex items-center justify-center bg-gray-900 transition-opacity duration-300 ease-in-out z-10 ${
          isTransitioning ? "opacity-100" : "opacity-0 pointer-events-none"
        }`}
        style={{ borderRadius: "5px" }}
      >
        <div className="w-12 h-12 border-4 border-white/30 border-t-white rounded-full animate-spin" />
      </div>

      {/* Indicador de blocos restantes */}
      {remainingBlocks !== null && !isNaN(remainingBlocks) && (
        <div id="capacityBubble">
          <div id="capacity" style={{ display: "block" }}>
            {remainingLabel}: {" "}
            <span className="capacityNumber">{remainingBlocks}</span>
          </div>
        </div>
      )}

      <div
        className="flex items-center justify-center w-full h-full phaser-container"
        style={{
          backgroundColor: "#242527",
        }}
      >
        {children}
      </div>
    </div>
  );
}

GameArea.propTypes = {
  children: PropTypes.node,
  blocksRemaining: PropTypes.number,
  phaseId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  remainingBlocksLabel: PropTypes.string,
};
