const { useState, useEffect, useRef, useCallback } = React;

const Trophy = ({ className }) => (
  <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>
);
const RefreshCcw = ({ className }) => (
  <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></svg>
);
const Play = ({ className }) => (
  <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="6 3 20 12 6 21 6 3"/></svg>
);
const X = ({ className }) => (
  <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
);
// --- Game Constants & Definitions ---
const BOARD_SIZE = 10;

// Color palette for the blocks (Tailwind classes)
const COLORS = [
  'bg-blue-500', 'bg-red-500', 'bg-green-500', 'bg-yellow-400',
  'bg-purple-500', 'bg-pink-500', 'bg-teal-400', 'bg-orange-500'
];

// A comprehensive library of classic block puzzle shapes
const SHAPE_DEFS = [
  [[1]], // 1x1
  [[1, 1]], [[1], [1]], // 2s
  [[1, 1, 1]], [[1], [1], [1]], // 3s
  [[1, 1, 1, 1]], [[1], [1], [1], [1]], // 4s
  [[1, 1, 1, 1, 1]], [[1], [1], [1], [1], [1]], // 5s
  [[1, 1], [1, 1]], // 2x2 Square
  [[1, 1, 1], [1, 1, 1], [1, 1, 1]], // 3x3 Square
  // Small L
  [[1, 0], [1, 1]], [[0, 1], [1, 1]], [[1, 1], [1, 0]], [[1, 1], [0, 1]],
  // Big L
  [[1, 0, 0], [1, 0, 0], [1, 1, 1]], [[1, 1, 1], [1, 0, 0], [1, 0, 0]], 
  [[1, 1, 1], [0, 0, 1], [0, 0, 1]], [[0, 0, 1], [0, 0, 1], [1, 1, 1]],
  // Z / S
  [[1, 1, 0], [0, 1, 1]], [[0, 1, 1], [1, 1, 0]], 
  [[1, 0], [1, 1], [0, 1]], [[0, 1], [1, 1], [1, 0]],
  // T
  [[1, 1, 1], [0, 1, 0]], [[0, 1, 0], [1, 1, 1]], 
  [[1, 0], [1, 1], [1, 0]], [[0, 1], [1, 1], [0, 1]]
];

// --- Tangram Levels Definition ---
const TANGRAM_LEVELS = [
  {
    name: "The Stairs",
    target: [
      [1,0,0,0],
      [1,1,0,0],
      [1,1,1,0],
      [1,1,1,1]
    ],
    pieces: [
      { grid: [[1]], color: 'bg-blue-500' },
      { grid: [[1,1]], color: 'bg-red-500' },
      { grid: [[1,1,1]], color: 'bg-green-500' },
      { grid: [[1,1,1,1]], color: 'bg-yellow-400' }
    ]
  },
  {
    name: "The Square",
    target: [
      [1,1,1],
      [1,1,1],
      [1,1,1]
    ],
    pieces: [
      { grid: [[1,1],[1,1]], color: 'bg-purple-500' },
      { grid: [[1,1,1]], color: 'bg-pink-500' },
      { grid: [[1],[1]], color: 'bg-teal-400' }
    ]
  },
  {
    name: "The Ring",
    target: [
      [1,1,1,1],
      [1,0,0,1],
      [1,0,0,1],
      [1,1,1,1]
    ],
    pieces: [
      { grid: [[1,1],[1,0]], color: 'bg-yellow-400' },
      { grid: [[1,1],[0,1]], color: 'bg-teal-400' },
      { grid: [[0,1],[1,1]], color: 'bg-pink-500' },
      { grid: [[1,0],[1,1]], color: 'bg-orange-500' }
    ]
  },
  {
    name: "The Core",
    target: [
      [1,1,1,1,1],
      [1,1,1,1,1],
      [1,1,1,1,1],
      [1,1,1,1,1],
      [1,1,1,1,1]
    ],
    pieces: [
      { grid: [[1,1,1,1,1]], color: 'bg-blue-500' },
      { grid: [[1,1,1,1,1]], color: 'bg-red-500' },
      { grid: [[1],[1],[1]], color: 'bg-green-500' },
      { grid: [[1],[1],[1]], color: 'bg-yellow-400' },
      { grid: [[1,1,1],[1,1,1],[1,1,1]], color: 'bg-purple-500' }
    ]
  }
];

