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

import { Play, Loader, RotateCcw, CircleAlert } from "lucide-react";
import PropTypes from "prop-types";
import { useGameState, GAME_STATES } from "../../contexts/GameStateContext";
import { useRef, useEffect } from "react";

export default function GameEditor(props) {
  const { children } = props;

  const runText = props.runText ?? props.textoExecutar ?? props.runLabel ?? "Executar";
  const restartText = props.restartText ?? props.textoReiniciar ?? props.restartLabel ?? "Reiniciar";

  // useRef é síncrono: leitura/escrita imediata, sem batch do React
  const isProcessingRef = useRef(false);
  const processingTimeoutRef = useRef(null);

  const {
    executionState,
    execute,
    restart,
    stop,
    currentBlockCount,
    editorType,
  } = useGameState();

  useEffect(() => {
    return () => {
      if (processingTimeoutRef.current) {
        clearTimeout(processingTimeoutRef.current);
      }
    };
  }, []);

  const isExecuting = executionState === GAME_STATES.EXECUTANDO;
  const needsRestart =
    executionState === GAME_STATES.SUCESSO ||
    executionState === GAME_STATES.FALHA;
  const noBlocks = currentBlockCount === 0;

  const handleClick = () => {
    // Leitura síncrona — funciona mesmo com cliques ultra-rápidos
    if (isProcessingRef.current) {
      return;
    }

    if (noBlocks && !isExecuting && !needsRestart) {
      return;
    }

    // Escrita síncrona — bloqueia imediatamente
    isProcessingRef.current = true;

    if (processingTimeoutRef.current) {
      clearTimeout(processingTimeoutRef.current);
    }
    processingTimeoutRef.current = setTimeout(() => {
      isProcessingRef.current = false;
    }, 200);

    if (isExecuting) {
      stop();
      return;
    }

    if (needsRestart) {
      restart();
    } else {
      execute();
    }
  };

  const setStyle = () => {
    const style =
      "game-controls-custom flex items-center space-x-2 px-6 py-3 rounded-full font-medium transition-all duration-200 shadow-md";

    if (noBlocks) {
      return `${style} bg-gray-300 text-black cursor-not-allowed`;
    }

    if (isExecuting) {
      return `${style} bg-[var(--action-green)] hover:bg-[rgb(235_119_63/1)]`;
    }

    if (needsRestart) {
      return `${style} bg-[rgb(254_0_2/1)] hover:bg-[rgb(230_0_0/1)] text-white`;
    }

    return `${style} bg-green-100 hover:bg-green-200 text-black`;
  };

  const getEmptyStateText = () => {
    return editorType === "code"
      ? "Adicione código para execute"
      : "Adicione blocos para execute";
  };

  return (
    <div className="w-full h-full flex flex-col">
      <div className="flex-1 min-h-0">{children}</div>
      <div className="game-editor-controls py-1 flex flex-col items-center space-y-2">
        <button
          onClick={handleClick}
          className={setStyle()}
          disabled={noBlocks && !isExecuting && !needsRestart}
          data-tour={needsRestart ? "reset-button" : "run-button"}
        >
          {isExecuting ? (
            <>
              <Loader className="w-4 h-4 animate-spin" />
              <span>Executando, clique para interromper...</span>
            </>
          ) : needsRestart ? (
            <>
              <RotateCcw className="w-4 h-4" />
              <span>{restartText}</span>
            </>
          ) : noBlocks ? (
            <>
              <CircleAlert className="w-4 h-4 opacity-50" />
              <span>{getEmptyStateText()}</span>
            </>
          ) : (
            <>
              <Play className="w-4 h-4" />
              <span>{runText}</span>
            </>
          )}
        </button>
      </div>
    </div>
  );
}

GameEditor.propTypes = {
  runText: PropTypes.string,
  runLabel: PropTypes.string,
  textoExecutar: PropTypes.string,
  restartText: PropTypes.string,
  restartLabel: PropTypes.string,
  textoReiniciar: PropTypes.string,
  children: PropTypes.node,
};