// @ts-nocheck
// This file bundles all logic (Components, Services, Types) to run directly in the browser.

// Explicitly access globals to ensure we use the UMD build
const React = window.React;
const ReactDOM = window.ReactDOM;
const { useState, useEffect, useRef, useCallback } = React;

// --- CONFIGURATION ---
const PUZZLE_IMAGES = [
  "images/puzzle1.jpg", 
  "images/puzzle2.jpg", 
  "images/puzzle3.jpg"
];
const BG_IMAGE = "bg.jpg";

// --- TYPES ---
const ViewState = {
  MENU: 'MENU',
  GAME: 'GAME',
};

// --- SERVICES ---
const STORAGE_KEY = 'cubes_leaderboard';

const getScores = async () => {
  const stored = localStorage.getItem(STORAGE_KEY);
  if (!stored) return [];
  try {
    return JSON.parse(stored);
  } catch (e) {
    return [];
  }
};

const saveScore = async (newScore) => {
  const currentScores = await getScores();
  const updatedScores = [...currentScores, newScore];
  // Sort by time (ascending)
  updatedScores.sort((a, b) => a.time - b.time);
  // Keep top 20
  const top20 = updatedScores.slice(0, 20);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(top20));
  return top20;
};

// --- COMPONENTS ---

// 1. Leaderboard Component
const Leaderboard = ({ onClose, highlightName }) => {
  const [scores, setScores] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchScores = async () => {
      const data = await getScores();
      setScores(data);
      setLoading(false);
    };
    fetchScores();
  }, []);

  const formatTime = (ms) => {
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-fade-in">
      <div className="bg-white rounded-xl shadow-2xl w-full max-w-md border-4 border-capoliBlue overflow-hidden">
        <div className="bg-capoliBlue p-4 text-white text-center relative border-b-4 border-capoliYellow">
          <h2 className="text-2xl font-bold uppercase tracking-wider">Tabuľka výsledkov</h2>
          <button 
            onClick={onClose}
            className="absolute right-4 top-1/2 -translate-y-1/2 text-capoliYellow hover:text-white font-bold text-2xl"
          >
            ✕
          </button>
        </div>
        
        <div className="p-0 max-h-[60vh] overflow-y-auto">
          {loading ? (
            <div className="p-8 text-center text-gray-500">Načítavam...</div>
          ) : scores.length === 0 ? (
            <div className="p-8 text-center text-gray-500">Zatiaľ žiadne výsledky. Buď prvý!</div>
          ) : (
            <table className="w-full text-left border-collapse">
              <thead className="bg-gray-100 text-gray-600 text-xs uppercase sticky top-0 shadow-sm">
                <tr>
                  <th className="p-3">#</th>
                  <th className="p-3">Meno</th>
                  <th className="p-3 text-right">Čas</th>
                </tr>
              </thead>
              <tbody>
                {scores.map((score, index) => (
                  <tr 
                    key={index} 
                    className={`border-b border-gray-100 ${
                      score.name === highlightName ? 'bg-yellow-100' : index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
                    }`}
                  >
                    <td className="p-3 font-mono text-gray-400 w-12">{index + 1}.</td>
                    <td className={`p-3 font-semibold ${index < 3 ? 'text-capoliBlue' : 'text-gray-700'}`}>
                      {score.name}
                      {index === 0 && <span className="ml-2">👑</span>}
                    </td>
                    <td className="p-3 text-right font-mono font-bold text-capoliBlue">
                      {formatTime(score.time)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        <div className="p-4 bg-gray-50 border-t border-gray-200 text-center">
          <button 
            onClick={onClose}
            className="px-6 py-2 bg-capoliBlue text-white rounded hover:bg-blue-900 transition-colors font-bold shadow-md border-b-4 border-blue-900 active:border-b-0 active:translate-y-1"
          >
            Zatvoriť
          </button>
        </div>
      </div>
    </div>
  );
};

// 2. Main Menu Component
const MainMenu = ({ onNavigate }) => {
  return (
    <div className="w-full h-full flex flex-col relative overflow-hidden bg-white">
      {/* Background Image Layer */}
      <div className="absolute inset-0 z-0">
          <img 
            src={BG_IMAGE}
            onError={(e) => e.target.style.display = 'none'} 
            alt="Background" 
            className="w-full h-full object-cover opacity-20"
          />
          <div className="absolute inset-0 bg-gradient-to-b from-white/40 to-yellow-50/60"></div>
      </div>

      {/* Content Layer */}
      <div className="relative z-10 flex flex-col h-full overflow-y-auto">
        {/* Header Area */}
        <div className="p-8 text-center">
           <h1 className="text-6xl font-black text-capoliBlue tracking-wide drop-shadow-md">
             CAPOLI <span className="text-capoliYellow text-stroke-blue">FUN</span>
           </h1>
           <p className="mt-2 text-capoliBlue font-bold text-xl uppercase tracking-widest">Herná zóna</p>
        </div>

        {/* 6-Grid Layout for Games */}
        <div className="flex-grow p-4 md:p-8 max-w-6xl mx-auto w-full">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            
            {/* Game 1: CUBES (Active) */}
            <button 
              onClick={() => onNavigate(ViewState.GAME)}
              className="group relative bg-white border-4 border-capoliBlue rounded-xl overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2 flex flex-col aspect-[4/3]"
            >
              {/* Corner accent */}
              <div className="absolute top-0 right-0 w-16 h-16 bg-capoliYellow transform translate-x-8 -translate-y-8 rotate-45 z-20"></div>

              <div className="h-2/3 bg-capoliBlue flex items-center justify-center overflow-hidden relative">
                 <div className="absolute inset-0 bg-capoliBlue opacity-90"></div>
                 {/* Decorative Grid */}
                 <div className="grid grid-cols-3 gap-2 p-4 rotate-12 group-hover:rotate-0 transition-transform duration-500 z-10">
                    <div className="w-8 h-8 bg-capoliYellow rounded-sm shadow-lg"></div>
                    <div className="w-8 h-8 bg-white rounded-sm shadow-lg"></div>
                    <div className="w-8 h-8 bg-capoliYellow rounded-sm shadow-lg"></div>
                    <div className="w-8 h-8 bg-white rounded-sm shadow-lg"></div>
                    <div className="w-8 h-8 bg-capoliYellow rounded-sm shadow-lg"></div>
                    <div className="w-8 h-8 bg-white rounded-sm shadow-lg"></div>
                 </div>
              </div>
              <div className="h-1/3 bg-white flex items-center justify-center border-t-4 border-capoliYellow z-10">
                <span className="text-3xl font-black text-capoliBlue uppercase tracking-widest group-hover:scale-110 transition-transform">CUBES</span>
              </div>
            </button>

           {/* Game 2: PONG (PRIPRAVUJEME 2) - Opravený ODKAZ na https://capoli.net/fun/pong/index.html */}
            <a 
                href="https://capoli.net/fun/pong/index.html" 
                className="group relative bg-white border-4 border-capoliBlue rounded-xl overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2 flex flex-col aspect-[4/3]"
            >
              {/* Corner accent (šedý) */}
              <div className="absolute top-0 right-0 w-16 h-16 bg-capoliYellow transform translate-x-8 -translate-y-8 rotate-45 z-20"></div>

              <div className="h-2/3 bg-gray-300 flex items-center justify-center relative">
                 <h4 className="text-4xl font-black text-white opacity-80 z-10">PONG</h4>
              </div>
              
              <div className="h-1/3 p-4 flex flex-col justify-center items-center bg-gray-100">
                <h3 className="text-2xl font-black text-gray-500 uppercase">PONG</h3>
                <p className="text-gray-400 text-sm">Classic arcade</p>
              </div>
            </a>
            
            {/* Placeholder Slots 3-6 (pre ostávajúce 4 voľné sloty) */} 
            {Array.from({ length: 4 }).map((_, index) => (
                <div key={`placeholder-${index}`} className="relative bg-white border-4 border-gray-200 border-dashed rounded-xl flex flex-col items-center justify-center opacity-60 aspect-[4/3] group hover:opacity-100 transition-opacity cursor-not-allowed">
                    <div className="text-4xl text-gray-300 mb-2 font-bold">{index + 3}</div>
                    <span className="text-gray-400 font-bold uppercase tracking-wider">Pripravujeme</span>
                </div>
            ))}

          </div>
        </div>
        
        <div className="p-4 text-center text-capoliBlue font-bold text-sm">
          © 2024 Capoli.net
        </div>
      </div>
    </div>
  );
};

// 3. Game Component
const CubesGame = ({ onBack }) => {
  const GRID_SIZE = 5;
  const TILE_COUNT = GRID_SIZE * GRID_SIZE; 
  const EMPTY_INDEX = TILE_COUNT - 1;

  // Game State
  const [grid, setGrid] = useState([]);
  const [isGameActive, setIsGameActive] = useState(false);
  const [isSolved, setIsSolved] = useState(false);
  const [moveCount, setMoveCount] = useState(0);
  
  // Timer State
  const [startTime, setStartTime] = useState(null);
  const [elapsedTime, setElapsedTime] = useState(0);
  
  // Settings
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [playerName, setPlayerName] = useState('');
  const [showLeaderboard, setShowLeaderboard] = useState(false);

  const timerRef = useRef(null);

  // Initialize ordered grid
  const getSolvedGrid = () => Array.from({ length: TILE_COUNT }, (_, i) => i);

  // Start/Reset Game
  const initGame = useCallback(() => {
    const solved = getSolvedGrid();
    
    // Shuffle logic
    let tempGrid = [...solved];
    let emptyPos = EMPTY_INDEX;
    let previousPos = -1;

    // Perform 200 random moves
    for (let i = 0; i < 200; i++) {
      const neighbors = [];
      const row = Math.floor(emptyPos / GRID_SIZE);
      const col = emptyPos % GRID_SIZE;

      if (row > 0) neighbors.push(emptyPos - GRID_SIZE); // Up
      if (row < GRID_SIZE - 1) neighbors.push(emptyPos + GRID_SIZE); // Down
      if (col > 0) neighbors.push(emptyPos - 1); // Left
      if (col < GRID_SIZE - 1) neighbors.push(emptyPos + 1); // Right

      const validNeighbors = neighbors.filter(n => n !== previousPos);
      if (validNeighbors.length > 0) {
        const randomNeighbor = validNeighbors[Math.floor(Math.random() * validNeighbors.length)];
        // Swap
        tempGrid[emptyPos] = tempGrid[randomNeighbor];
        tempGrid[randomNeighbor] = EMPTY_INDEX; 
        
        previousPos = emptyPos;
        emptyPos = randomNeighbor;
      }
    }

    setGrid(tempGrid);
    setIsGameActive(false); 
    setIsSolved(false);
    setMoveCount(0);
    setStartTime(null);
    setElapsedTime(0);
    if (timerRef.current) clearInterval(timerRef.current);
  }, []);

  useEffect(() => {
    initGame();
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [initGame, currentImageIndex]);

  // Timer Effect
  useEffect(() => {
    if (isGameActive && !isSolved) {
      timerRef.current = window.setInterval(() => {
        setElapsedTime(Date.now() - (startTime || Date.now()));
      }, 100);
    } else {
      if (timerRef.current) clearInterval(timerRef.current);
    }
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [isGameActive, isSolved, startTime]);

  const handleTileClick = (index) => {
    if (isSolved) return;

    if (!isGameActive) {
      setIsGameActive(true);
      setStartTime(Date.now());
    }

    const emptyPos = grid.indexOf(EMPTY_INDEX);
    const row = Math.floor(index / GRID_SIZE);
    const col = index % GRID_SIZE;
    const emptyRow = Math.floor(emptyPos / GRID_SIZE);
    const emptyCol = emptyPos % GRID_SIZE;

    const isAdjacent = 
      (Math.abs(row - emptyRow) === 1 && col === emptyCol) ||
      (Math.abs(col - emptyCol) === 1 && row === emptyRow);

    if (isAdjacent) {
      const newGrid = [...grid];
      newGrid[emptyPos] = newGrid[index];
      newGrid[index] = EMPTY_INDEX;
      setGrid(newGrid);
      setMoveCount(prev => prev + 1);
      
      // Check win
      const isWin = newGrid.every((val, idx) => val === idx);
      if (isWin) {
        setIsSolved(true);
        setIsGameActive(false);
      }
    }
  };

  const handleSaveScore = async () => {
    if (!playerName.trim()) {
      alert("Prosím zadaj meno (max 8 znakov)");
      return;
    }
    await saveScore({
      name: playerName.trim().substring(0, 8),
      time: elapsedTime,
      date: new Date().toISOString()
    });
    setShowLeaderboard(true);
  };

  const formatTime = (ms) => {
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    return `${minutes.toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
  };

  return (
    <div className="flex flex-col items-center min-h-full p-4 w-full bg-gray-50/50">
      {/* Top Bar */}
      <div className="w-full max-w-2xl flex justify-between items-center mb-6">
        <button 
          onClick={onBack}
          className="bg-white border-2 border-capoliBlue text-capoliBlue px-4 py-2 rounded font-bold hover:bg-capoliBlue hover:text-white transition-colors shadow-sm"
        >
          ← Späť
        </button>
        <h1 className="text-3xl font-black text-capoliBlue hidden md:block tracking-widest">CUBES</h1>
        <div className="flex space-x-2">
            <div className="bg-capoliBlue text-white px-4 py-2 rounded font-mono border-2 border-capoliBlue">
                Ťahy: <span className="font-bold">{moveCount}</span>
            </div>
            <div className="bg-capoliYellow text-capoliBlue px-4 py-2 rounded font-mono font-bold w-24 text-center border-2 border-capoliBlue">
                {formatTime(elapsedTime)}
            </div>
        </div>
      </div>

      {/* Main Game Area */}
      <div className="flex flex-col lg:flex-row gap-8 items-start justify-center w-full">
        
        {/* The Grid */}
        <div 
          className="relative bg-capoliBlue p-2 rounded shadow-2xl border-4 border-capoliBlue"
          style={{ width: 'min(90vw, 500px)', height: 'min(90vw, 500px)' }}
        >
          {/* Success Overlay */}
          {isSolved && (
             <div className="absolute inset-0 z-20 bg-capoliBlue/90 flex flex-col items-center justify-center text-white rounded p-6 animate-fade-in backdrop-blur-sm border-4 border-capoliYellow">
                <h2 className="text-5xl font-black text-capoliYellow mb-2 drop-shadow-lg">HOTOVO!</h2>
                <p className="text-2xl mb-8 font-mono">{formatTime(elapsedTime)}</p>
                
                <div className="flex flex-col gap-3 w-full max-w-xs">
                    <label className="text-sm text-yellow-200 font-bold uppercase tracking-wider text-center">Zapíš sa do siene slávy</label>
                    <input 
                      type="text" 
                      maxLength={8}
                      value={playerName}
                      onChange={(e) => setPlayerName(e.target.value)}
                      className="p-3 rounded text-capoliBlue text-center font-bold text-xl uppercase outline-none border-4 border-transparent focus:border-capoliYellow transition-colors"
                      placeholder="TVOJE MENO"
                    />
                    <button 
                      onClick={handleSaveScore}
                      className="mt-2 bg-gradient-to-r from-yellow-400 to-yellow-600 text-capoliBlue font-black py-3 rounded hover:brightness-110 transition-all shadow-lg text-lg uppercase"
                    >
                      Uložiť výsledok
                    </button>
                </div>
                <button onClick={initGame} className="mt-8 text-sm text-yellow-200 underline hover:text-white">Hrať znova bez uloženia</button>
             </div>
          )}

          <div className="grid grid-cols-5 gap-1 w-full h-full bg-capoliBlue border-4 border-capoliYellow">
            {grid.map((tileNumber, index) => {
              const originalRow = Math.floor(tileNumber / GRID_SIZE);
              const originalCol = tileNumber % GRID_SIZE;
              const isBlank = tileNumber === EMPTY_INDEX;

              return (
                <div
                  key={`${index}-${tileNumber}`}
                  onClick={() => handleTileClick(index)}
                  className={`
                    relative w-full h-full overflow-hidden transition-all duration-100 rounded-sm
                    ${isBlank ? 'opacity-0 cursor-default' : 'cursor-pointer hover:brightness-110 shadow-inner'}
                  `}
                  style={{ backgroundColor: '#e5e7eb' }}
                >
                  {!isBlank && (
                    <div 
                        className="w-full h-full bg-cover"
                        style={{
                            backgroundImage: `url(${PUZZLE_IMAGES[currentImageIndex]})`,
                            backgroundSize: '500% 500%', 
                            backgroundPosition: `${originalCol * 25}% ${originalRow * 25}%` 
                        }}
                    >
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Controls & Mini View */}
        <div className="flex flex-col gap-6 w-full max-w-sm lg:w-72">
           {/* Preview */}
           <div className="bg-white p-2 rounded shadow-md border-2 border-capoliBlue">
              <div className="bg-capoliBlue text-white text-xs font-bold uppercase py-1 px-2 mb-2 text-center rounded-sm">Predloha</div>
              <div className="aspect-square w-full overflow-hidden rounded bg-gray-200 relative">
                  <img 
                    src={PUZZLE_IMAGES[currentImageIndex]} 
                    onError={(e) => {
                      // Fallback if image not found
                      e.target.style.display='none';
                      e.target.parentElement.innerHTML += '<div class="absolute inset-0 flex items-center justify-center text-gray-400 text-center p-4">Obrázok nenájdený.<br/>Nahrajte puzzle1.jpg</div>';
                    }}
                    alt="Target" 
                    className="w-full h-full object-cover"
                  />
              </div>
           </div>

           {/* Controls */}
           <div className="bg-white p-4 rounded shadow-md border-2 border-gray-200 space-y-3">
              <button 
                onClick={initGame}
                className="w-full py-3 bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold uppercase text-sm rounded transition-colors border-2 border-gray-300"
              >
                Reštartovať
              </button>
              
              <button 
                onClick={() => setShowLeaderboard(true)}
                className="w-full py-3 bg-capoliBlue text-white font-bold uppercase text-sm rounded hover:bg-blue-900 transition-colors shadow-md"
              >
                Tabuľka výsledkov
              </button>

              <div className="pt-4 border-t border-gray-100">
                <label className="text-xs text-capoliBlue font-bold block mb-2 uppercase text-center">Zmeniť obrázok</label>
                <div className="flex gap-2 justify-center">
                    {PUZZLE_IMAGES.map((img, idx) => (
                        <button 
                            key={idx}
                            onClick={() => setCurrentImageIndex(idx)}
                            className={`w-12 h-12 rounded overflow-hidden border-4 transition-all ${currentImageIndex === idx ? 'border-capoliYellow scale-110 shadow-lg z-10' : 'border-transparent opacity-60 hover:opacity-100 grayscale hover:grayscale-0'}`}
                        >
                            <img src={img} alt={`Choice ${idx}`} className="w-full h-full object-cover" />
                        </button>
                    ))}
                </div>
              </div>
           </div>
        </div>
      </div>

      {showLeaderboard && (
        <Leaderboard 
            onClose={() => setShowLeaderboard(false)} 
            highlightName={playerName}
        />
      )}
    </div>
  );
};

// --- APP ROOT ---
const App = () => {
  const [currentView, setCurrentView] = useState(ViewState.MENU);

  return (
    // Global Framing (The "Capoli" Frame)
    <div className="min-h-screen bg-white p-2 md:p-6 lg:p-8 flex items-center justify-center">
      <div className="w-full max-w-[1400px] min-h-[800px] bg-white border-[10px] border-capoliBlue relative shadow-2xl flex flex-col">
        {/* Inner Gold Border */}
        <div className="absolute inset-0 border-[6px] border-capoliYellow pointer-events-none z-50"></div>
        
        {/* Main Content Area */}
        <div className="flex-grow relative z-0">
          {currentView === ViewState.MENU && (
            <MainMenu onNavigate={setCurrentView} />
          )}
          
          {currentView === ViewState.GAME && (
            <CubesGame onBack={() => setCurrentView(ViewState.MENU)} />
          )}
        </div>
      </div>
    </div>
  );
};

// Mount the App
const rootElement = document.getElementById('root');
if (rootElement) {
    const root = ReactDOM.createRoot(rootElement);
    root.render(<App />);
}