// Helper to generate a random shape object
const getRandomShape = () => {
  const grid = SHAPE_DEFS[Math.floor(Math.random() * SHAPE_DEFS.length)];
  const color = COLORS[Math.floor(Math.random() * COLORS.length)];
  return { grid, color, id: Math.random().toString(36).substr(2, 9) };
};

// --- Main Application Component ---
function BlockCrush() {
  const [board, setBoard] = useState(Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null)));
  const [tray, setTray] = useState([null, null, null]);
  const [score, setScore] = useState(0);
  const [highScore, setHighScore] = useState(0);
  const [gameOver, setGameOver] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);

  // Tangram State
  const [gameMode, setGameMode] = useState('classic'); // 'classic' | 'tangram'
  const [tangramLevel, setTangramLevel] = useState(0);
  const [levelComplete, setLevelComplete] = useState(false);

  // Drag and Drop State
  const [dragState, setDragState] = useState(null);
  const [hoverTarget, setHoverTarget] = useState(null);
  
  const gridRef = useRef(null);

  // Load High Score
  useEffect(() => {
    const saved = localStorage.getItem('blockCrushHighScore');
    if (saved) setHighScore(parseInt(saved, 10));
  }, []);

  // Initialize Game
  const startGame = useCallback(() => {
    if (gameMode === 'classic') {
      setBoard(Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null)));
      setTray([getRandomShape(), getRandomShape(), getRandomShape()]);
      setScore(0);
    } else {
      // Tangram Initialization
      const levelData = TANGRAM_LEVELS[tangramLevel];
      const newBoard = Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill('invalid'));
      
      const rOffset = Math.floor((BOARD_SIZE - levelData.target.length) / 2);
      const cOffset = Math.floor((BOARD_SIZE - levelData.target[0].length) / 2);

      for (let r = 0; r < levelData.target.length; r++) {
        for (let c = 0; c < levelData.target[r].length; c++) {
          if (levelData.target[r][c] === 1) {
            newBoard[r + rOffset][c + cOffset] = null; // empty valid spot
          }
        }
      }
      setBoard(newBoard);
      setTray(levelData.pieces.map(p => ({ ...p, id: Math.random().toString(36).substr(2, 9) })));
    }
    setGameOver(false);
    setLevelComplete(false);
    setIsPlaying(true);
  }, [gameMode, tangramLevel]);

  const handleModeSwitch = (mode) => {
    setGameMode(mode);
    setIsPlaying(false);
    setGameOver(false);
    setLevelComplete(false);
  };

  // Refill tray if empty
  useEffect(() => {
    if (gameMode === 'classic' && isPlaying && !gameOver && tray.every(shape => shape === null)) {
      setTray([getRandomShape(), getRandomShape(), getRandomShape()]);
    }
  }, [tray, isPlaying, gameOver, gameMode]);

  // Check Game Over condition every time the tray or board changes
  useEffect(() => {
    if (!isPlaying || gameOver || levelComplete) return;

    if (gameMode === 'tangram') {
      let isWon = true;
      for (let r = 0; r < BOARD_SIZE; r++) {
        for (let c = 0; c < BOARD_SIZE; c++) {
          if (board[r][c] === null) isWon = false;
        }
      }
      
      if (isWon) {
        setLevelComplete(true);
        return;
      }
    }

    let canPlaceAny = false;
    for (const shape of tray) {
      if (shape !== null) {
        for (let r = 0; r < BOARD_SIZE; r++) {
          for (let c = 0; c < BOARD_SIZE; c++) {
            if (canPlaceShape(board, shape.grid, r, c)) {
              canPlaceAny = true;
              break;
            }
          }
          if (canPlaceAny) break;
        }
      }
      if (canPlaceAny) break;
    }

    if (!canPlaceAny && tray.some(s => s !== null)) {
      setGameOver(true);
      if (gameMode === 'classic' && score > highScore) {
        setHighScore(score);
        localStorage.setItem('blockCrushHighScore', score.toString());
      }
    }
  }, [board, tray, isPlaying, gameOver, score, highScore, gameMode, levelComplete]);

  // Logic to verify if a shape fits at a specific row/col
  const canPlaceShape = (currentBoard, shapeGrid, startRow, startCol) => {
    for (let r = 0; r < shapeGrid.length; r++) {
      for (let c = 0; c < shapeGrid[r].length; c++) {
        if (shapeGrid[r][c] === 1) {
          const boardR = startRow + r;
          const boardC = startCol + c;
          if (
            boardR < 0 || boardR >= BOARD_SIZE ||
            boardC < 0 || boardC >= BOARD_SIZE ||
            currentBoard[boardR][boardC] !== null
          ) {
            return false;
          }
        }
      }
    }
    return true;
  };

  // Logic to clear completed lines
  const clearLines = (currentBoard) => {
    let newBoard = currentBoard.map(row => [...row]);
    let rowsToClear = [];
    let colsToClear = [];

    // Find full rows
    for (let r = 0; r < BOARD_SIZE; r++) {
      if (newBoard[r].every(cell => cell !== null)) {
        rowsToClear.push(r);
      }
    }

    // Find full columns
    for (let c = 0; c < BOARD_SIZE; c++) {
      let isFull = true;
      for (let r = 0; r < BOARD_SIZE; r++) {
        if (newBoard[r][c] === null) {
          isFull = false;
          break;
        }
      }
      if (isFull) colsToClear.push(c);
    }

    // Clear them
    rowsToClear.forEach(r => {
      for (let c = 0; c < BOARD_SIZE; c++) newBoard[r][c] = null;
    });
    colsToClear.forEach(c => {
      for (let r = 0; r < BOARD_SIZE; r++) newBoard[r][c] = null;
    });

    const linesCleared = rowsToClear.length + colsToClear.length;
    return { newBoard, linesCleared };
  };

  // --- Drag and Drop Handlers ---
  const handlePointerDown = (e, shape, index) => {
    if (!isPlaying || gameOver || !shape) return;
    
    // Prevent default touch behavior to stop scrolling
    if (e.pointerType === 'touch') {
      e.target.releasePointerCapture(e.pointerId);
    }

    setDragState({
      shape,
      index,
      x: e.clientX,
      y: e.clientY,
      isDragging: true
    });
    setHoverTarget(null);
  };

  useEffect(() => {
    const handlePointerMove = (e) => {
      if (!dragState?.isDragging) return;

      setDragState(prev => ({ ...prev, x: e.clientX, y: e.clientY }));

      // Calculate hover target on the grid
      if (gridRef.current) {
        const rect = gridRef.current.getBoundingClientRect();
        const cellW = rect.width / BOARD_SIZE;
        const cellH = rect.height / BOARD_SIZE;

        // SIGNIFICANT UX IMPROVEMENT: 
        // We push the "virtual" center of the piece way up so the finger doesn't block it.
        // Mobile offset is 120px above the finger, Desktop is 40px.
        const yOffset = e.pointerType === 'touch' || window.innerWidth < 768 ? 120 : 40;
        
        const visualX = e.clientX;
        const visualY = e.clientY - yOffset;

        const shapeRows = dragState.shape.grid.length;
        const shapeCols = dragState.shape.grid[0].length;

        const leftX = visualX - (shapeCols * cellW) / 2;
        const topY = visualY - (shapeRows * cellH) / 2;

        const col = Math.round((leftX - rect.left) / cellW);
        const row = Math.round((topY - rect.top) / cellH);

        // Check if reasonably within bounds to show hover
        if (row >= -2 && row <= BOARD_SIZE && col >= -2 && col <= BOARD_SIZE) {
          if (canPlaceShape(board, dragState.shape.grid, row, col)) {
            setHoverTarget({ row, col });
          } else {
            setHoverTarget(null);
          }
        } else {
          setHoverTarget(null);
        }
      }
    };

    const handlePointerUp = () => {
      if (!dragState?.isDragging) return;

      // Attempt to place the shape if we have a valid hover target
      if (hoverTarget) {
        const { row, col } = hoverTarget;
        
        let newBoard = board.map(r => [...r]);
        const shapeGrid = dragState.shape.grid;
        
        // Place the piece
        let blocksPlaced = 0;
        for (let r = 0; r < shapeGrid.length; r++) {
          for (let c = 0; c < shapeGrid[r].length; c++) {
            if (shapeGrid[r][c] === 1) {
              newBoard[row + r][col + c] = dragState.shape.color;
              blocksPlaced++;
            }
          }
        }

        if (gameMode === 'classic') {
          // Process line clears
          const { newBoard: clearedBoard, linesCleared } = clearLines(newBoard);
          setBoard(clearedBoard);

          // Calculate score
          let points = blocksPlaced; 
          if (linesCleared > 0) {
             points += (linesCleared * 10) * linesCleared;
          }
          setScore(s => s + points);
        } else {
          // Tangram mode skips line clearing
          setBoard(newBoard);
        }

        // Remove shape from tray
        const newTray = [...tray];
        newTray[dragState.index] = null;
        setTray(newTray);
      }

      // Reset drag state
      setDragState(null);
      setHoverTarget(null);
    };

    if (dragState?.isDragging) {
      window.addEventListener('pointermove', handlePointerMove);
      window.addEventListener('pointerup', handlePointerUp);
    }

    return () => {
      window.removeEventListener('pointermove', handlePointerMove);
      window.removeEventListener('pointerup', handlePointerUp);
    };
  }, [dragState, hoverTarget, board, tray]);

  // --- Rendering Helpers ---
  
  // Render a block within a shape
  const renderShapeBlock = (filled, color, key) => {
    if (!filled) return <div key={key} className="w-full h-full" />;
    return (
      <div 
        key={key} 
        className={`w-full h-full rounded-[4px] shadow-sm ${color} border-b-4 border-r-4 border-black/20`}
      />
    );
  };

  // Render a miniature shape in the tray
  const renderTrayShape = (shape, index) => {
    if (!shape) {
      if (gameMode === 'tangram') return null; 
      return <div className="w-16 h-16 sm:w-[70px] sm:h-[70px]" key={`empty-${index}`} />;
    }
    
    // Hide the original shape in the tray if it's currently being dragged
    const isBeingDragged = dragState && dragState.index === index;

    return (
      <div 
        key={shape.id}
        className={`relative flex items-center justify-center cursor-pointer transition-opacity ${isBeingDragged ? 'opacity-0' : 'opacity-100'} touch-none hover:scale-105 active:scale-95 duration-150`}
        style={{ width: '70px', height: '70px' }} 
        onPointerDown={(e) => handlePointerDown(e, shape, index)}
      >
        <div 
          className="grid gap-[2px] pointer-events-none"
          style={{ 
            gridTemplateColumns: `repeat(${shape.grid[0].length}, minmax(0, 1fr))`,
            width: `${shape.grid[0].length * 14}px`,  
            height: `${shape.grid.length * 14}px`
          }}
        >
          {shape.grid.map((row, rIdx) => 
            row.map((cell, cIdx) => renderShapeBlock(cell === 1, shape.color, `${rIdx}-${cIdx}`))
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="fixed inset-0 bg-slate-900 text-slate-100 flex flex-col font-sans select-none overflow-hidden touch-none">
      
      {/* Wrapper to center everything and restrict max width */}
      <div className="flex-1 w-full max-w-md mx-auto flex flex-col p-4 sm:p-6 min-h-0">

        {/* Header - Fixed Height */}
        <div className="w-full shrink-0 mb-4 sm:mb-6">
          <div className="flex bg-slate-800 p-1 rounded-xl mb-4 shadow-inner">
            <button 
              onClick={() => handleModeSwitch('classic')} 
              className={`flex-1 py-2 rounded-lg text-sm font-bold transition-colors ${gameMode === 'classic' ? 'bg-blue-500 text-white shadow-md' : 'text-slate-400 hover:text-slate-200'}`}
            >
              Classic Mode
            </button>
            <button 
              onClick={() => handleModeSwitch('tangram')} 
              className={`flex-1 py-2 rounded-lg text-sm font-bold transition-colors ${gameMode === 'tangram' ? 'bg-purple-500 text-white shadow-md' : 'text-slate-400 hover:text-slate-200'}`}
            >
              Tangram Mode
            </button>
          </div>
          
          <div className="flex justify-between items-end px-2">
            <div>
              <h1 className="text-3xl font-extrabold tracking-tight text-white mb-1">
                BLOCK <span className={gameMode === 'classic' ? "text-blue-500" : "text-purple-500"}>CRUSH</span>
              </h1>
              {gameMode === 'classic' ? (
                <p className="text-slate-400 text-sm font-medium flex items-center gap-1">
                  <Trophy size={14} className="text-yellow-500" /> Best: {highScore}
                </p>
              ) : (
                <p className="text-slate-400 text-sm font-medium flex items-center gap-1">
                  Level {tangramLevel + 1}: {TANGRAM_LEVELS[tangramLevel].name}
                </p>
              )}
            </div>
            
            {gameMode === 'classic' ? (
              <div className="text-right bg-slate-800 px-4 py-2 rounded-xl shadow-inner border border-slate-700/50">
                <p className="text-xs text-slate-400 font-bold uppercase tracking-wider mb-1">Score</p>
                <p className="text-2xl font-black text-white leading-none">{score}</p>
              </div>
            ) : (
              <button 
                onClick={startGame}
                title="Restart Level"
                className="p-3 bg-slate-800 rounded-xl hover:bg-slate-700 transition-colors border border-slate-700/50 text-slate-300"
              >
                <RefreshCcw size={24} />
              </button>
            )}
          </div>
        </div>

        {/* Main Game Area */}
        <div className="w-full flex-1 relative flex items-center justify-center min-h-0">
          
          {/* Game Board */}
          <div 
            ref={gridRef}
            className="bg-slate-800 p-2 rounded-xl shadow-2xl border border-slate-700 grid gap-[2px] touch-none"
            style={{ 
              gridTemplateColumns: `repeat(${BOARD_SIZE}, minmax(0, 1fr))`,
              width: '100%',
              maxWidth: 'min(100%, calc(100dvh - 280px))',
              aspectRatio: '1 / 1'
            }}
          >
            {board.map((row, r) => (
              row.map((cellColor, c) => {
                if (cellColor === 'invalid') {
                  return <div key={`${r}-${c}`} className="w-full h-full" />;
                }

                // Determine if this cell is part of the current drag hover preview
                let isHoverTarget = false;
                let hoverColor = null;

                if (hoverTarget && dragState) {
                  const shapeR = r - hoverTarget.row;
                  const shapeC = c - hoverTarget.col;
                  const shapeGrid = dragState.shape.grid;

                  if (
                    shapeR >= 0 && shapeR < shapeGrid.length &&
                    shapeC >= 0 && shapeC < shapeGrid[0].length &&
                    shapeGrid[shapeR][shapeC] === 1
                  ) {
                    isHoverTarget = true;
                    hoverColor = dragState.shape.color;
                  }
                }

                return (
                  <div 
                    key={`${r}-${c}`} 
                    className={`
                      w-full h-full rounded-[4px] transition-all duration-100 ease-out
                      ${cellColor ? `${cellColor} border-b-4 border-r-4 border-black/20 shadow-sm` : 'bg-slate-700/60 shadow-inner border border-dashed border-slate-600'}
                      
                      ${/* UX IMPROVEMENT: The "landing shadow" is now a solid, slightly shrunken block, 
                           making it instantly obvious exactly where the piece will drop */ ''}
                      ${isHoverTarget && !cellColor ? `${hoverColor} opacity-90 border-b-4 border-r-4 border-black/30 scale-90` : ''}
                    `}
                  />
                )
              })
            ))}
          </div>

          {/* Start / Game Over Overlay */}
          {(!isPlaying || gameOver || levelComplete) && (
            <div className="absolute inset-0 z-10 bg-slate-900/80 backdrop-blur-sm rounded-xl flex flex-col items-center justify-center p-6 text-center animate-in fade-in zoom-in duration-300">
              {levelComplete ? (
                 <>
                   <h2 className="text-4xl font-black text-emerald-400 mb-2 drop-shadow-md">You Did It!</h2>
                   <p className="text-slate-300 mb-8 font-medium">Shape completed.</p>
                   <button 
                     onClick={() => {
                       setTangramLevel(l => (l + 1) % TANGRAM_LEVELS.length);
                       setIsPlaying(false);
                       setLevelComplete(false);
                     }}
                     className="flex items-center gap-2 bg-emerald-600 hover:bg-emerald-500 text-white px-8 py-4 rounded-full font-bold text-lg transition-transform active:scale-95 shadow-lg shadow-emerald-500/30"
                   >
                     <Play size={20} fill="currentColor" />
                     Next Level
                   </button>
                 </>
              ) : gameOver ? (
                <>
                  <h2 className="text-4xl font-black text-rose-500 mb-2 drop-shadow-md">
                    {gameMode === 'classic' ? 'Game Over' : 'Stuck!'}
                  </h2>
                  <p className="text-slate-300 mb-6 font-medium">No more moves available!</p>
                  {gameMode === 'classic' && (
                    <div className="bg-slate-800 p-4 rounded-xl w-full max-w-[200px] mb-8 border border-slate-700">
                      <p className="text-sm text-slate-400 mb-1">Final Score</p>
                      <p className="text-3xl font-bold text-white">{score}</p>
                    </div>
                  )}
                  <button 
                    onClick={startGame}
                    className="flex items-center gap-2 bg-blue-600 hover:bg-blue-500 text-white px-8 py-4 rounded-full font-bold text-lg transition-transform active:scale-95 shadow-lg shadow-blue-500/30"
                  >
                    <RefreshCcw size={20} />
                    {gameMode === 'classic' ? 'Play Again' : 'Retry Level'}
                  </button>
                </>
              ) : (
                <>
                  <div className={`w-20 h-20 ${gameMode === 'classic' ? 'bg-blue-500' : 'bg-purple-500'} rounded-2xl mb-6 shadow-lg border-b-8 border-r-8 border-black/20 flex items-center justify-center transform rotate-12`}>
                     <div className="w-10 h-10 bg-white/20 rounded-lg"></div>
                  </div>
                  <h2 className="text-2xl font-bold text-white mb-2">Ready to play?</h2>
                  {gameMode === 'tangram' && (
                     <p className="text-slate-400 mb-6 font-medium">Level {tangramLevel + 1}: {TANGRAM_LEVELS[tangramLevel].name}</p>
                  )}
                  <button 
                    onClick={startGame}
                    className={`flex items-center gap-2 ${gameMode === 'classic' ? 'bg-blue-600 hover:bg-blue-500 shadow-blue-500/30' : 'bg-purple-600 hover:bg-purple-500 shadow-purple-500/30'} text-white px-8 py-4 rounded-full font-bold text-lg transition-transform active:scale-95 shadow-lg mt-4`}
                  >
                    <Play size={20} fill="currentColor" />
                    Start Game
                  </button>
                </>
              )}
            </div>
          )}
        </div>

        {/* Shape Tray */}
        <div className="w-full shrink-0 mt-4 bg-slate-800/50 p-3 sm:p-4 rounded-2xl border border-slate-700/50 flex flex-wrap justify-center gap-3 sm:gap-4 items-center min-h-[90px]">
          {tray.map((shape, idx) => renderTrayShape(shape, idx))}
        </div>

      </div>

      {/* Floating Dragged Shape (Rendered outside normal flow) */}
      {dragState?.isDragging && dragState.shape && (
        <div 
          className="fixed pointer-events-none z-50 transition-none"
          style={{
            left: dragState.x,
            top: dragState.y,
            // UX IMPROVEMENT: Substantially increased the Y offset (120px on mobile) 
            // so the dragged piece floats high above the user's thumb/finger.
            transform: `translate(-50%, calc(-50% - ${window.innerWidth < 768 ? '120px' : '40px'}))`,
          }}
        >
          {/* UX IMPROVEMENT: Added opacity-75 so the user can easily see the board grid THROUGH the piece */}
          <div 
            className="grid gap-[2px] opacity-75 drop-shadow-2xl"
            style={{ 
              gridTemplateColumns: `repeat(${dragState.shape.grid[0].length}, minmax(0, 1fr))`,
              width: `calc(min(9vw, 36px) * ${dragState.shape.grid[0].length})`,
              height: `calc(min(9vw, 36px) * ${dragState.shape.grid.length})`
            }}
          >
            {dragState.shape.grid.map((row, rIdx) => 
              row.map((cell, cIdx) => renderShapeBlock(cell === 1, dragState.shape.color, `drag-${rIdx}-${cIdx}`))
            )}
          </div>
        </div>
      )}

    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<BlockCrush />);
