<!DOCTYPE html>
<html lang="hr">
    <meta name="google" content="notranslate">
    <meta charset="UTF-8">
    <title>Igra pamćenja</title>
    <link rel="stylesheet" href="stilovi.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <canvas id="background-canvas"></canvas>

    <div id="difficulty-selection" class="overlay-message">
        <h3> </h3>
        <h3> </h3>
        <h3> </h3>
        <h2 style="color: #fffede; text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.9); text-decoration: underline;">
            Odaberi težinu
        </h2>
        <button class="difficulty-btn" id="easy-btn">😊 Laganica</button><p> </p>
        <button class="difficulty-btn" id="normal-btn">😎 Normala</button><p> </p>
        <button class="difficulty-btn" id="hard-btn">🤯 Ludilo!</button><p> </p>
        <button class="difficulty-btn" id="back-btn">❌ Nazad</button><p> </p>
        <h3> </h3>
        <h3> </h3>
        <h3> </h3>
    </div>
    <div id="background-layer"></div>
    <div id="transition-layer"></div>


    
    <!-- Logo -->
    <div id="background-overlay"></div>
    <img id="logo" src="bananaman-hidayat-aydin-transparent.png" alt="Logo">
    <div class="player-info">
        <!-- Prvi red: Ime i Nadimak -->
        <div>
            <span id="player-name" class="player-name">JGN</span>
            <span id="player-nick" class="player-nick"></span>
        </div>
        <!-- Drugi red: Medalje i Zlato -->
        <div class="player-stats">
            <span id="medal-count" class="medal">🏆</span>
            <span id="gold-count" class="gold">👑</span>
        </div>
    </div>
    <div id="main-buttons">
        <button class="menu-btn" id="start-game-btn">🎮 Standardica</button>
        <button class="menu-btn" id="classic-mode-btn">🤠 Klasika</button> <!-- Novo dugme za Klasiku -->
        <button class="menu-btn" id="bomb-mode-btn" style="background-color: black; color: white;">🔥 Specijal</button>
        <button class="menu-btn" id="time-attack-btn">🕒 Dokle više...</button>
        <button class="menu-btn" id="practice-btn">🤓 Vježba</button>
        <button class="menu-btn" id="instructions-btn">📖 Uputstvo</button>
        <button class="menu-btn" id="continue-game-btn" style="background-color: rgb(0, 75, 22); color: white;">🚀 Nastavi</button>
        <button class="menu-btn" id="view-results-btn">📊 Rezultati</button>
        <button class="menu-btn" id="tema-mode-btn" style="background-color: rgb(35, 0, 130); color: white;">✨ Tema: Jami Stikeri</button>
    </div>

    </div>
<!-- Zaglavlje sa info panelom -->
<div id="header-container" class="hidden">
    <div class="info">
        <p>
            N:<span id="level"></span>&nbsp;
            <span id="lives-display">❤️<span id="lives"></span></span>
        </p>
        <div class="timer-container">
            <p>&nbsp;&nbsp;🃏<span id="cards-to-match-timer">2</span> kartice &nbsp;⏱️<span id="timer">120</span>s &nbsp;💎<span id="score-timer">0</span></p>
        </div>
        <div class="moves-container">
            <p>&nbsp;&nbsp;🃏<span id="cards-to-match-moves">2</span> kartice &nbsp;🤏<span id="moves">0</span>&nbsp;💎<span id="score-moves">0</span></p>
        </div>        
    </div>
</div>
<div id="header-container-hybrid" class="hidden">
    <div class="info">
        <p>N:<span id="level-hybrid"></span>&nbsp;❤️<span id="lives-hybrid"></span></p>
<div class="hybrid-container" style="display: none;">
    <p>&nbsp;&nbsp;🃏<span id="cards-to-match-hybrid">2</span> kartice &nbsp;⏱️<span id="timer-hybrid">120</span>s &nbsp;🤏<span id="moves-hybrid">0</span>&nbsp;💎<span id="score-hybrid">0</span></p>
</div>
</div>
</div>
    <!-- Omotač za ploču za igru i poruke -->
    <div id="game-container">
        <!-- Ploča za igru (grid) -->
        <div id="game-board"></div>
        <!-- Poruka o završenom nivou -->
        <div id="level-up-msg" class="overlay-message">
            <h2 class="level-up-title" style="color: #fffede; text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.9); text-decoration: none;">
                <img src="200.webp" alt="Bravo!" style="width: 100px; height: auto;">
                <p>Nivo je završen!</p>
            </h2>
            <p id="final-score-overlay"></p>
            <button id="next-level-btn-overlay">Sljedeći nivo</button>
        </div>
        <!-- Poruka o završenoj igri -->
        <div id="game-completed-msg" class="overlay-message">
            <!--<h2>Čestitamo! Završili ste igru!</h2>-->
            <p id="final-score-game-over">Ukupno osvojeni poeni: 0</p>
            <button id="restart-game-btn-overlay">Ponovo pokreni igru</button>
        </div>
        <!-- Overlay za pauzu -->
        <div id="pause-overlay" class="overlay-message">
            <h2>Igra je pauzirana</h2>
            <button id="resume-btn">Nastavi igru</button>
            <button id="end-game-btn">Kraj</button>
        </div>
    </div>
<!-- Poruka kada istekne vrijeme -->
<div id="time-up-msg" class="overlay-message">
    <h2>Vrijeme je isteklo!</h2>
    <h2 id="final-score-time-up">Osvojili ste 0 💎!</h2>
    <button id="continue-btn" class="hidden">Nastaviti igru: plati 36 💎</button>
    <button id="use-life-btn" class="hidden">Nastavi igru: Iskoristi ❤️</button>
    <button id="restart-btn" class="hidden">Završi igru</button>
</div>
<div id="match-requirement"></div>

    <!-- Audio datoteke za zvučne efekte -->
    <audio id="reveal-sound" src="sounds/reveal.mp3"></audio>
    <audio id="click-sound" src="sounds/klik.mp3"></audio>
    <audio id="flip-sound" src="sounds/flip.mp3"></audio>
    <audio id="flip-sound2" src="sounds/flip2.mp3"></audio>
    <audio id="match-sound" src="sounds/match.mp3"></audio>
    <audio id="mismatch-sound" src="sounds/mismatch.mp3"></audio>
    <audio id="level-up-sound" src="sounds/level-up.mp3"></audio>
    <audio id="end-sound" src="sounds/end.mp3"></audio>
    <audio id="card-appear-sound" src="sounds/card-appear.mp3"></audio>
    <audio id="card-hide-sound" src="sounds/card-hide.mp3"></audio>
    <audio id="game-over-sound" src="sounds/game-over.mp3"></audio>
    <audio id="game-over-TU-sound" src="sounds/TATU.mp3"></audio>
    <audio id="applause-sound" src="sounds/applause.mp3"></audio>
    <audio id="nomoves" src="sounds/nomoves.mp3"></audio>
    <audio id="pause" src="sounds/pause.mp3"></audio>
    <!-- Forma za podešavanja Vježbe -->
    <div id="practice-settings" class="overlay">
        <div class="overlay-content">
            <h2>Prilagođene postavke za Vježbu</h2>
            <!-- Mandatorna polja -->
            <label style="background-color: yellow;">Broj redova:
                <input type="number" id="practice-rows" min="2" max="10" value="4">
            </label>
            <label style="background-color: yellow;">Broj kolona:
                <input type="number" id="practice-cols" min="2" max="10" value="4">
            </label>
            <label style="background-color: yellow;">Broj kartica za slaganje:
                <input type="number" id="practice-match-cards" min="2" max="5" value="2">
            </label>
            <label style="background-color: yellow;">Vrijeme za rješavanje (s):
                <input type="number" id="practice-solve-time" min="30" max="300" value="120">
            </label>
            <!-- Opcionalna polja -->
            <label>Vrijeme do okretanja kartice (ms):
                <input type="number" id="practice-flip-back-time" min="500" max="5000" value="1500">
            </label>
            <label>Vrijeme prikaza pogrešnog pokušaja (ms):
                <input type="number" id="practice-mismatch-time" min="200" max="2000" value="500">
            </label>
            <label>Vrijeme čekanja nakon uparivanja (ms):
                <input type="number" id="practice-match-delay-time" min="0" value="500">
            </label>
            <label>Broj kartica za prikaz na početku:
                <input type="number" id="practice-cards-to-show" min="0" value="0">
            </label>
            <label>Vrijeme prikaza kartica na početku (ms):
                <input type="number" id="practice-preview-time" min="0" value="0">
            </label>
            <label>Boja kartica:
                <input type="color" id="practice-card-color" value="#ff6666">
            </label>
            <label>Boja pozadine:
                <input type="color" id="practice-bg-color" value="#f4f4f9">
            </label>
            <label>Pozadinska slika:
                <input type="file" id="practice-bg-image" accept="image/*">
            </label>
            <label>Pozadinska muzika:
                <input type="file" id="practice-music" accept="audio/*">
            </label>
            <label>Glasnoća pozadinske muzike:
                <input type="range" id="practice-music-volume" min="0" max="1" step="0.01" value="1">
            </label>
            <label>Slika poleđine kartice:
                <input type="file" id="practice-card-back-image" accept="image/*">
            </label>
            <button id="start-practice-btn">Započni Vježbu</button>
            <button id="cancel-practice-btn">Otkaži</button>
        </div>
    </div>
    <!-- Modal za uputstvo sa informacijama -->
    <div id="instructions-modal" class="overlay-message hidden uputstvo">
        <h4>Informacije o igri:</h4>
        <p2><strong>Verzija igre:</strong> 1.1.B
            <br><strong>Programer, grafika, zvuk i dizajn:</strong> Jasenko Grbo
            <br><strong>Ostalo:</strong> Rezervisano
            <br><strong>Ostalo2:</strong> Rezervisano</p2>

            <br>
        <h2>U  P  U  T  S  T  V  O</h2>
    
        <p><strong>Dobrodošli u našu igru pamćenja</strong> – izazov koji ne samo da testira tvoje vještine već i doprinosi razvoju kognitivnih sposobnosti! Ova igra je osmišljena tako da kroz zabavne i dinamične nivoe poboljša tvoje pamćenje, strateško razmišljanje i brzinu odlučivanja. Sa svakim nivoom postaje sve uzbudljivija, pa će te motivisati da se stalno vraćaš po još!</p>
    
        <h3>1. Načini igre</h3>
        <p class="standardica"><strong>🎮 Standardica</strong>: U ovom modu igraš na vrijeme. Broj poteza je <strong>neograničen</strong>, ali imaš <strong>ograničeno vrijeme</strong> za završavanje nivoa i postizanje što višeg rezultata.</p>
        
        <p class="klasika"><strong>🤠 Klasika</strong>: Mod se igra <strong>na poteze</strong>. Vrijeme je <strong>neograničeno</strong>, ali je broj poteza <strong>ograničen</strong>.</p>
        
        <p class="specijal"><strong>🔥 Specijal</strong>: U Specijal modu, nivoi se razlikuju po ograničenjima:
            <br>- Neki nivoi imaju <strong>ograničeno vrijeme</strong>
            <br>- Neki <strong>ograničen broj poteza</strong>
            <br>- Neki su <strong>hibridni</strong> s oba ograničenja.
            <br>- Specijalne kartice sa <span style="color: rgb(0, 255, 0);">zelenom pozadinom</span> pomažu ti u napredovanju, dok kartice sa <span style="color: rgb(255, 76, 76);">crvenom pozadinom</span> predstavljaju izazov i mogu te usporiti.
        </p>
        
        <p class="dokle-vise"><strong>⏱ Dokle više</strong>: Mod u kojem se nivoi stalno generišu. Cilj je <strong>zarađivati dodatno vrijeme</strong> pravilnim slaganjem kartica. Ovaj mod nema različite težine – igra se završava kada istekne vrijeme.</p>
    
        <h3>2. Težine</h3>
        <p>Za svaki mod osim Dokle više, možeš odabrati jednu od tri težine:
            <br>- <strong>Laganica</strong>: Opusti se uz lakše izazove.
            <br>- <strong>Normala</strong>: Uživaj u umjerenom izazovu.
            <br>- <strong>Ludilo!</strong>: Testiraj svoje granice i vještine!</p>
    
        <h3>3. Osnovna pravila</h3>
        <p>- Prati specifične ciljeve i koristi strategiju prilagođenu modu igre.
            <br>- <strong>Poeni i bonusi</strong>: Na svakih <strong>10 000 💎</strong> dobijaš dodatni život ❤️ (jednokratno).
            <br>- Specijalne kartice utiču na napredak – koristi ih mudro!</p>
    
        <h3>4. Pauza</h3>
        <p>Igru možeš pauzirati klikom na info panel iznad kartica, gdje su prikazani trenutni nivo, poeni, vrijeme i ostale statistike.</p>
        <h3>5. Spremanje stanja</h3>
        <p>Igra automatski snima zadnje stanje kada izađeš iz igre. Svaki nivo možeš nastaviti <strong>maksimalno 3 puta</strong>, što ti omogućava više prilika da savladaš izazove!</p>
        <h3>6. Promjena teme</h3>
        <p>Klikom na dugme <strong>Tema</strong>, možeš promijeniti kompletnu temu igre, uključujući pozadinsku sliku, animacije i sličice na karticama za uparivanje. Pronađi stil koji ti najbolje odgovara!</p>
        <h3>7. Najbolji rezultati</h3>
        <p>- Moji: Tvoji najbolji rezultati čuvaju se lokalno na uređaju i dostupni su za pregled.
            <br>- Globalno: Pogledaj rezultate svih igrača za sve modove i težine igre. Ako je tvoj rezultat dovoljno dobar, pojaviće se i na globalnoj listi!</p>
        <button id="back-btn-instructions">Nazad</button>
    </div>
    <!-- Level Notification Overlay -->
    <div id="level-notification" class="hidden">
        <div class="level-notification-content">
            <h1 id="level-number"></h1>
            <p id="level-match-cards"></p>
            <p id="level-type"></p>
            <p id="level-moves"></p>
            <p id="level-time"></p>
            <div id="countdown-timer">5</div>
            <button id="start-level-button" class="hidden">Pokreni nivo</button>
        </div>
    </div>
<script>
// Globalni niz za praćenje trenutno svirajućih zvukova
// Globalni niz za praćenje trenutno svirajućih zvukova
window.playingAudio = [];

// Omotač za Audio() da prati trenutno aktivne zvukove
const OriginalAudio = window.Audio;
window.Audio = function (...args) {
    const audio = new OriginalAudio(...args);

    // Omotač za logovanje događaja i dinamičko ažuriranje liste
    audio.addEventListener("play", () => {
        // Dodaj zvuk u listu ako već nije tamo
        if (!window.playingAudio.includes(audio)) {
            window.playingAudio.push(audio);
        }

        logCurrentlyPlaying(); // Logiraj trenutno stanje
    });

    audio.addEventListener("pause", () => {
        // Ukloni zvuk iz liste ako je pauziran
        const index = window.playingAudio.indexOf(audio);
        if (index !== -1) {
            window.playingAudio.splice(index, 1);
        }

        logCurrentlyPlaying(); // Logiraj trenutno stanje
    });

    audio.addEventListener("ended", () => {
        // Ukloni zvuk iz liste ako je završio
        const index = window.playingAudio.indexOf(audio);
        if (index !== -1) {
            window.playingAudio.splice(index, 1);
        }

        logCurrentlyPlaying(); // Logiraj trenutno stanje
    });

    return audio;
};
window.pausedAudio = [];
// Funkcija za logovanje trenutno svirajućih zvukova
function logCurrentlyPlaying() {
    console.log("Currently playing audio:", window.playingAudio.map(audio => audio.src));
}
 window.playingAudioObjects = [];
   /* window.activeAudioObjects = [];
    // Omot za Audio() da prati sve instance
const OriginalAudio = window.Audio;
window.Audio = function (...args) {
    const audio = new OriginalAudio(...args);
    window.activeAudioObjects.push(audio);

    // Logiraj kada se kreira novi Audio objekat
    console.log("New Audio object created:", args[0]);
    console.log("Current active audio objects:", window.activeAudioObjects);

    return audio;
};*/

let medalja_ukupno = 0;
let nadimak ="";
let nadimak_level = 0;
let testMode = 0;
let medalja = 0;
let medaljap = 0;
let gold = 0;
let goldp = 0;
let y = 0;
let gameStarted = false; 
function loadInitialGold() {
    const savedData = JSON.parse(localStorage.getItem("savedGameState")) || {};
    gold = savedData.gold || 0; 
    medalja = savedData.medalja || 0; 
    medalja_ukupno = savedData.medalja_ukupno || 0;

    medalja = medalja + medaljap;
    y = Math.round(medalja / 100);
    medalja_ukupno = medalja_ukupno + medaljap;

    console.log("Početni gold i medalja učitan:", gold, medalja);
}
// Funkcija za dohvaćanje ili kreiranje `localStorage` podataka
function getPlayerData() {
    const data = JSON.parse(localStorage.getItem("playerData")) || {};
    return {
        playerName: data.playerName || "Igrač",
    };
}

function savePlayerData(data) {
    localStorage.setItem("playerData", JSON.stringify(data));
}

// Funkcija za ažuriranje DOM-a s imenom igrača
let threshold = 0; // Početni prag za zlato
let tito =0;
function initializeThreshold() {
    // Izračunaj početni prag na osnovu trenutnog `y`
    threshold = Math.floor(y / 100) * 100;
    console.log(`Početni threshold postavljen na ${threshold} za y = ${y}`);
}
function updatePlayerName() {
    // [UKLONJENO] checkAndSyncOnGameStart(); 
    // [UKLONJENO] loadInitialGold();  

    // Ako trebaš da se threshold prvi put izračuna upravo kad ispisuješ igrača
    // (ali ga radije inicijaliziraj nakon loadInitialGold, npr. u DOMContentLoaded)
    if (tito === 0) {
        initializeThreshold();
        tito = 1;
    }

    // Prođi kroz thresholds
    let nicknameIndex = 0;
    for (let i = 0; i < medalThresholds.length; i++) {
        if (medalja_ukupno >= medalThresholds[i]) {
            nicknameIndex = i;
        }
    }

    const storedData = getPlayerData();
    const playerNameDiv = document.getElementById("player-name");
    const playerNickDiv = document.getElementById("player-nick");
    const medalCountDiv = document.getElementById("medal-count");
    const goldCountDiv = document.getElementById("gold-count");

    playerNameDiv.innerText = storedData.playerName;
    playerNickDiv.innerText = nicknames[nicknameIndex];
    medalCountDiv.innerText = `${y} 🏆`;
    goldCountDiv.innerText = `${gold} 👑`;

    nadimak = nicknames[nicknameIndex];
    nadimak_level = nicknameIndex;

    console.log(`Novi nadimak: ${nicknames[nicknameIndex]} za ${medalja_ukupno} medalja!`);

    // [NOVO] - Animacija zlata samo ako je igra zapravo startala
    if (gameStarted) {
        while (y >= threshold + 100) {
            threshold += 100; 
            gold++;
            updateGoldOnly();
            console.log(`Gold povećan na ${gold} za dostignuti prag ${threshold}`);
            animateGoldUpdate();
            showCrownEffect();
        }
    }
}
// Funkcija za animaciju zlata
function animateGoldUpdate() {
    const goldCountDiv = document.getElementById("gold-count");
    const audio = new Audio("sounds/gold.mp3");
    audio.play();

    // Ažuriraj broj zlata
    goldCountDiv.innerText = `${gold} 👑`;

    // Dodaj malo kašnjenja pre pokretanja animacije
    goldTimerId = setTimeout(() => {
        // Resetuj prethodnu animaciju
        goldCountDiv.style.animation = "none"; // Uklanja prethodnu animaciju
        goldCountDiv.offsetHeight; // Forsira reflow za resetovanje animacije

        // Ponovo pokreni animaciju sa blagim kašnjenjem
        goldCountDiv.style.animation = "gold-bounce 0.5s ease-in-out";
    }, 300); // 200ms kašnjenja pre pokretanja animacije
}

// Funkcija za prikaz krune
let goldTimerId = null;
let crownTimerId = null; // Globalna varijabla za ID tajmera krune

function showCrownEffect() {
    confetti({
        particleCount: 480,
        spread: 420,
        origin: { y: 0.4 },
        scalar: 2
    });
    const body = document.body;
    const crown = document.createElement("div");

    // Stilizacija krune
    crown.innerHTML = "👑";
    crown.classList.add("crown-effect");

    // Dodaj krunu u DOM
    body.appendChild(crown);

    console.log("Kruna dodana na ekran");

    // Postavi tajmer za uklanjanje krune
    crownTimerId = setTimeout(() => {
        if (crown.parentNode) {
            console.log("Kruna uklonjena iz DOM-a, tajmer ID:", crownTimerId);
            crown.remove();
            crownTimerId = null; // Resetujemo ID nakon uklanjanja
        }
    }, 1000); // Vrijeme trajanja animacije

    console.log("Tajmer za uklanjanje krune postavljen, ID:", crownTimerId);
}



document.addEventListener("DOMContentLoaded", () => {
    const backgroundLayer = document.getElementById("background-layer");
    backgroundLayer.style.backgroundImage = `url(${themeBackgrounds[""]})`;
    backgroundLayer.style.opacity = 1;

    updatePlayerName();
});
async function checkAndSyncOnGameStart() {
    const storedData = JSON.parse(localStorage.getItem("playerData")) || {};
    const playerName = storedData.playerName || '';
    if (!playerName) {
        console.warn("Nema imena igrača, preskačem provjeru i sinhronizaciju.");
        return;
    }

    try {
        const serverData = await loadLocalStorageFromServer(playerName);
        if (serverData && serverData.status === 'success') {
            const serverSavedDate = new Date(serverData.savedDate);
            const localGame = localStorage.getItem('savedGameState');
            let localSavedDate = null;
            if (localGame) {
                localSavedDate = new Date(JSON.parse(localGame).savedDate);
            }

            if (!localSavedDate || serverSavedDate > localSavedDate) {
                // Server ima novije podatke, obnovi lokalni storage
                restoreLocalStorageFromServer(serverData);
                enableContinueButton();
                console.log("LocalStorage je ažuriran sa servera.");
            } else {
                console.log("LocalStorage je noviji ili jednako nov, nema potrebe za ažuriranjem.");
            }
        } else {
            console.log("Nema podataka na serveru za ovog igrača.");
        }
    } catch (error) {
        console.error("Greška pri provjeri i sinhronizaciji podataka na pokretanju igre:", error);
    }
}

    async function loadLocalStorageFromServer(playerName) {
    try {
        const response = await fetch('https://jami.ba/jgngame/getLocalStorageData.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ nickname: playerName })
        });
        return await response.json();
    } catch (error) {
        console.error('Greška pri učitavanju stanja sa servera:', error);
        return null;
    }
}
// Simulacija logovanja ili stvarno logovanje
function onLoginSuccess(playerName) {
    const storedData = JSON.parse(localStorage.getItem("playerData")) || {};
    storedData.playerName = playerName;
    localStorage.setItem("playerData", JSON.stringify(storedData));

    loadLocalStorageFromServer(playerName).then(serverData => {
        if (serverData && serverData.status === 'success') {
            const serverSavedDate = new Date(serverData.savedDate);
            const localGame = localStorage.getItem('savedGameState');
            let localSavedDate = null;
            if (localGame) {
                localSavedDate = new Date(JSON.parse(localGame).savedDate);
            }

            if (!localSavedDate) {
                restoreLocalStorageFromServer(serverData);
                enableContinueButton();
            } else {
                if (serverSavedDate > localSavedDate) {
                    restoreLocalStorageFromServer(serverData);
                    enableContinueButton();
                } else {
                    syncLocalStorageWithServer();
                    enableContinueButton();
                }
            }
        } else {
            // Nema podataka na serveru, Continue dugme ostaje neaktivno
            disableContinueButton();
        }

        // [OSTAVLJENO] - Tek kad odradimo gore sync/restore,
        //                možemo osvježiti prikaz (ako želimo odmah)
        updatePlayerName();  
    });
}

    // Prvi put postavljamo trenutnu temu na početnu vrijednost
    // Početna tema je prazna (ili možeš postaviti direktno kao "default")
    /*// Selektuje sva dugmad na stranici
    const buttons = document.querySelectorAll('button');
    const clickSound = document.getElementById('click-sound');

    // Dodaje event listener na svako dugme
    buttons.forEach(button => {
        button.addEventListener('click', () => {
            clickSound.currentTime = 0; // Vraća zvuk na početak
            clickSound.play(); // Reprodukuje zvuk
        });
    });*/
    let width = window.innerWidth;
    let height = window.innerHeight;
    let activeSpecialSounds = [];
    const rezultatiSound = new Audio('sounds/rezultati.mp3');
    const lifesound = new Audio('sounds/life.mp3');
    const beepSound = new Audio('sounds/beep.mp3');
    const continueSound = new Audio('sounds/plati.mp3');
    const useLifeSound = new Audio('sounds/srceplati.mp3');
    const restartSound = new Audio('sounds/restart.mp3');
    let helpRevealTimeout;
   
</script>
<script src="leveli/ostalo.js"></script>
<script src="leveli/nlevels.js"></script>
<script src="animacije.js"></script>
<script src="bonusminigame.js"></script>
<script src="leveli/elevels.js"></script>
<script src="leveli/blevels.js"></script>
<script src="leveli/cnlevels.js"></script>
<script src="leveli/hlevels.js"></script>
<script src="redirect.js"></script>
<script src="startButton.js"></script>
<script src="leveli/eblevels.js"></script>
<script src="leveli/hblevels.js"></script>

<script>
    
    function onStartGame() {
    gameStarted = true; // [NOVO] Sada je igra zaista startana
    console.log('Pokretanje igre...');

    document.getElementById('main-buttons').style.display = 'none';
    mainButtons.style.display = 'flex';

    // Ovdje staviš svoju logiku
    startBouncingImages();
    // startGame();
}


// Pokretanje Start Dugmeta
function showUpdateAlert(message, title = 'Obavještenje', icon = 'informacija', onOkCallback = null) {
        setTimeout(() => {
            let existingModal = document.getElementById('custom-update-alert');
            if (existingModal) {
                existingModal.remove();
            }
            
            const modalOverlay = document.createElement('div');
            modalOverlay.id = 'custom-update-alert';
            modalOverlay.style.position = 'fixed';
            modalOverlay.style.top = '0';
            modalOverlay.style.left = '0';
            modalOverlay.style.width = '100%';
            modalOverlay.style.height = '100%';
            modalOverlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
            modalOverlay.style.display = 'flex';
            modalOverlay.style.justifyContent = 'center';
            modalOverlay.style.alignItems = 'center';
            modalOverlay.style.zIndex = '100001';
            modalOverlay.style.animation = 'fadeIn 0.1s ease';

            const modalContent = document.createElement('div');
            modalContent.style.backgroundColor = '#fff';
            modalContent.style.padding = '8px 10px';
            modalContent.style.borderRadius = '10px';
            modalContent.style.boxShadow = '0 5px 15px rgba(0,0,0,0.3)';
            modalContent.style.textAlign = 'center';
            modalContent.style.maxWidth = '348px';
            modalContent.style.width = '70%';
            modalContent.style.position = 'relative';
            
            if (icon === 'error') {
                modalContent.style.animation = 'shakeModal 0.5s';
            } else {
                modalContent.style.animation = 'happyJump 0.3s ease';
            }

            if (icon !== 'none') {
                const iconElement = document.createElement('div');
                iconElement.style.marginBottom = '7px';
                iconElement.innerHTML = getUpdateIconSVG(icon);
                modalContent.appendChild(iconElement);
            }

            const titleElement = document.createElement('h2');
            titleElement.textContent = title;
            titleElement.style.marginBottom = '7px';
            modalContent.appendChild(titleElement);

            const messagePara = document.createElement('p');
            messagePara.textContent = message;
            messagePara.style.marginBottom = '10px';
            messagePara.style.fontSize = '1.8rem';
            messagePara.style.color = '#333';
            modalContent.appendChild(messagePara);

            const okButton = document.createElement('button');
            okButton.textContent = 'OK';
            okButton.style.padding = '10px 20px';
            okButton.style.fontSize = '1.5rem';
            okButton.style.border = 'none';
            okButton.style.borderRadius = '5px';
            okButton.style.backgroundColor = '#02750c';
            okButton.style.color = '#fff';
            okButton.style.cursor = 'pointer';
            okButton.style.transition = 'background-color 0.3s ease, box-shadow 0.3s ease';
            okButton.style.marginTop = '10px';
            okButton.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.3)';

            okButton.addEventListener('mouseover', () => {
                okButton.style.backgroundColor = '#025e0a';
                okButton.style.boxShadow = '0 6px 8px rgba(0, 0, 0, 0.4)';
            });

            okButton.addEventListener('mouseout', () => {
                okButton.style.backgroundColor = '#02750c';
                okButton.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.3)';
            });

            okButton.addEventListener('click', () => {
                modalOverlay.remove();
                if (typeof onOkCallback === 'function') {
                    onOkCallback();
                }
            });

            modalContent.appendChild(okButton);
            modalOverlay.appendChild(modalContent);
            document.body.appendChild(modalOverlay);
        }, 124);
    }

    function getUpdateIconSVG(icon) {
        switch(icon) {
            case 'success':
                return `<svg width="50" height="50" viewBox="0 0 24 24" fill="#28a745">
                            <path d="M20.285 2.857a1 1 0 0 1 1.428 1.428l-12 12a1 1 0 0 1-1.428 0l-5-5a1 1 0 1 1 1.428-1.428L8 13.172l11.285-11.285z"/>
                        </svg>`;
            case 'error':
                return `<svg width="50" height="50" viewBox="0 0 24 24" fill="#dc3545">
                            <path d="M12 10.586l4.95-4.95a1 1 0 1 1 1.414 1.414L13.414 12l4.95 4.95a1 1 0 1 1-1.414 1.414L12 13.414l-4.95 4.95a1 1 0 1 1-1.414-1.414L10.586 12l-4.95-4.95a1 1 0 1 1 1.414-1.414L12 10.586z"/>
                        </svg>`;
            default:
                return `<svg width="50" height="50" viewBox="0 0 24 24" fill="#17a2b8">
                            <path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm.75 18h-1.5v-8h1.5v8zm0-10.25h-1.5V6h1.5v1.75z"/>
                        </svg>`;
        }
    }
   function playSoundjgn(filename) {
        const audio = new Audio(`sounds/${filename}`);
        audio.play();
    }
// Pokretanje Start Dugmeta
document.addEventListener('DOMContentLoaded', async () => {
        // Ubacujemo faze update-a
        let updatePhase = localStorage.getItem('updatePhase') || '0';
        const cacheName = 'jgn-v5';
        const cacheExists = await caches.has(cacheName);

        if (updatePhase === '0') {
            // Ako cache ne postoji ili je broj stavki ispod 30, prikazujemo prvu poruku
            if (!cacheExists) {
                playSoundjgn('startsuccess.mp3');
                showUpdateAlert(
                    'Igra se mora ažurirati. Klikni OK za početak.',
                    'Ažuriranje',
                    'informacija',
                    () => {
                        localStorage.setItem('updatePhase', '1');
                        window.location.href = 'https://jami.ba/jgngame';
                    }
                );
                return;
            }
            const cache = await caches.open(cacheName);
            const cacheKeys = await cache.keys();
            if (cacheKeys.length < 30) {
                playSoundjgn('startsuccess.mp3');
                showUpdateAlert(
                    'Igra se mora ažurirati. Klikni OK za početak.',
                    'Ažuriranje',
                    'informacija',
                    () => {
                        localStorage.setItem('updatePhase', '1');
                        window.location.href = 'https://jami.ba/jgngame';
                    }
                );
                return;
            }
            // Ako već imamo keš >=30 stavki, možemo odmah nastaviti bez poruka
        }
        else if (updatePhase === '1') {
            // Druga poruka
            playSoundjgn('startsuccess.mp3');
            showUpdateAlert(
                'Ubačeni su novi leveli i zvukovi. Kliknite OK za početak igre.',
                'Ažuriranje završeno',
                'success',
                () => {
                    localStorage.setItem('updatePhase', '2');
                    window.location.href = 'https://jami.ba/jgngame';
                }
            );
            return;
        }
        else if (updatePhase === '2') {
            // Nakon druge poruke
            localStorage.removeItem('updatePhase'); 
        }

        // [NOVO] - prvo uradi provjeru i sinhronizaciju sa serverom
        await checkAndSyncOnGameStart();

        // Zatim učitaj localStorage u globalne varijable...
        loadInitialGold();

        // Inicijalizuj threshold
        initializeThreshold();

        // Tek sad ispiši ime igrača i valute
        updatePlayerName();

        // Podesi background
        const backgroundLayer = document.getElementById("background-layer");
        backgroundLayer.style.backgroundImage = `url(${themeBackgrounds[""]})`;
        backgroundLayer.style.opacity = 1;

        // Na kraju prikaži start dugme
        showStartButton({
            buttonText: '🎮 Pokreni Igru',
            buttonFontSize: '3rem',
            buttonColor: '#ff0303',
            buttonTextColor: '#ffffff',
            buttonShadow: '0 4px 6px rgba(0, 0, 0, 0.3)',
            blinkInterval: 1000,
            onStart: onStartGame
        });

        // Provjera "Nastavi igru" dugmeta
        const savedGameState = localStorage.getItem('savedGameState');
        if (savedGameState) {
            const gameState = JSON.parse(savedGameState);
            continueCount = gameState.continueCount || 0;
            if (continueCount >= maxContinues) {
                disableContinueButton();
            } else {
                enableContinueButton();
            }
        } else {
            disableContinueButton();
        }
    });

let globalTotalMatchingCards = 0;  // globalna varijabla za ukupne kartice za uparivanje
let suspiciousActive = false;
let suspiciousPenaltyCount = 0;


function applyGrayscale(duration) {
    // Primeni crno-beli filter na ceo body, uključujući pozadinsku sliku i sadržaj
    document.body.style.filter = 'grayscale(100%)';
    
    // Nakon određenog vremena ukloni filter
    setTimeout(() => {
        document.body.style.filter = 'none';
    }, duration); // Trajanje u milisekundama
}
    let milestone = 0;
    let specialSound;
    let pointsModifier = 1;
    let isHybridMode = false;
    let rmc = false;
    let bns = true;
    let levelCompleted = false;
    let da_li_je_game_over = false;
    let sessionId = null;

const useLifeButton = document.getElementById('use-life-btn');
const levelDisplayHybrid = document.getElementById('level-hybrid');
const scoreDisplayHybrid = document.getElementById('score-hybrid');
const cardsToMatchHybrid = document.getElementById('cards-to-match-hybrid');
const headerContainerHybrid = document.getElementById('header-container-hybrid');
const movesHybrid = document.getElementById('moves-hybrid');
const timerHybrid = document.getElementById('timer-hybrid');
let currentGameMode = 'Standardica';
let totalscore = 0;


function calculateMaxHeight(grid, levelType, availableWidth, availableHeight) {
    
    console.log("Funkcija pozvana sa sljedećim parametrima:");
    console.log("Grid:", grid);
    console.log("Level type:", levelType);
    console.log("Available width:", availableWidth);
    console.log("Available height:", availableHeight);

    const gameBoard = document.getElementById('game-board');
    let maxHeight;

    switch (levelType) {
        case 'cols-rows': {
            console.log("Level tip: cols-rows");
            const { cols, rows } = grid; // Grid definisan kao { cols: x, rows: y }
            console.log("Cols:", cols, "Rows:", rows);

            const cardWidth = (availableWidth - (cols - 1) * 7) / cols; // Računamo širinu kartice
            console.log("Izračunata širina kartice:", cardWidth);

            const cardHeight = cardWidth; // Kartice su kvadrati
            maxHeight = rows * cardHeight + (rows - 1) * 7; // Ukupna visina grida
            console.log("Izračunata visina grida (bez skaliranja):", maxHeight);
            break;
        }
        case 'array': {
            console.log("Level tip: array");
            console.log("Grid (broj kartica po redovima):", grid);

            // Pronađi red sa najviše kartica
            const maxCardsInRow = Math.max(...grid);
            console.log("Maksimalan broj kartica u jednom redu:", maxCardsInRow);

            // Izračunaj širinu kartica prema redu sa najviše kartica
            const cardWidth = (availableWidth - (maxCardsInRow - 1) * 7) / maxCardsInRow;
            console.log("Izračunata širina kartica za sve redove:", cardWidth);

            // Svi redovi imaju istu širinu kartica, računaj visinu za svaki red
            const rowHeights = grid.map((numCardsInRow, index) => {
                const rowHeight = cardWidth; // Visina kartica je ista kao širina
                console.log(`Red ${index + 1}: Broj kartica: ${numCardsInRow}, Visina reda: ${rowHeight}`);
                return rowHeight;
            });

            // Ukupna visina grida
            maxHeight = rowHeights.reduce((sum, height) => sum + height, 0) + (grid.length - 1) * 7;
            console.log("Ukupna visina grida (bez skaliranja):", maxHeight);
            break;
        }
        case 'matrix': {
            console.log("Level tip: matrix");
            console.log("Grid (2D matrica):", grid);

            const rowHeights = grid.map((row, rowIndex) => {
                const numElements = row.filter(cell => cell === 'k' || cell === 'p').length; // Broj kartica i placeholdera
                const cardWidth = (availableWidth - (numElements - 1) * 7) / numElements;
                console.log(`Red ${rowIndex + 1}: Broj elemenata: ${numElements}, Širina kartice: ${cardWidth}`);
                return cardWidth; // Visina kartica je ista kao širina
            });

            maxHeight = rowHeights.reduce((sum, height) => sum + height, 0) + (grid.length - 1) * 7;
            console.log("Ukupna visina grida (bez skaliranja):", maxHeight);
            break;
        }
        default:
            console.error("Nepoznat level type:", levelType);
            return;
    }

    // Ako je maxHeight veći od dostupne visine, skaliraj
    if (maxHeight > availableHeight) {
        const scaleFactor = availableHeight / maxHeight;
        console.log("Max height prelazi dostupnu visinu! Skaliramo...");
        console.log("Faktor skaliranja:", scaleFactor);

        maxHeight = availableHeight;
        const scaledWidth = availableWidth * scaleFactor;
        gameBoard.style.setProperty('max-width', `${scaledWidth}px`);
        console.log("Nova širina grida nakon skaliranja:", scaledWidth);
    }

    // Postavi max-height na game-board
    gameBoard.style.setProperty('max-height', `${maxHeight}px`);
    console.log("Postavljena max-height na game-board:", maxHeight);
}

imenivoa ="";
function startGame() {

    startTime = Date.now();

    if (selectedDifficulty === null) {
        // Prikaži selektor težine ako nije odabrana
        showDifficultySelection();
        return;
    }
    console.log("Starting game with difficulty:", selectedDifficulty);
    console.log("Is Bomb Mode:", isBombMode);
    console.log("Is Classic Mode:", isClassicMode);

    // Inicijalizacija poena
    score = 0;
    matchedCards = 0;
    levelCompleted = false;
    isBoardLocked = false;
    bns = true;

    // Resetuj ostale modove
    isPracticeMode = false;
    isTimeAttackMode = false;
    isHybridMode = false;

    // Initialize lives based on selected difficulty
    if (selectedDifficulty === 'easy') {
        lives = 2;
    } else if (selectedDifficulty === 'normal') {
        lives = 1;
    } else if (selectedDifficulty === 'hard') {
        lives = 0;
    }



    // Show the appropriate header
    document.getElementById('header-container').style.display = 'none';
    document.getElementById('header-container-hybrid').style.display = 'none';

    // Postavi nivoe i trenutni nivo na osnovu moda i težine
    if (isBombMode) {
        if (selectedDifficulty === 'easy') {
            levels = eblevels;
            imenivoa = "Specijal - Laganica";
        
        } else if (selectedDifficulty === 'normal') {
            levels = blevels;
            imenivoa = "Specijal - Normala";
            console.log("Selected Bomb Mode Levels: blevels");
        } else if (selectedDifficulty === 'hard') {
            levels = hblevels;
            imenivoa = "Specijal - Ludilo!";
            console.log("Selected Bomb Mode Levels: hblevels");
        }
    } else if (isClassicMode) {
        if (selectedDifficulty === 'easy') {
            levels = celevels;
            imenivoa = "Klasika - Laganica";
            console.log("Selected Classic Mode Levels: celevels");
        } else if (selectedDifficulty === 'normal') {
            levels = cnlevels;
            imenivoa = "Klasika - Normala";
            console.log("Selected Classic Mode Levels: cnlevels");
        } else if (selectedDifficulty === 'hard') {
            levels = chlevels;
            imenivoa = "Klasika - Ludilo!";
            console.log("Selected Classic Mode Levels: chlevels");
        }
    } else {
        if (selectedDifficulty === 'easy') {
            levels = elevels;
            imenivoa = "Standardica - Laganica";
            console.log("Selected Standard Mode Levels: elevels");
        } else if (selectedDifficulty === 'normal') {
            levels = nlevels;
            imenivoa = "Standardica - Normala";
            console.log("Selected Standard Mode Levels: nlevels");
        } else if (selectedDifficulty === 'hard') {
            levels = hlevels;
            imenivoa = "Klasika - Ludilo!";
            console.log("Selected Standard Mode Levels: hlevels");
        }
    }
    
    // Provjeri da li su levels ispravno postavljeni
    if (!levels || levels.length === 0) {
        console.error("Levels nisu pravilno inicijalizirani. Provjerite definiciju level-eva.");
        return;
    }

    // Inicijalizuj trenutni nivo
    currentLevelIndex = 0;
    level = levels[currentLevelIndex];

    // Set mode flags based on the new level's properties
    isHybridMode = level.solveTime > 0 && level.moves > 0;
    isClassicMode = level.moves > 0 && level.solveTime === 0;
    isTimeMode = level.solveTime > 0 && level.moves === 0;

    // Update lives display
    if (isHybridMode) {
        document.getElementById('lives-hybrid').textContent = lives;
    } else {
        document.getElementById('lives').textContent = lives;
    }
    

    // Show the appropriate header based on mode
   
    console.log("Current Level:", level);

    // Set remaining moves or time based on the mode
    if (isHybridMode) {
        remainingMoves = level.moves + testMode + kupljenipoteziskroz + kupljenipotezi;
        remainingTime = level.solveTime + testMode;
        document.getElementById('moves-hybrid').textContent = remainingMoves;
        document.getElementById('timer-hybrid').textContent = remainingTime;
    } else if (isClassicMode) {
        remainingMoves = level.moves + testMode + kupljenipoteziskroz + kupljenipotezi;
        document.getElementById('moves').textContent = remainingMoves;
        console.log("Classic Mode Enabled with moves:", remainingMoves);
    } else {
        remainingTime = level.solveTime + testMode + kupljenovrijeme + kupljenovrijemeskroz;
        document.getElementById('timer').textContent = remainingTime;
        console.log("Time Mode Enabled with remainingTime:", remainingTime);
    }

    // Reset pause and board lock
    isPaused = false;
    isBoardLocked = false;

    // Start fullscreen mode
   // openFullscreen();

    // Add fade-out class for animation
    document.body.classList.add('fade-out');
    setTimeout(() => {
        document.body.classList.remove('fade-out');
        // Hide and show relevant elements
        logo.style.display = 'none';
        if (isHybridMode) {
            headerContainerHybrid.style.display = 'flex';
        } else {
            headerContainer.style.display = 'flex';
        }
        startGameBtn.style.display = 'none';
        BombBtn.style.display = 'none';
        practiceBtn.style.display = 'none';
        timeAttackBtn.style.display = 'none';
        classicModeBtn.style.display = 'none'; // Hide "Classic" button
        instructionsBtn.style.display = 'none';
        gameBoard.style.display = 'grid';
        infoPanel.style.display = 'flex';
        document.body.style.backgroundColor = level.backgroundColor || '#ffffff';

        // Pause background music if exists
        if (bgMusic) {
            bgMusic.pause();
            bgMusic.currentTime = 0;
        }

        // Start new background music if defined for the current level
        if (level.music) {
            bgMusic = new Audio(level.music);
            bgMusic.loop = true;
            bgMusic.volume = 1; // Adjust the volume as needed
            bgMusic.play();
            console.log("Playing background music:", level.music);
        }
        headerContainer.style.display = 'none';
        headerContainerHybrid.style.display = 'none';
        // Show the level notification before starting the level
        showLevelNotification(level, () => {
            
            updateUIForCurrentMode();

            // This callback runs after the notification is handled
            if (isBombMode) {
                sessionId = generateSessionId();
                createBombGrid();
                console.log("Created Bomb Grid");
            } else {
                sessionId = generateSessionId();
                createBoard();
                console.log("Created Standard/Classic Grid");
            }
            if (isBombMode) {
        currentGameMode = 'Specijal';
    } else if (isClassicMode) {
        currentGameMode = 'Klasika';
    } else if (isTimeAttackMode) {
        currentGameMode = 'Dokle vise';
    } else {
        currentGameMode = 'Standardica';
    }
            // Update the info panel text color
            updateInfoTextColor();
            // Update the score display
            if (isHybridMode) {
                document.getElementById('score-hybrid').textContent = score;
                console.log("Score Display (Hybrid):", score);
            } else if (isClassicMode) {
                scoreDisplayMoves.textContent = score;
                console.log("Score Display (Moves):", score);
            } else {
                scoreDisplayTimer.textContent = score;
                console.log("Score Display (Timer):", score);
            }
        });
    }, 500); // Animation duration
}
function startBombMode() {
    isBombMode = true;
    isClassicMode = false;
    isTimeAttackMode = false;
    isPracticeMode = false;
    // Prikaži selektor težine za "Bomba" mod
    showDifficultySelection('bomb');
}
const bombModeBtn = document.getElementById('bomb-mode-btn');
bombModeBtn.addEventListener('click', () => {
    selectedDifficulty = null; // Resetujte odabranu težinu
    startBombMode(); // Poziv funkcije za pokretanje Bomba moda
});

function createBombGrid() {
    bns = true;
    clearAllTimeouts();
    clearCardFlipTimeouts();
    if (assistIntervalId) {
        clearInterval(assistIntervalId);
        assistIntervalId = null;
    }

    console.log('createBombGrid called with level:', level);

    // Clear any existing timer interval
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }

    consecutiveWrongMatches = 0;
    level.currentAssistCount = 0;

    // Modovi (timeAttack, classic, hybrid, itd.)
    if (isTimeAttackMode) {
        currentGameMode = 'Dokle vise';
    }
    if (!isTimeAttackMode) {
        isHybridMode = level.solveTime > 0 && level.moves > 0;
        isClassicMode = level.moves > 0 && level.solveTime === 0;
        isTimeMode = level.solveTime > 0 && level.moves === 0;
    }
    if (isHybridMode) {
        document.getElementById('lives-hybrid').textContent = lives;
    } else {
        document.getElementById('lives').textContent = lives;
    }

    // Assist interval
    console.log("level.assistMode:", level.assistMode);
    console.log("level.assistInterval:", level.assistInterval);
    console.log("level.assistCardsCount:", level.assistCardsCount);

    if (
        (level.assistMode === "time" || level.assistMode === "both") &&
        level.assistInterval &&
        level.assistCardsCount > 0
    ) {
        assistIntervalId = setInterval(() => {
            console.log("Assist interval triggered.");
            revealAssistanceCards();
        }, level.assistInterval);
        console.log(`Assist interval set: every ${level.assistInterval} ms`);
    } else {
        console.log("Assist interval not set. Either assistMode does not include time or parameters are not defined.");
    }

    // Setup UI elements based on game mode
    if (isHybridMode) {
        remainingMoves = level.moves + testMode + kupljenipoteziskroz + kupljenipotezi;
        remainingTime = level.solveTime + testMode + kupljenovrijeme + kupljenovrijemeskroz;
        movesHybrid.textContent = remainingMoves;
        timerHybrid.textContent = remainingTime;
        cardsToMatchHybrid.textContent = level.matchCards;

        document.querySelector('.hybrid-container').style.display = 'block';
        document.querySelector('.timer-container').style.display = 'none';
        document.querySelector('.moves-container').style.display = 'none';
    } else if (level.moves && level.moves > 0) {
        isClassicMode = true;
        remainingMoves = level.moves + testMode + kupljenipoteziskroz + kupljenipotezi;

        document.querySelector('.timer-container').style.display = 'none';
        document.querySelector('.moves-container').style.display = 'block';
        document.getElementById('moves').textContent = remainingMoves;
    } else {
        isClassicMode = false;
        remainingTime = level.solveTime + testMode + kupljenovrijeme + kupljenovrijemeskroz;

        document.querySelector('.timer-container').style.display = 'block';
        document.querySelector('.moves-container').style.display = 'none';
        timerDisplay.textContent = remainingTime;
    }

    // Update level and score displays
    if (isHybridMode) {
        scoreDisplayHybrid.textContent = score;
        levelDisplayHybrid.textContent = isPracticeMode ? '-' : currentLevelIndex + 1;
    } else {
        levelDisplay.textContent = isPracticeMode ? '-' : currentLevelIndex + 1;
    }
    if (isClassicMode) {
        scoreDisplayMoves.textContent = score;
        cardsToMatchMoves.textContent = level.matchCards;
    } else {
        scoreDisplayTimer.textContent = score;
        cardsToMatchTimer.textContent = level.matchCards;
    }

    // Reset game board and variables
    gameBoard.innerHTML = '';
    gameBoard.style.display = '';
    gameBoard.style.flexDirection = '';
    gameBoard.style.gridTemplateColumns = '';
    gameBoard.style.gap = '';
    matchedCards = 0;
    isBoardLocked = true;
    selectedCards = [];

    // Background color / image
    document.body.style.backgroundColor = level.backgroundColor;
    if (level.backgroundImage) {
        // Provjerava postoji li .jpg na kraju i uklanja ga prije dodavanja teme
        let baseImage = level.backgroundImage.endsWith('.jpg')
            ? level.backgroundImage.slice(0, -4)
            : level.backgroundImage;

        let themedBackground = `${baseImage}${tema}.jpg`;
        console.log("Pokušava učitati sliku:", themedBackground);
        document.body.style.backgroundImage = `url(${themedBackground})`;
        document.body.style.backgroundSize = 'cover';
        document.body.style.backgroundPosition = 'center center';
    } else {
        console.log("Nema slike za učitavanje, postavljam prazan background.");
        document.body.style.backgroundImage = '';
    }

    // ============================
    // 2) PRIPREMA ZA BOMB GRID
    // ============================
    let totalCards = 0;
    let maxCardsInRow = 0;
    let allCardPositions = [];
    const availableWidth = window.innerWidth;
    const availableHeight = window.innerHeight - 40;

    // Odredit ćemo tip grida (2D array, 1D array, ili cols-rows object)
    if (Array.isArray(level.grid) && Array.isArray(level.grid[0])) {
        // 2D array grid
        const levelType = 'matrix';
        gameBoard.style.display = 'flex';
        gameBoard.style.flexDirection = 'column';
        gameBoard.style.gap = '7px';

        level.grid.forEach(row => {
            maxCardsInRow = Math.max(maxCardsInRow, row.length);
        });
        document.documentElement.style.setProperty('--max-cards-in-row', maxCardsInRow);

        // Poziv calculateMaxHeight
        calculateMaxHeight(level.grid, levelType, availableWidth, availableHeight);

        level.grid.forEach((row, rowIndex) => {
            row.forEach((cell, colIndex) => {
                if (cell === 'k') {
                    allCardPositions.push({ rowIndex, colIndex });
                    totalCards++;
                }
            });
        });

    } else if (Array.isArray(level.grid)) {
        // Array of numbers grid
        const levelType = 'array';
        gameBoard.style.display = 'flex';
        gameBoard.style.flexDirection = 'column';
        gameBoard.style.gap = '7px';

        totalCards = level.grid.reduce((a, b) => a + b, 0);
        maxCardsInRow = Math.max(...level.grid);
        document.documentElement.style.setProperty('--max-cards-in-row', maxCardsInRow);

        calculateMaxHeight(level.grid, levelType, availableWidth, availableHeight);

        level.grid.forEach((numCardsInRow, rowIndex) => {
            for (let colIndex = 0; colIndex < numCardsInRow; colIndex++) {
                allCardPositions.push({ rowIndex, colIndex });
            }
        });

    } else if (typeof level.grid === 'object' && level.grid.cols && level.grid.rows) {
        // Object grid with 'cols' and 'rows'
        const levelType = 'cols-rows';
        gameBoard.style.display = 'grid';
        gameBoard.style.gridTemplateColumns = `repeat(${level.grid.cols}, 1fr)`;
        gameBoard.style.gap = '7px';

        totalCards = level.grid.cols * level.grid.rows;
        calculateMaxHeight(level.grid, levelType, availableWidth, availableHeight);

        for (let rowIndex = 0; rowIndex < level.grid.rows; rowIndex++) {
            for (let colIndex = 0; colIndex < level.grid.cols; colIndex++) {
                allCardPositions.push({ rowIndex, colIndex });
            }
        }
    } else {
        console.error("The level's 'grid' property must be an array or an object with 'cols' and 'rows'.");
        return;
    }

    // =========================
    // 3) PRIPREMA BOMBI & SLIKA
    // =========================
    let bigBombs = level.bigBombs || 0;
    let smallBombs = level.smallBombs || 0;
    let totalBombs = bigBombs + smallBombs;

    // Special cards
    let totalSpecialCards = 0;
    let specialCardTypes = [];
    if (level.specialCards) {
        for (let [type, quantity] of Object.entries(level.specialCards)) {
            totalSpecialCards += quantity;
            for (let i = 0; i < quantity; i++) {
                specialCardTypes.push(type);
            }
        }
    }

    let totalNonMatchingCards = totalBombs + totalSpecialCards;
    totalMatchingCards = totalCards - totalNonMatchingCards;
    globalTotalMatchingCards = totalMatchingCards;

    if (totalMatchingCards % level.matchCards !== 0) {
        console.error("Total matching cards is not divisible by matchCards.");
        return;
    }

    // Izaberemo slike za matching karte
    const numUniqueCards = totalMatchingCards / level.matchCards;
    let mandatoryImage = mandatoryImages[Math.floor(Math.random() * mandatoryImages.length)];

    // Filtriraj currentImages da ukloni sve iz mandatoryImages
    let availableImages = currentImages.filter(img => !mandatoryImages.includes(img));

    // Odaberi ostatak potrebnih slika
    let selectedImages = shuffleArray(availableImages).slice(0, numUniqueCards - 1);

    // Dodaj obaveznu sliku na početak
    selectedImages.unshift(mandatoryImage);

    // Kreiramo niz "cardImages" u kojem je svaka slika ponovljena matchCards puta
    let cardImages = [];
    selectedImages.forEach(image => {
        for (let i = 0; i < level.matchCards; i++) {
            cardImages.push(image);
        }
    });
    cardImages = shuffleArray(cardImages);

    // Shuffle pozicije na boardu
    let shuffledPositions = shuffleArray(allCardPositions);

    // Pripremimo niz za bombe
    let bombPositions = shuffledPositions.splice(0, totalBombs);
    let bombTypes = [];
    for (let i = 0; i < bigBombs; i++) bombTypes.push('bigbomb');
    for (let i = 0; i < smallBombs; i++) bombTypes.push('smallbomb');
    bombTypes = shuffleArray(bombTypes);

    // Pripremimo niz za special cards
    let specialCardPositions = shuffledPositions.splice(0, totalSpecialCards);
    specialCardTypes = shuffleArray(specialCardTypes);

    // Ostatak su matching cards
    let imageIndex = 0;
    let indexForBomb = 0;
    let indexForSpecial = 0;

    // =============
    // 4) KREIRANJE KARTICA
    // =============
    let generatedCards = []; // <== OVDJE ČUVAMO SVE KREIRANE KARTICE

    if (Array.isArray(level.grid) && Array.isArray(level.grid[0])) {
        // 2D array
        level.grid.forEach((row, rowIndex) => {
            let rowDiv = document.createElement('div');
            rowDiv.classList.add('row');
            rowDiv.style.setProperty('--max-cards-in-row', row.length);

            row.forEach((cell, colIndex) => {
                if (cell === 'k') {
                    let cellDiv = document.createElement('div');
                    cellDiv.classList.add('card', 'showing');

                    if (level.cardBackImage) {
                        cellDiv.style.backgroundImage = `url(${level.cardBackImage})`;
                        cellDiv.style.backgroundSize = 'cover';
                        cellDiv.style.backgroundPosition = 'center center';
                    } else {
                        cellDiv.style.backgroundImage = '';
                    }

                    // Da li je bomb, special ili matching card?
                    let bombIndex = bombPositions.findIndex(
                        pos => pos.rowIndex === rowIndex && pos.colIndex === colIndex
                    );
                    if (bombIndex !== -1) {
                        let bombType = bombTypes[indexForBomb++];
                        cellDiv.dataset.type = bombType;
                        cellDiv.dataset.image = `images/special/${bombType}.jpg`;
                        cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="${bombType}">`;
                        cellDiv.addEventListener('click', handleSpecialCardClick);
                    } else {
                        let specialIndex = specialCardPositions.findIndex(
                            pos => pos.rowIndex === rowIndex && pos.colIndex === colIndex
                        );
                        if (specialIndex !== -1) {
                            let specialType = specialCardTypes[indexForSpecial++];
                            cellDiv.dataset.type = specialType;
                            cellDiv.dataset.image = `images/special/${specialType}.jpg`;
                            cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="${specialType}">`;
                            cellDiv.addEventListener('click', handleSpecialCardClick);
                        } else {
                            cellDiv.dataset.type = 'card';
                            cellDiv.dataset.image = cardImages[imageIndex++];
                            cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="Memory Image">`;
                            cellDiv.addEventListener('click', flipCard);
                            if (cellDiv.dataset.image === mandatoryImage) {
                                cellDiv.classList.add('mandatory-card');
                            }
                        }
                    }

                    // Animacija
                    cellDiv.addEventListener('animationend', () => {
                        cellDiv.classList.remove('showing');
                    });
                    cardAppearSound.play();

                    rowDiv.appendChild(cellDiv);
                    generatedCards.push(cellDiv);
                } else if (cell === 'p') {
                    let placeholder = document.createElement('div');
                    placeholder.classList.add('placeholder');
                    rowDiv.appendChild(placeholder);
                }
            });

            gameBoard.appendChild(rowDiv);
        });

    } else if (Array.isArray(level.grid)) {
        // 1D array
        level.grid.forEach((numCardsInRow, rowIndex) => {
            let rowDiv = document.createElement('div');
            rowDiv.classList.add('row');
            rowDiv.style.setProperty('--max-cards-in-row', maxCardsInRow);

            if (level.rowAlignment) {
                rowDiv.classList.add(`align-${level.rowAlignment}`);
            } else {
                rowDiv.classList.add('align-center');
            }

            for (let colIndex = 0; colIndex < numCardsInRow; colIndex++) {
                let cellDiv = document.createElement('div');
                cellDiv.classList.add('card', 'showing');

                if (level.cardBackImage) {
                    cellDiv.style.backgroundImage = `url(${level.cardBackImage})`;
                    cellDiv.style.backgroundSize = 'cover';
                    cellDiv.style.backgroundPosition = 'center center';
                } else {
                    cellDiv.style.backgroundImage = '';
                }

                let bombIndex = bombPositions.findIndex(
                    pos => pos.rowIndex === rowIndex && pos.colIndex === colIndex
                );
                if (bombIndex !== -1) {
                    let bombType = bombTypes[indexForBomb++];
                    cellDiv.dataset.type = bombType;
                    cellDiv.dataset.image = `images/special/${bombType}.jpg`;
                    cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="${bombType}">`;
                    cellDiv.addEventListener('click', handleSpecialCardClick);
                } else {
                    let specialIndex = specialCardPositions.findIndex(
                        pos => pos.rowIndex === rowIndex && pos.colIndex === colIndex
                    );
                    if (specialIndex !== -1) {
                        let specialType = specialCardTypes[indexForSpecial++];
                        cellDiv.dataset.type = specialType;
                        cellDiv.dataset.image = `images/special/${specialType}.jpg`;
                        cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="${specialType}">`;
                        cellDiv.addEventListener('click', handleSpecialCardClick);
                    } else {
                        cellDiv.dataset.type = 'card';
                        cellDiv.dataset.image = cardImages[imageIndex++];
                        cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="Memory Image">`;
                        cellDiv.addEventListener('click', flipCard);
                        if (cellDiv.dataset.image === mandatoryImage) {
                            cellDiv.classList.add('mandatory-card');
                        }
                    }
                }

                cellDiv.addEventListener('animationend', () => {
                    cellDiv.classList.remove('showing');
                });
                cardAppearSound.play();

                rowDiv.appendChild(cellDiv);
                generatedCards.push(cellDiv);
            }
            gameBoard.appendChild(rowDiv);
        });

    } else if (typeof level.grid === 'object' && level.grid.cols && level.grid.rows) {
        // cols-rows
        for (let i = 0; i < totalCards; i++) {
            let rowIndex = Math.floor(i / level.grid.cols);
            let colIndex = i % level.grid.cols;

            let cellDiv = document.createElement('div');
            cellDiv.classList.add('card', 'showing');

            if (level.cardBackImage) {
                cellDiv.style.backgroundImage = `url(${level.cardBackImage})`;
                cellDiv.style.backgroundSize = 'cover';
                cellDiv.style.backgroundPosition = 'center center';
            } else {
                cellDiv.style.backgroundImage = '';
            }

            let bombIndex = bombPositions.findIndex(
                pos => pos.rowIndex === rowIndex && pos.colIndex === colIndex
            );
            if (bombIndex !== -1) {
                let bombType = bombTypes[indexForBomb++];
                cellDiv.dataset.type = bombType;
                cellDiv.dataset.image = `images/special/${bombType}.jpg`;
                cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="${bombType}">`;
                cellDiv.addEventListener('click', handleSpecialCardClick);
            } else {
                let specialIndex = specialCardPositions.findIndex(
                    pos => pos.rowIndex === rowIndex && pos.colIndex === colIndex
                );
                if (specialIndex !== -1) {
                    let specialType = specialCardTypes[indexForSpecial++];
                    cellDiv.dataset.type = specialType;
                    cellDiv.dataset.image = `images/special/${specialType}.jpg`;
                    cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="${specialType}">`;
                    cellDiv.addEventListener('click', handleSpecialCardClick);
                } else {
                    cellDiv.dataset.type = 'card';
                    cellDiv.dataset.image = cardImages[imageIndex++];
                    cellDiv.innerHTML = `<img src="${cellDiv.dataset.image}" alt="Memory Image">`;
                    cellDiv.addEventListener('click', flipCard);
                    if (cellDiv.dataset.image === mandatoryImage) {
                        cellDiv.classList.add('mandatory-card');
                    }
                }
            }

            cellDiv.addEventListener('animationend', () => {
                cellDiv.classList.remove('showing');
            });
            cardAppearSound.play();

            gameBoard.appendChild(cellDiv);
            generatedCards.push(cellDiv);
        }
    } else {
        console.error("The level's 'grid' property must be an array or an object with 'cols' and 'rows'.");
        return;
    }

    // ======================================================
    // 5) DODJELA BOJA KARTICAMA (ISTO KAO createBoard)
    // ======================================================
    // Sada kada smo generirali sve kartice, možemo im dodijeliti boje/gradijente
    // (uključujući bomb i special kartice, ako želite da i one imaju background boju).
    assignColorsToCards({
        cards: generatedCards,
        // matchCards: level.matchCards,  -- NE TREBA NAKON UKLANJANJA randomPairs
        colorScheme: level.colorScheme || 'uniformRandom', 
        gradient: level.gradient || 'vertical'
    });

    // ==================================
    // 6) PREVIEW ILI START TIME
    // ==================================
    // Show cards at the start if needed
    if (level.previewTime > 0) {
    // Pause the timer during preview
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    showCardsAtStart(() => {
        isBoardLocked = false; // Unlock the board after preview
        if (!isClassicMode && !isPaused) {
            startTimer(); // Start the timer after preview if not paused
            if (robot > 0 && igralitajrobot === "jasta_nego_igra"){ console.log("Robot igra: simulatePlayWithAccuracy() pozvan.");
                    simulatePlayWithAccuracy();}
        }
        if (isClassicMode && !isPaused) {
            if (robot > 0 && igralitajrobot === "jasta_nego_igra"){ console.log("Robot igra: simulatePlayWithAccuracy() pozvan.");
                    simulatePlayWithAccuracy();}
        }
    });
} else {
    isBoardLocked = false; // Unlock the board if no preview
    if (!isClassicMode && !isPaused) {
        startTimer(); // Start the timer immediately if not paused
        if (robot > 0 && igralitajrobot === "jasta_nego_igra"){ console.log("Robot igra: simulatePlayWithAccuracy() pozvan.");
        simulatePlayWithAccuracy();}
        
    }
}
}


function isSpecialCard(cardType) {
    const specialCards = [
        'rotateBoard',
        'increaseTime',
        'decreaseTime',
        'increasePoints',
        'decreasePoints',
        'helpCard',
        'freezeCard',
        'shuffleCards',
        'cancelMatched',
        'randomMatch',
        'doublePoints',
        'halfPoints',
        'bonusCard',
        "increaseMoves",
        "decreaseMoves",
        "bwCard",
        'bigbomb',
        'smallbomb',
        'randomCard',
        "life"
    ];
    return specialCards.includes(cardType);
}

function handleSpecialCardClick(event) {
    if (isPaused || isBoardLocked) return;
    const specialCard = event.currentTarget;
    let specialType = specialCard.dataset.type;
    
    if (specialType === 'randomCard') {
        // Definišemo dostupne specijalne kartice prema režimu igre
        let availableSpecialCards = [
            'rotateBoard', 'increaseTime', 'decreaseTime', 'increasePoints',
            'decreasePoints', 'helpCard', 'freezeCard', 'randomMatch',
            'doublePoints', 'halfPoints', 'bonusCard', 'increaseMoves',
            'decreaseMoves', 'bwCard', 'bigbomb', 'smallbomb'
        ];

        // Filtriramo dostupne kartice u zavisnosti od režima igre
        if (isClassicMode) {
            availableSpecialCards = availableSpecialCards.filter(card => !['increaseTime', 'decreaseTime'].includes(card));
        } else if (isTimeAttackMode || isTimeMode) {
            availableSpecialCards = availableSpecialCards.filter(card => !['increaseMoves', 'decreaseMoves'].includes(card));
        }

        // Nasumično biramo specijalnu karticu
        const randomIndex = Math.floor(Math.random() * availableSpecialCards.length);
        specialType = availableSpecialCards[randomIndex];

        // Pretvaramo `randomCard` u izabranu specijalnu karticu
        specialCard.dataset.type = specialType;
        specialCard.classList.add('converted-to-special');
    }

    // Nastavljamo kao da je kliknuta specifična kartica
    if (specialCard.classList.contains('flipped')) return;
    specialCard.classList.add('flipped', 'special-clicked');
    
    // Reprodukcija zvuka specijalne kartice
    specialSound = new Audio(`sounds/${specialType}.mp3`);
    specialSound.play();
    activeSpecialSounds.push(specialSound);

    // Smanjivanje poteza u Classic ili Hybrid modu
    if ((isClassicMode && level.moves > 0) || isHybridMode) {
        remainingMoves--;
        if (isHybridMode) {
            movesHybrid.textContent = remainingMoves;
        } else {
            document.getElementById('moves').textContent = remainingMoves;
        }
        if (remainingMoves <= 0) {
            if (isHybridMode) {
                gameOverHybrid('moves');
            } else {
                gameOverClassic();
            }
            return;
        }
    }

    // Aktiviranje specijalnog efekta i prosleđivanje `event` u funkciju
    triggerSpecialCardEffect(specialType, event);

    // Nakon što efekat bude primenjen, uklanjamo događaj
    specialCard.removeEventListener('click', handleSpecialCardClick);

    // Provera preostalih poteza i vremena
    if ((isClassicMode && remainingMoves <= 0) || (isHybridMode && remainingMoves <= 0)) {
        if (isHybridMode) {
            gameOverHybrid('moves');
        } else {
            gameOverClassic();
        }
    }
    if (isHybridMode && remainingTime <= 0) {
        gameOverHybrid('time');
    }
}
window.k = 0;

function triggerSpecialCardEffect(specialType, event) {
    // Definišemo specialCard iz event objekta
    const specialCard = event.currentTarget;

    switch (specialType) {
        case "life":
        lives +=1;
        lifesound.play();
        addPassiveOverlay();
        showHeartAnimation()
            universalOverlay('white', 100, 1000, 100, 0.48, 1500, "");
            applyCardEffect(' #b2ff00 ', true, "", 500, false, "", 24);
        if (isHybridMode) {
            document.getElementById('lives-hybrid').textContent = lives;
        } else {
            document.getElementById('lives').textContent = lives;
        }
        break;
        case "decreaseMoves":
            showAnimatedTextAtClick(event, "Potezi\nminus!", "white", 2500, 1500); // Poziv sa `event`
            applyCardEffect(' #810101 ', true, "wagfinger", 600, false, "");
            if (remainingMoves >= 3) {
                remainingMoves -= 3;
            } else if (isHybridMode) {
                remainingMoves = 0;
                movesHybrid.textContent = remainingMoves;
                setTimeout(() => resetSeriesOnBomb(), 500);
                gameOverHybrid('moves');
            } else {
                remainingMoves = 0;
                document.getElementById('moves').textContent = remainingMoves;
                setTimeout(() => resetSeriesOnBomb(), 500);
                gameOverClassic();
            }
            if ((isClassicMode && level.moves > 0) || isHybridMode) {
                if (isHybridMode) {
                    movesHybrid.textContent = remainingMoves;
                } else {
                    document.getElementById('moves').textContent = remainingMoves;
                }
            }
            break;

        case "increaseMoves":
            showAnimatedTextAtClick(event, "Potezi\nplus!", "white", 2500, 1501);
            universalOverlay('white', 100, 200, 100, 0.48, 1500, "");
            applyCardEffect('yellow', true, "incmoves", 400, false, "");
            remainingMoves += 5;
            if (isHybridMode) {
                movesHybrid.textContent = remainingMoves;
            } else {
                document.getElementById('moves').textContent = remainingMoves;
            }
            setTimeout(() => resetSeriesOnBomb(), 500);
            break;
        case "bwCard":
            createSparkles(event, "rgb(255, 255, 255)");
            applyGrayscale(14000);
            universalOverlay('rgba(0, 0, 0)', 1500, 11666, 1500, 0.99, -1, 'backgrounds/200w.gif');

            break;
        case "bonusCard":
            clearInterval(timerInterval);
            const clickX = event.clientX;
            const clickY = event.clientY;
            const transformX = (clickX / window.innerWidth) * 100;
            const transformY = (clickY / window.innerHeight) * 100;
            oblici(transformX, transformY);
            setTimeout(() => {
                stopoblici();
                resumeGame();
            }, 17142);
            break;
        case 'rotateBoard':
            flipBoardTemporarily();
            break;
        case 'shuffleCards':
            shuffleUnmatchedCards();
            break;
        case 'cancelMatched':
            cancelAllMatchedCards();
            break;
        case 'randomMatch':
           randomMatchCards();
            break;
        case 'decreaseTime':
        showAnimatedTextAtClick(event, "Vrijeme\nminus!", "white", 2500, 1501);
        applyCardEffect('#000773', false, "", 600, false, "", 15);
        window.k = 1;
            const timePenalty = level.decreaseTimeAmount || 10;
            remainingTime -= timePenalty;
            if (remainingTime <= 0) {
                remainingTime = 0;
                timerHybrid.textContent = remainingTime;
                if (isHybridMode && !levelCompleted) {
                    gameOverHybrid('time');
                } else {
                    if (!levelCompleted) {
        timeUp();
    }
                }
                return;
            }
            timerHybrid.textContent = remainingTime;
           gameBoard.classList.add('wagfinger2');
            setTimeout(() => {
                gameBoard.classList.remove('wagfinger2');
            }, 500);
            resetSeriesOnBomb();
            break;
        case 'increaseTime':
        showAnimatedTextAtClick(event, "Vrijeme\nplus!", "white", 2500, 1501);
            universalOverlay('#00e8ff', 100, 200, 100, 0.5, 1500);
            applyCardEffect('#00e8ff', "", 400, false, "");
            const timeBonus = level.increaseTimeAmount || 10;
            remainingTime += timeBonus;
            timerHybrid.textContent = remainingTime;
            gameBoard.classList.add('happy-jump');
            setTimeout(() => {
                gameBoard.classList.remove('happy-jump');
            }, 500);
            resetSeriesOnBomb();
            break;
        case 'decreasePoints':
        showAnimatedTextAtClick(event, "Poeni\nminus!", "white", 2500, 1501);
            universalOverlay('black', 50, 200, 50, 0.63, 1500, "");
            applyCardEffect('black', true, "wagFinger", 400, false, "");
            const pointsPenalty = level.decreasePointsAmount || 121;
            score -= Math.round(pointsPenalty * pointsModifier);
            updateScoreDisplay(score, 'decrease');
            document.body.classList.add('sad-dip');
            setTimeout(() => {
                document.body.classList.remove('sad-dip');
            }, 500);
            resetSeriesOnBomb();
            break;
        case 'increasePoints':
        showAnimatedTextAtClick(event, "Poeni\nplus!", "white", 2500, 1501);
            universalOverlay('yellow', 100, 200, 100, 0.48, 1500);
            applyCardEffect('yellow', true, "negative-rotate-left", 400, false, "");
            const pointsBonus = level.increasePointsAmount || 121;
            score += Math.round(pointsBonus * pointsModifier);
            zivotna_provjera();
            updateScoreDisplay(score, 'increase');
            document.body.classList.add('happy-jump');

            setTimeout(() => {
                document.body.classList.remove('happy-jump');
            }, 500);
            resetSeriesOnBomb();
            break;
        case 'helpCard':
            consecutiveMatches = 0;
            streakCards = [];
            selectedCards.forEach(card => {
                card.classList.remove('selected', 'flipped');
                if (card.flipBackTimeout) {
                    clearTimeout(card.flipBackTimeout);
                    card.flipBackTimeout = null;
                }
            });
            const helpRevealTime = level.helpRevealTime || 2000;
            selectedCards = [];
            revealAllCards();
            if (helpRevealTimeout) clearTimeout(helpRevealTimeout);
            helpRevealTimeout = setTimeout(hideAllCards, helpRevealTime);
            break;
        case 'freezeCard':
            consecutiveMatches = 0;
            streakCards = [];
            selectedCards.forEach(card => card.classList.remove('selected', 'flipped'));
            selectedCards = [];
            const freezeDuration = level.freezeDuration || 3000;
            isBoardLocked = true;
            gameBoard.classList.add('frozen');
            const flashOverlay = document.createElement('div');
            flashOverlay.classList.add('freeze-overlay');
            document.body.appendChild(flashOverlay);
            setTimeout(() => {
                flashOverlay.remove();
            }, freezeDuration);
            const allCards = document.querySelectorAll('.card');
            allCards.forEach(card => card.classList.add('frozen-effect'));
            resetSeriesOnBomb();
            setTimeout(() => {
                isBoardLocked = false;
                gameBoard.classList.remove('frozen');
                allCards.forEach(card => card.classList.remove('frozen-effect'));
            }, freezeDuration);
            resetSeriesOnBomb();
            break;
        case 'doublePoints':
        showAnimatedTextAtClick(event, "Dupli\npoeni!", "white", 2500, 1501);
            createSparkles(event, "rgb(0, 255, 153)");
            activateDoublePoints();
            break;
        case 'halfPoints':
        showAnimatedTextAtClick(event, "Polovični\npoeni!", "white", 2500, 1501);
            createSparkles(event, "rgba(255, 0, 0, 0.99)");
            activateHalfPoints();
            break;
        case 'bigbomb':
        case 'smallbomb':
            // Integrisana logika za bombe
            const bombType = specialType.toLowerCase();
            console.log(`Bomb activated. Type: ${bombType}`);

            // Dodavanje animacije i klasifikacije
            specialCard.classList.add('bomb-clicked');

            // Reprodukcija zvuka bombe
            const bombSound = new Audio(`sounds/${bombType}.mp3`);
            bombSound.play();

            // Triggerovanje efekta treperenja ekrana
            triggerScreenShake();

            // Smanjivanje poteza u Classic ili Hybrid modu
            if ((isClassicMode && level.moves > 0) || isHybridMode) {
                remainingMoves--;
                if (isHybridMode) {
                    movesHybrid.textContent = remainingMoves;
                } else {
                    document.getElementById('moves').textContent = remainingMoves;
                }
                if (remainingMoves <= 0) {
                    if (isHybridMode) {
                        gameOverHybrid('moves');
                    } else {
                        gameOverClassic();
                    }
                    return;
                }
            }

            // Određivanje broja kartica koje će bomba uticati
            let numCardsToAffect = bombType === 'bigbomb' ? 5 : 3;
            const availableCardsForBomb = Array.from(document.querySelectorAll('.card'))
                .filter(card =>
                    !card.classList.contains('flipped') &&
                    !card.classList.contains('matched') &&
                    card !== specialCard
                );
            if (availableCardsForBomb.length < numCardsToAffect) {
                numCardsToAffect = availableCardsForBomb.length;
            }
            const cardsToAffectBomb = shuffleArray(availableCardsForBomb).slice(0, numCardsToAffect);
            cardsToAffectBomb.forEach(card => {
                card.classList.add('darkened');
                card.style.pointerEvents = 'none';
            });

            // Postavljanje trajanja efekta bombe
            const effectDurationBomb = level.bombEffectDuration || 2400;
            setTimeout(() => {
                cardsToAffectBomb.forEach(card => {
                    
                    card.classList.remove('darkened');
                    card.classList.add('showing');
                    card.style.pointerEvents = '';
                });
            }, effectDurationBomb);

            // Smanjenje broja poena i resetovanje serije
            const penaltyPointsBomb = level.bombPenaltyPoints || 0;
            score -= penaltyPointsBomb;
            updateScoreDisplay(score, 'decrease');
            resetSeriesOnBomb();
            break;
        default:
            console.warn('Unknown special card type:', specialType);
    }
}
// Function to activate Double Points
function activateDoublePoints() {
    if (pointsModifier !== 1) return; // Sprečava naknadno slaganje efekata

    // Selektuje sve kartice
    const cards = document.querySelectorAll('.card');
    cards.forEach(card => card.classList.add('double-points-active'));
    const gameBoard = document.getElementById('game-board');
    gameBoard.classList.add('active-effect2');
    pointsModifier = 2; // Dupliranje bodova

    const duration = level.doublePointsDuration || 10000; // Trajanje efekta u ms

    setTimeout(() => {
        pointsModifier = 1; // Vraćanje bodova na normalu
        const gameBoard = document.getElementById('game-board');
        gameBoard.classList.remove('active-effect2');
        // Uklanja aktivni efekat sa svih kartica
        cards.forEach(card => {
            card.classList.remove('double-points-active');
            //card.classList.add('remove-glow'); // Dodaje klasu za glatko uklanjanje obruba
        });

        // Nakon završetka tranzicije, uklanja klasu remove-glow
        setTimeout(() => {
           // cards.forEach(card => card.classList.remove('remove-glow'));
        }, 1000); // Usklađeno sa trajanjem animacije borderColorRevert u CSS-u (1s)

    }, duration);
}

function activateHalfPoints() {
    if (pointsModifier !== 1) return; // Prevent stacking
    const cards = document.querySelectorAll('.card');
    cards.forEach(card => card.classList.add('double-points-active-2'));
   const gameBoard = document.getElementById('game-board');
    gameBoard.classList.add('halfpoints');
    pointsModifier = 0.5; // Half points
    const duration = level.halfPointsDuration || 10000; // Duration in ms

    setTimeout(() => {
        pointsModifier = 1; // Revert to normal
       const gameBoard = document.getElementById('game-board');
        gameBoard.classList.remove('halfpoints');

        const cards = document.querySelectorAll('.card');
        cards.forEach(card => {
            card.classList.remove('double-points-active-2'); // Remove red glow
            card.classList.add('remove-glow'); // Add transition for smooth shadow removal
        });

        // After the transition finishes, remove the remove-glow class
        setTimeout(() => {
            cards.forEach(card => card.classList.remove('remove-glow'));
        }, 1000); // Match the transition duration (0.5s in CSS)

    }, duration);
}


function flipBoardTemporarily() {
    const gameBoard = document.getElementById('game-board');
    if (!gameBoard) {
        console.error('Element with ID "game-board" not found!');
        return;
    }
    // Add class 'rotated' to rotate the board
    gameBoard.classList.add('rotated');
    // After the duration, remove the 'rotated' class to rotate back
    setTimeout(() => {
        gameBoard.classList.remove('rotated');
    }, level.rotateduration || 5000); // Use a default duration if level.rotateduration is not set
}
function shuffleUnmatchedCards() {
    // Pronađi sve neotkrivene i nenaučene kartice koje nisu specijalne ili uparene
    const availableCards = Array.from(document.querySelectorAll('.card'))
        .filter(card => 
            !card.classList.contains('flipped') &&
            !card.classList.contains('matched') &&
            !isSpecialCard(card.dataset.type)
        );
    if (availableCards.length === 0) {
        console.log('Nema kartica za mešanje.');
        return;
    }
    // Pauziraj vreme igre
    pauseTimer();
    // Otvori sve dostupne kartice uz flip animaciju
    availableCards.forEach(card => {
        card.classList.add('flipped');
    });
    // Kratka pauza da igrač vidi kartice pre mešanja
    setTimeout(() => {
        // Sakrij kartice uz flip animaciju
        availableCards.forEach(card => {
            card.classList.remove('flipped');
        });
        // Izmiješaj kartice u DOM-u
        const cardElements = availableCards.map(card => card.cloneNode(true));
        // Ukloni originalne kartice iz DOM-a
        availableCards.forEach(card => {
            card.parentElement.removeChild(card);
        });
        // Izmiješaj kopirane kartice
        const shuffledCards = shuffleArray(cardElements);
        // Dodaj izmešane kartice nazad na tablu
        shuffledCards.forEach(card => {
            gameBoard.appendChild(card);
            // Ponovno dodaj event listener
            card.addEventListener('click', flipCard);
        });
        // Prikaži kartice ponovo uz flip animaciju
        shuffledCards.forEach(card => {
            card.classList.add('flipped');
        });
        // Oduzmi bodove ili dodaj odgovarajući efekat
        const shufflePenalty = level.shufflePenaltyPoints || 20;
        score -= shufflePenalty;
        updateScoreDisplay(score, 'decrease');
        console.log(`Shuffle penalty: -${shufflePenalty} bodova. Novi skor: ${score}`);
        // Prikaži kartice za vreme definisano u level.previewTime
        setTimeout(() => {
            shuffledCards.forEach(card => {
                // Sakrij kartice osim onih koje su uparene ili specijalne
                if (!card.classList.contains('matched') && !isSpecialCard(card.dataset.type)) {
                    card.classList.remove('flipped');
                }
            });
            // Ponovo pokreni vreme igre
            resumeTimer();
        }, level.previewTime || 2000); // Vreme koje kartice ostaju otkrivene
    }, 1000); // Vreme za otkrivanje kartica pre mešanja
}
function pauseTimer() {
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
        console.log('Timer paused.');
    }
}
function resumeTimer() {
    console.log('resumeTimer called');
    
    if (!timerInterval) {
        console.log('No active timerInterval found, starting new interval.');

        if (isHybridMode) {
            console.log('Hybrid mode detected. Starting hybrid timer.');
            timerInterval = setInterval(() => {
                remainingTime--;
                console.log(`Hybrid Mode - Remaining Time: ${remainingTime}`);
                timerHybrid.textContent = remainingTime;
                if (remainingTime <= 5 && remainingTime > 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }
                
                if (remainingTime === 0) {
                    console.log('Hybrid mode timer reached zero, triggering gameOverHybrid.');
                    gameOverHybrid('time');
                }
            }, 1000);

        } else if (isTimeAttackMode) {
            console.log('Time Attack mode detected. Starting Time Attack timer.');
            // Existing Time Attack logic
            // Add similar logging within Time Attack logic as needed

        } else {
            console.log('Standard mode detected. Starting standard timer.');
            timerInterval = setInterval(() => {
                remainingTime--;
                console.log(`Standard Mode - Remaining Time: ${remainingTime}`);
                timerDisplay.textContent = remainingTime;
                if (remainingTime <= 5 && remainingTime > 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }

                if (remainingTime === 0 && !levelCompleted) {
                    console.log('Standard timer reached zero, triggering timeUp.');
                    timeUp();
                }
            }, 1000);
        }

        console.log('Timer resumed.');
    } else {
        console.log('Timer is already running. No action taken.');
    }
}


function cancelAllMatchedCards() {
    let gameBoardElement = document.getElementById('game-board');
    gameBoardElement.classList.add('rotate-center');
    // Remove shake effect after animation
    setTimeout(() => {
        gameBoardElement.classList.remove('rotate-center');
    }, 800); // Duration should match CSS animation duration
    consecutiveMatches = 0;
    consecutiveWrongMatches = 0;
matchedCards = 0;
    selectedCards = [];
    const matchedCards = Array.from(document.querySelectorAll('.card.matched'))
        .filter(card => !isSpecialCard(card.dataset.type));
    if (matchedCards.length === 0) {
        console.log('Nema uparenih kartica za poništavanje.');
        return;
    }
    matchedCards.forEach(card => {
        card.classList.remove('matched');
        card.classList.remove('flipped');
        card.style.pointerEvents = ''; // Omogući ponovni klik
    });
    // Reorganizacija skora ili dodavanje odgovarajućeg efekta
    const cancelPenalty = level.cancelPenaltyPoints || 30;
    score -= cancelPenalty;
    updateScoreDisplay(score, 'decrease');
    console.log(`Cancel matched penalty: -${cancelPenalty} bodova. Novi skor: ${score}`);
}
function randomMatchCards() {

    isBoardLocked = true; // Zaključava tablu tokom automatskog uparivanja
   // rmc = true;
    // Resetovanje prethodno selektovanih kartica ako postoje
    if (selectedCards.length > 0) {
        selectedCards.forEach(card => {
            // Ako kartica nije uparen, sakrij je
            if (!card.classList.contains('matched')) {
                card.classList.remove('flipped', 'selected'); // Sakrij karticu
            }
        });
        selectedCards = []; // Resetuj niz
    }
    const matchCount = level.matchCards || 2; // Broj kartica za uparivanje (2 ili 3)
    // Pronađi sve neotkrivene, nenaučene, i ne-specijalne kartice
    const availableCards = Array.from(document.querySelectorAll('.card'))
        .filter(card => 
            
            !card.classList.contains('matched') &&
            !isSpecialCard(card.dataset.type)
        );
    if (availableCards.length < matchCount) {
        console.log('Nema dovoljno kartica za nasumično uparivanje.');
        isBoardLocked = false; // Otključava tablu ako nema dovoljno kartica
        return;
    }
    // Grupisanje kartica po slici
    const cardGroups = availableCards.reduce((groups, card) => {
        const image = card.dataset.image;
        if (!groups[image]) {
            groups[image] = [];
        }
        groups[image].push(card);
        return groups;
    }, {});
    // Filtriranje grupa koje imaju dovoljno kartica za uparivanje
    const validGroups = Object.values(cardGroups).filter(group => group.length >= matchCount);
    if (validGroups.length === 0) {
        console.log('Nema grupa kartica sa dovoljnim brojem za uparivanje.');
        isBoardLocked = false; // Otključava tablu ako nema validnih grupa
        return;
    }
    // Odabir nasumične grupe
    const selectedGroup = shuffleArray(validGroups)[0];
    const matchedCardsGroup = selectedGroup.slice(0, matchCount);
    // Funkcija za animirano otkrivanje kartica jednu po jednu
    matchedCardsGroup.forEach((card, index) => {
        setTimeout(() => {
            card.classList.add('flipped', 'selected'); // Otvori karticu i označi je kao selektovanu
            selectedCards.push(card);
            // Reprodukcija flip zvuka (opciono)
            if (flipSound) flipSound.play();
            // Kada su sve kartice otkrivene, pozovi checkMatch
            if (index === matchedCardsGroup.length - 1) {
                setTimeout(() => {
                    checkMatch(); // Obrada uparivanja
                }, 500); // Kratko kašnjenje pre provere uparivanja
            }
        }, index * 300); // Vreme između otkrivanja kartica (npr., 300ms)
    });
    console.log('Random Match Selected Cards:', matchedCardsGroup);
}
let robotPlaying = false;  
function getAvailableCards() {
  return Array.from(document.querySelectorAll('.card')).filter(card =>
    // Već uparene -> preskačemo
    !card.classList.contains('matched') &&
    // (opciono) ako ne želite da robot *ikad* klikne specijalne:
    !isSpecialCard(card.dataset.type)
  );
}

/******************************************************/
/* 2) pickCorrectGroup - bira validnu (pravu) grupu   */
/******************************************************/
function pickCorrectGroup(availableCards, matchCount) {
  // Izbaci specijalne + frozen + darkened
  let normalCards = availableCards.filter(card =>
    !isSpecialCard(card.dataset.type) &&
    !card.classList.contains('matched') &&
    !isSpecialCard(card.dataset.type)
  );

  // Grupisanje po slici
  const groups = normalCards.reduce((acc, card) => {
    const img = card.dataset.image;
    if (!acc[img]) acc[img] = [];
    acc[img].push(card);
    return acc;
  }, {});

  // validne grupe = one koje imaju bar matchCount kartica
  let validGroups = Object.values(groups).filter(g => g.length >= matchCount);
  if (validGroups.length === 0) {
    return null; // Nema ispravne grupe
  }

  shuffleArray(validGroups);
  return validGroups[0].slice(0, matchCount);
}


/********************************************************************/
/* 3) pickRandomWrongGroup - bira kartice koje *nisu* sve iste       */
/*    i sprečava beskrajnu petlju ako ne postoji pogrešna kombinacija*/
/********************************************************************/
function pickRandomWrongGroup(availableCards, matchCount) {
  // Izbaci specijalne kartice i već uparene kartice
  let normalCards = availableCards.filter(card =>
    !isSpecialCard(card.dataset.type) &&
    !card.classList.contains('matched')
  );

  console.log('Normalne kartice:', normalCards.map(c => c.dataset.image));

  // Pronađi različite slike
  const distinctImages = [...new Set(normalCards.map(c => c.dataset.image))];
  console.log('Različite slike:', distinctImages);

  // Ako nema dovoljno različitih slika, nije moguće napraviti pogrešnu grupu
  if (distinctImages.length < 2) {
    console.log('Nedovoljno različitih slika za pogrešnu kombinaciju.');
    return null;
  }

  // Praćenje već pokušanih kombinacija (globalni Set)
  if (!window.triedWrongCombos) {
    window.triedWrongCombos = new Set();
  }

  // Nasumično biranje kartica
  let candidate = [];
  let comboKey = '';
  let safetyCounter = 0;

  do {
    // Pomiješaj kartice nasumično
    shuffleArray(normalCards);

    // Uzmi prvih `matchCount` kartica
    candidate = normalCards.slice(0, matchCount);

    // Kreiraj ključ za kombinaciju (sortirane slike)
    comboKey = candidate.map(c => c.dataset.image).sort().join(',');

    console.log(`Kandidat: ${candidate.map(c => c.dataset.image)} | ComboKey: ${comboKey}`);

    safetyCounter++;

    // Ako se iscrpe pokušaji, resetuj probane kombinacije
    if (safetyCounter > 50) {
      console.log('Resetovanje niza loših izbora jer nije moguće pronaći novu kombinaciju.');
      window.triedWrongCombos.clear(); // Resetovanje probanih kombinacija
      safetyCounter = 0; // Ponovo pokrećemo pokušaje
    }
  } while (
    new Set(candidate.map(c => c.dataset.image)).size === 1 || // Sve kartice imaju istu sliku
    window.triedWrongCombos.has(comboKey) // Kombinacija je već isprobana
  );

  // Dodaj novu kombinaciju u praćene kombinacije
  window.triedWrongCombos.add(comboKey);

  console.log('Odabrana pogrešna kombinacija:', candidate.map(c => c.dataset.image));
  return candidate;
}

/********************************************************************/
/* 4) simulatePlayWithAccuracy - glavni tok "robotskog" igranja     */
/********************************************************************/
let r = level.flipBackTime;
function simulatePlayWithAccuracy(robotMoveDuration = 2000, cardFlipDelay = 500) { // robotMoveDuration u ms
  if (robotPlaying) {
    console.warn("Robot već igra, ne može se pokrenuti dvaput.");
    return;
  }

  robot--; // Smanji brojač robota

  const totalCards = getAvailableCards().length;
  const correctMoves = totalCards / level.matchCards; // Tačni potezi potrebni za završetak

  const hasTimeLimit = level.solveTime > 0;
  const hasMoveLimit = level.moves > 0;

  const fixedDelayBetweenMoves = 1350; // Fiksno kašnjenje između poteza u ms

  // Prilagođeno vrijeme za svaki potez u zavisnosti od matchCards
  // Vrijeme za otvaranje svih kartica plus fiksno kašnjenje
  const timePerMove = (cardFlipDelay * level.matchCards) + fixedDelayBetweenMoves;

  let maxMoves;
  if (hasTimeLimit && hasMoveLimit) {
    maxMoves = Math.min(level.moves, Math.floor((level.solveTime * 1000) / timePerMove));
    console.log("Kombinovano ograničenje. Max poteza:", maxMoves);
  } else if (hasTimeLimit) {
    maxMoves = Math.floor((((level.solveTime * 1000))+500) / timePerMove);
    console.log("Vremensko ograničenje. Max poteza:", maxMoves);
  } else if (hasMoveLimit) {
    maxMoves = level.moves;
    console.log("Ograničenje poteza. Max poteza:", maxMoves);
  } else {
    console.error("Nema definisanih ograničenja za nivo.");
    return;
  }

  // Provjera da li je maxMoves dovoljno velik
  if (maxMoves < correctMoves) {
    console.warn(`Max poteza (${maxMoves}) je manje od potrebnih tačnih poteza (${correctMoves}). Igra možda neće biti završena uspešno.`);
  }

  // Računanje poteza i grešaka na osnovu šanse
  let spareMoves = maxMoves - correctMoves;
  if (spareMoves < 2) { // Potrebno je rezervisati 2 tačna poteza
    spareMoves = 0;
  }

  // Povećana šansa za greške na 95-100%
  let mistakesToPlay = 0;
  if (spareMoves > 0) {
    const randomPercentage = 0.63 + Math.random() * 0.37; // 0.95 to 1.0
    mistakesToPlay = Math.round(spareMoves * randomPercentage);
    mistakesToPlay = Math.min(mistakesToPlay, spareMoves); // Osiguraj da ne prelazi spareMoves
  }

  console.log(`Robot ima ${spareMoves} viška poteza, od čega planira odigrati ${mistakesToPlay} grešaka.`);

  // Rezervacija poslednja dva poteza kao tačna
  const reservedTrueMoves = 2;
  let trueMoves = correctMoves - reservedTrueMoves;

  // Ako nema dovoljno tačnih poteza da rezervišemo poslednja dva, prilagodi
  if (trueMoves < 0) {
    console.warn(`Broj tačnih poteza (${correctMoves}) je manji od rezervisanih tačnih poteza (${reservedTrueMoves}). Prilagođavam broj tačnih poteza.`);
    trueMoves = 0;
    // Možda ćete želeti da prilagodite broj grešaka ovde, ali korisnik želi samo 95-100%
  }

  // Ukupan planirani broj poteza mora biti jednak maxMoves
  let totalPlannedMoves = trueMoves + mistakesToPlay + reservedTrueMoves;

  // Provera da ukupno planirani potezi ne premašuju maxMoves
  if (totalPlannedMoves > maxMoves) {
    const excess = totalPlannedMoves - maxMoves;
    console.warn(`Ukupan broj poteza (${totalPlannedMoves}) premašuje maxMoves (${maxMoves}). Smanjujem broj grešaka za ${excess}.`);
    mistakesToPlay = Math.max(mistakesToPlay - excess, 0);
    totalPlannedMoves = trueMoves + mistakesToPlay + reservedTrueMoves;
  }

  console.log(`Finalno planirani tačni potezi: ${trueMoves}, greške: ${mistakesToPlay}`);

  // Kreiranje sekvence poteza za prvi deo (maxMoves -2)
  let firstPartMoves = [];

  // Dodaj tačne poteze (osim rezervisanih poslednja dva)
  for (let i = 0; i < trueMoves; i++) {
    firstPartMoves.push(true);
  }

  // Dodaj pogrešne poteze
  for (let i = 0; i < mistakesToPlay; i++) {
    firstPartMoves.push(false);
  }

  // Mešanje poteza
  shuffleArray(firstPartMoves);

  // Osiguraj da false potezi nisu uzastopni gde god je moguće
  for (let i = 1; i < firstPartMoves.length; i++) {
    if (!firstPartMoves[i - 1] && !firstPartMoves[i]) {
      // Pronađi sledeći true potez i zameni
      let j = i + 1;
      while (j < firstPartMoves.length && !firstPartMoves[j]) {
        j++;
      }
      if (j < firstPartMoves.length) {
        [firstPartMoves[i], firstPartMoves[j]] = [firstPartMoves[j], firstPartMoves[i]];
      }
    }
  }

  // Dodaj rezervisana tačna poteza na kraj
  const finalMovesSequence = firstPartMoves.concat([true, true]);

  // Provera da je finalMovesSequence.length tačno maxMoves
  if (finalMovesSequence.length > maxMoves) {
    console.warn(`Finalni niz poteza (${finalMovesSequence.length}) premašuje maxMoves (${maxMoves}). Skraćujem niz.`);
    finalMovesSequence.length = maxMoves;
    // Osiguraj da poslednja dva poteza budu tačna
    if (finalMovesSequence.length >= 2) {
      finalMovesSequence[maxMoves - 2] = true;
      finalMovesSequence[maxMoves - 1] = true;
    }
  } else if (finalMovesSequence.length < maxMoves) {
    console.warn(`Finalni niz poteza (${finalMovesSequence.length}) je manji od maxMoves (${maxMoves}). Dodajem dodatne tačne poteze.`);
    while (finalMovesSequence.length < maxMoves - 2) { // Oduzmi 2 za rezervisana poteza
      finalMovesSequence.push(true);
    }
    finalMovesSequence.push(true, true);
  }

  console.log("Finalna sekvenca poteza:", finalMovesSequence);
  console.log(`Ukupan broj poteza: ${finalMovesSequence.length}, Max Moves: ${maxMoves}`);

  robotPlaying = true;
  isBoardLocked = true;

  let currentMoveIndex = 0;

  function playOneRound() {
    if (!robotPlaying) {
      stopRobotPlay();
      return;
    }

    if (currentMoveIndex >= finalMovesSequence.length) {
      console.log("Robot: Završio sve poteze.");
      stopRobotPlay();
      return;
    }

    const availableCards = getAvailableCards();
    if (availableCards.length < level.matchCards) {
      console.log("Robot: Nema dovoljno dostupnih kartica za potez.");
      stopRobotPlay();
      return;
    }

    const isMatchSuccessful = finalMovesSequence[currentMoveIndex];
    currentMoveIndex++;

    let chosenCards;
    if (isMatchSuccessful) {
      chosenCards = pickCorrectGroup(availableCards, level.matchCards);
    } else {
      chosenCards = pickRandomWrongGroup(availableCards, level.matchCards);
    }

    if (!chosenCards) {
      console.warn("Robot: Nema validnih kombinacija. Stajem.");
      stopRobotPlay();
      return;
    }

    console.log(isMatchSuccessful ? "Robot pravi tačan izbor." : "Robot pokušava pogrešnu kombinaciju.");

    let index = 0;

    function flipNextCard() {
      if (!robotPlaying) {
        console.warn("Robot više ne igra. Zaustavljam otkrivanje kartica.");
        stopRobotPlay();
        return;
      }

      if (index < chosenCards.length) {
        console.log(`Otkrivam karticu ${index + 1} od ${chosenCards.length}`);
        const card = chosenCards[index];
        card.classList.add("flipped");

        if (flipSound) flipSound.play();

        selectedCards.push(card); // Dodaj karticu u listu odabranih
        index++;

        setTimeout(flipNextCard, cardFlipDelay); // Nastavi sa sledećom karticom
      } else {
        console.log("Provera meča za odabrane kartice.");
        checkMatch(); // Proveri meč kada su sve kartice okrenute

        if (robotPlaying && matchedCards < totalMatchingCards) {
          setTimeout(playOneRound, fixedDelayBetweenMoves); // Koristi fiksno kašnjenje između poteza u ms
        } else {
          stopRobotPlay();
        }
      }
    }

    flipNextCard();
  }

  playOneRound();
}



function stopRobotPlay() {
  if (robotPlaying) {
    console.log("Zaustavljamo robotsku igru...");
    robotPlaying = false;
    isBoardLocked = false;
  }
}



function flipCardAutomated(card) {
    // Simuliraj otkrivanje kartice
    card.classList.add('flipped');
   // card.classList.add('selected'); // Obeleži karticu kao izabranu
    selectedCards.push(card);

    // Resetiraj flipBackTimeout ako postoji
    if (card.flipBackTimeout) {
        clearTimeout(card.flipBackTimeout);
    }
    // Postavi timeout za automatsko sakrivanje ako ne postane matched
    card.flipBackTimeout = setTimeout(() => {
        if (!card.classList.contains('matched')) {
            card.classList.remove('flipped'); // Sakrij karticu
            // 'selected' klasa ostaje
        }
    }, level.flipBackTime || 1000);
}
function revealAllCards() {
    const cards = document.querySelectorAll('.card:not(.matched)');
    cards.forEach(card => {
            card.classList.add('flipped');
    });
}
function hideAllCards() {
    const cards = document.querySelectorAll('.card:not(.matched)');
    cards.forEach(card => {
        if (card.classList.contains('flipped') && !card.classList.contains('special-clicked') && !card.classList.contains('bomb-clicked')) {
            card.classList.remove('flipped');
        }
    });
}
function resetSeriesOnBomb() {
    // Reset consecutive match counters
    consecutiveMatches = 0;
    streakCards = [];
    // Deselect and flip back any selected cards
    selectedCards.forEach(card => {
        card.classList.remove('selected', 'flipped');
    });
selectedCards =[];
    // Play mismatch sound
    //mismatchSound.play();
}
function triggerScreenShake() {
    const gameContainer = document.getElementById('game-container');
    gameContainer.classList.add('shake');
    setTimeout(() => {
        gameContainer.classList.remove('shake');
    }, 1000); // Duration of the shake
    const flashOverlay = document.createElement('div');
    flashOverlay.classList.add('bomb-flash-overlay');
    document.body.appendChild(flashOverlay);
    // Uklanjanje overlay-a nakon 300ms
    setTimeout(() => {
        flashOverlay.remove();
    }, 300);
}
function triggerScreenShakestreak() {

    const gameContainer = document.getElementById('game-container');
    setTimeout(() => {
        gameContainer.classList.add('shakestreak');
    }, 0); 

    setTimeout(() => {
        gameContainer.classList.remove('shakestreak');
    }, 400); // Duration of the shake
}
</script>
<script>
    document.addEventListener('dblclick', function(event) {
        event.preventDefault(); // nece mene dupli klik jebavat
    });
    </script>
<script>
 // Funkcija za dodavanje pasivnog overlay-a
 function addPassiveOverlay() {
    const existingOverlay = document.querySelector('.passive-overlay');
    if (!existingOverlay) { // Dodaj samo ako ne postoji
        const overlay = document.createElement('div');
        overlay.classList.add('passive-overlay');
        document.body.appendChild(overlay);
    }
}
// Funkcija za uklanjanje pasivnog overlay-a
function removePassiveOverlay() {
    const overlay = document.querySelector('.passive-overlay');
    if (overlay) {
        overlay.remove();
    }
}
</script>
    <script>
// Selektovanje elemenata
const playerInfoDiv = document.querySelector(".player-info");
const scoreDisplayTimer = document.getElementById('score-timer');
const scoreDisplayMoves = document.getElementById('score-moves');
const cardsToMatchTimer = document.getElementById('cards-to-match-timer');
const cardsToMatchMoves = document.getElementById('cards-to-match-moves');
const gameOverTUSound = document.getElementById('game-over-TU-sound');
const gameOverSound = document.getElementById('game-over-sound');
const gameBoard = document.getElementById('game-board');
const logo = document.getElementById('logo');
const infoPanel = document.querySelector('.info');
const scoreDisplay = document.getElementById('score');
const timeUpMsg = document.getElementById('time-up-msg');
const finalScoreTimeUp = document.getElementById('final-score-time-up');
const endSound = document.getElementById('end-sound');
const restartButton = document.getElementById('restart-btn');
const matchSound = document.getElementById('match-sound');
const mismatchSound = document.getElementById('mismatch-sound');
const levelUpSound = document.getElementById('level-up-sound');
const revealSound = document.getElementById('reveal-sound');
const nomovesSound = document.getElementById('nomoves');
const pauseSound = document.getElementById('pause');
const cardAppearSound = document.getElementById('card-appear-sound');
const cardHideSound = document.getElementById('card-hide-sound');
const flipSound = document.getElementById('flip-sound');
const flipSound2 = document.getElementById('flip-sound2');
// Novi elementi za poruke
const levelCompleteMsg = document.getElementById('level-up-msg');
const gameCompletedMsg = document.getElementById('game-completed-msg');
const finalScoreDisplay = document.getElementById('final-score-overlay'); // U 'level-up-msg'
const finalScoreGameOver = document.getElementById('final-score-game-over'); // U 'game-completed-msg'
const nextLevelBtnOverlay = document.getElementById('next-level-btn-overlay');
const restartGameBtnOverlay = document.getElementById('restart-game-btn-overlay');
// Novi elementi za Vježbu
const practiceSettings = document.getElementById('practice-settings');
const startPracticeBtn = document.getElementById('start-practice-btn');
const cancelPracticeBtn = document.getElementById('cancel-practice-btn');
// Dodatni elementi
const applauseSound = document.getElementById('applause-sound');
const headerContainer = document.getElementById('header-container');
//const logoSmall = document.getElementById('logo-small');
const levelDisplay = document.getElementById('level');
const levelNameDisplay = document.getElementById('level-name');
const timerDisplay = document.getElementById('timer');
// Novi elementi za pauzu
const pauseOverlay = document.getElementById('pause-overlay');
const resumeBtn = document.getElementById('resume-btn');
const endGameBtn = document.getElementById('end-game-btn');
// Dugme za nastavak igre
const continueButton = document.getElementById('continue-btn');
// Dugmad za težinu
const BombBtn = document.getElementById('bomb-mode-btn');
const startGameBtn = document.getElementById('start-game-btn');
const timeAttackBtn = document.getElementById('time-attack-btn');
const practiceBtn = document.getElementById('practice-btn');
const difficultySelection = document.getElementById('difficulty-selection');
const mainButtons = document.getElementById('main-buttons');
const easyBtn = document.getElementById('easy-btn');
const normalBtn = document.getElementById('normal-btn');
const hardBtn = document.getElementById('hard-btn');
const backBtn = document.getElementById('back-btn');
// Dugmad za uputstvo
const instructionsBtn = document.getElementById('instructions-btn');
const instructionsModal = document.getElementById('instructions-modal');
const backBtnInstructions = document.getElementById('back-btn-instructions');
// Globalne varijable
let lives = 0;
let levels = [];
let totalMatchingCards = 0;
let isBombMode = false;
const INITIAL_TIME_ATTACK_TIME = 7;
const streakThreshold = 3; // broj uzastopnih uparivanja za okidanje streaka
let streakCards = [];
let consecutiveMatches = 0;
let consecutiveWrongMatches = 0; // Broj uzastopnih neuspješnih uparivanja
let assistIntervalId = null; // ID intervala za automatsko otkrivanje pomoći
let isBoardLocked = false;
let mismatchTimeout = null;
let errorSeries = []; // Niz za pogrešno uparene kartice
let isErrorSeriesActive = false;
let isClassicMode = false;
let remainingMoves = 0;
let selectedDifficulty = null;
let flipCounter = 0;
let originalBackgroundColor; // Varijabla za pohranu originalne boje pozadine
let originalBackgroundImage; // Varijabla za pohranu originalne slike pozadine
let currentLevelIndex = 0;
//let level = levels[currentLevelIndex];
let matchedCards = 0;
let timerInterval;
let remainingTime = level.solveTime;
let score = 0;
let selectedCards = [];
let bgMusic = null;
let isPracticeMode = false;
let isPaused = false;
let isTimeAttackMode = false; // Dodali smo ovu varijablu
// Varijable za Time Attack mod
let currentTimeAttackLevelIndex = 0;
let timeAttackRemainingTime = INITIAL_TIME_ATTACK_TIME; // Početno vrijeme od n sekundi
let timeAttackLevels = [...nlevels]; // Kombinacija svih nivoa
timeAttackLevels.forEach((level, index) => {
});
let startTime = null;
// Event listeneri za restart igre
restartButton.addEventListener('click', () => {
    restartSound.play(); // Prvo pokreće zvuk
    resetGame(); // Zatim resetuje igru
});

practiceBtn.addEventListener('click', () => {
    if (practiceSettings) {
        practiceSettings.style.display = 'block'; // Prikazuje formu
        practiceSettings.style.position = 'fixed'; // Osigurava fiksnu poziciju
        practiceSettings.style.top = '50%'; // Centrirano po visini
        practiceSettings.style.left = '50%'; // Centrirano po širini
        practiceSettings.style.transform = 'translate(-50%, -50%)'; // Cijeli element se centrira
        document.body.style.overflow = 'hidden'; // Sprečava skrolanje
    }
});
cancelPracticeBtn.addEventListener('click', () => {
    practiceSettings.style.display = 'none'; // Sakriva formu pravilno
    document.body.style.overflow = ''; // Dozvoljava skrolanje
});
startPracticeBtn.addEventListener('click', startPractice);
infoPanel.addEventListener('click', () => {
    if (da_li_je_game_over === false){
        pauseGame();
        pauseSound.play();}



});
const hybridInfoPanel = document.querySelector('#header-container-hybrid');
hybridInfoPanel.addEventListener('click', () => {
    if (da_li_je_game_over === false){
        pauseGame();
        pauseSound.play();}
    

});
resumeBtn.addEventListener('click', resumeGame);
endGameBtn.addEventListener('click', () => {
    restartSound.play(); // Prvo pokreće zvuk
    resetGame(); // Zatim resetuje igru
});
nextLevelBtnOverlay.addEventListener('click', () => {
    fadeOutSound(levelUpSound, 1200);
    levelCompleteMsg.style.display = 'none';
    gameBoard.style.display = 'grid';
    infoPanel.style.display = 'flex';
    startNextLevel();
});
restartGameBtnOverlay.addEventListener('click', () => {
    gameCompletedMsg.style.display = 'none';

    resetGame();
});
// Dugme za nastavak igre - Event Listener Postavljen van funkcije timeUp
continueButton.addEventListener('click', () => {
    continueSound.play();
    let penaltyPoints = parseInt(continueButton.dataset.penalty) || 0;
    bns = false; // Disable bonus for continuing
    da_li_je_game_over = false; 

    if (isHybridMode) {
        let additionalMoves = parseInt(continueButton.dataset.additionalMoves) || 0;
        let additionalSeconds = parseInt(continueButton.dataset.additionalSeconds) || 0;
        // Deduct points
        score -= penaltyPoints;
        updateScoreDisplay(score, 'decrease');

        // Add moves and time
        remainingMoves += additionalMoves;
        remainingTime += additionalSeconds;
        movesHybrid.textContent = remainingMoves;
        timerHybrid.textContent = remainingTime;

        // Restore background
        document.body.style.backgroundColor = level.backgroundColor;
        if (level.backgroundImage) {
            document.body.style.backgroundImage = `url(${level.backgroundImage})`;
        } else {
            document.body.style.backgroundImage = '';
        }

        // Hide messages and buttons
        timeUpMsg.style.display = 'none';
        
        // Resetovanje klasa dugmića
        [continueButton, useLifeButton, restartButton].forEach(button => {
            button.classList.remove('visible-button', 'hidden-button');
            button.classList.add('hidden');
        });

        // Unlock the game board
        isBoardLocked = false;
        resumeTimer();

        // Reset selected cards if any
        if (selectedCards.length > 0) {
            selectedCards.forEach(card => {
                card.classList.remove('selected', 'flipped');
            });
            selectedCards.length = 0;
        }
    } else if (isClassicMode) {
        let additionalMoves = parseInt(continueButton.dataset.additionalMoves) || 0;
        if (score < penaltyPoints) {
            alert("Nemate dovoljno poena za nastavak igre.");
            return;
        }
        score -= penaltyPoints;
        updateScoreDisplay(score, 'decrease');
        remainingMoves += additionalMoves;
        document.getElementById('moves').textContent = remainingMoves;
        document.body.style.backgroundColor = level.backgroundColor;
        if (level.backgroundImage) {
            document.body.style.backgroundImage = `url(${level.backgroundImage})`;
        } else {
            document.body.style.backgroundImage = '';
        }
        timeUpMsg.style.display = 'none';
        
        // Resetovanje klasa dugmića
        [continueButton, useLifeButton, restartButton].forEach(button => {
            button.classList.remove('visible-button', 'hidden-button');
            button.classList.add('hidden');
        });

        isBoardLocked = false;
        if (selectedCards.length > 0) {
            selectedCards.forEach(card => {
                card.classList.remove('selected', 'flipped');
            });
            selectedCards.length = 0;
        }
    } else {
        let additionalSeconds = parseInt(continueButton.dataset.additionalSeconds) || 0;
        if (score < penaltyPoints) {
            alert("Nemate dovoljno poena za nastavak igre.");
            return;
        }
        score -= penaltyPoints;
        updateScoreDisplay(score, 'decrease');
        remainingTime += additionalSeconds;
        timerDisplay.textContent = remainingTime;
        document.body.style.backgroundColor = level.backgroundColor;
        if (level.backgroundImage) {
            document.body.style.backgroundImage = `url(${level.backgroundImage})`;
        } else {
            document.body.style.backgroundImage = '';
        }
        timeUpMsg.style.display = 'none';
        
        // Resetovanje klasa dugmića
        [continueButton, useLifeButton, restartButton].forEach(button => {
            button.classList.remove('visible-button', 'hidden-button');
            button.classList.add('hidden');
        });

        isBoardLocked = false;
        resumeTimer();
        if (selectedCards.length > 0) {
            selectedCards.forEach(card => {
                card.classList.remove('selected', 'flipped');
            });
            selectedCards.length = 0;
        }
    }
});


// Event listener for "Use Life" button
useLifeButton.addEventListener('click', () => {
    useLifeSound.play();
    applyCardEffect(' red ', true, "", 500, false, "", 24);
    lives--;
    if (isHybridMode) {
        document.getElementById('lives-hybrid').textContent = lives;
    } else {
        document.getElementById('lives').textContent = lives;
    }

    bns = false; // Disable bonus for continuing
    da_li_je_game_over = false;


    if (isHybridMode) {
        let additionalMoves = parseInt(useLifeButton.dataset.additionalMoves) || 0;
        let additionalSeconds = parseInt(useLifeButton.dataset.additionalSeconds) || 0;

        // Add moves and time
        remainingMoves += additionalMoves;
        remainingTime += additionalSeconds;
        movesHybrid.textContent = remainingMoves;
        timerHybrid.textContent = remainingTime;

        // Restore background
        document.body.style.backgroundColor = level.backgroundColor;
        if (level.backgroundImage) {
            document.body.style.backgroundImage = `url(${level.backgroundImage})`;
        } else {
            document.body.style.backgroundImage = '';
        }

        // Hide messages and buttons
        timeUpMsg.style.display = 'none';
        
        // Resetovanje klasa dugmića
        [continueButton, useLifeButton, restartButton].forEach(button => {
            button.classList.remove('visible-button', 'hidden-button');
            button.classList.add('hidden');
        });

        // Unlock the game board
        isBoardLocked = false;
        resumeTimer();

        // Reset selected cards if any
        if (selectedCards.length > 0) {
            selectedCards.forEach(card => {
                card.classList.remove('selected', 'flipped');
            });
            selectedCards.length = 0;
        }
    } else if (isClassicMode) {
        let additionalMoves = parseInt(useLifeButton.dataset.additionalMoves) || 0;

        // Add moves
        remainingMoves += additionalMoves;
        document.getElementById('moves').textContent = remainingMoves;
        document.body.style.backgroundColor = level.backgroundColor;
        if (level.backgroundImage) {
            document.body.style.backgroundImage = `url(${level.backgroundImage})`;
        } else {
            document.body.style.backgroundImage = '';
        }
        timeUpMsg.style.display = 'none';
        
        // Resetovanje klasa dugmića
        [continueButton, useLifeButton, restartButton].forEach(button => {
            button.classList.remove('visible-button', 'hidden-button');
            button.classList.add('hidden');
        });

        isBoardLocked = false;
        if (selectedCards.length > 0) {
            selectedCards.forEach(card => {
                card.classList.remove('selected', 'flipped');
            });
            selectedCards.length = 0;
        }
    } else {
        let additionalSeconds = parseInt(useLifeButton.dataset.additionalSeconds) || 0;

        // Add time
        remainingTime += additionalSeconds;
        timerDisplay.textContent = remainingTime;
        document.body.style.backgroundColor = level.backgroundColor;
        if (level.backgroundImage) {
            document.body.style.backgroundImage = `url(${level.backgroundImage})`;
        } else {
            document.body.style.backgroundImage = '';
        }
        timeUpMsg.style.display = 'none';
        
        // Resetovanje klasa dugmića
        [continueButton, useLifeButton, restartButton].forEach(button => {
            button.classList.remove('visible-button', 'hidden-button');
            button.classList.add('hidden');
        });

        isBoardLocked = false;
        resumeTimer();
        if (selectedCards.length > 0) {
            selectedCards.forEach(card => {
                card.classList.remove('selected', 'flipped');
            });
            selectedCards.length = 0;
        }
    }
});
document.getElementById('view-results-btn').addEventListener('click', showResultsOverlay);
// Event listeneri za dugmad za težinu
const classicModeBtn = document.getElementById('classic-mode-btn');
classicModeBtn.addEventListener('click', () => {
    difficultySelection.style.display = 'block';
    document.getElementById('background-overlay').style.display = 'block'; // Prikaži overlay
   mainButtons.style.display ="none";
    isClassicMode = true;
});
startGameBtn.addEventListener('click', () => {
    difficultySelection.style.display = 'block';
    document.getElementById('background-overlay').style.display = 'block'; // Prikaži overlay
    mainButtons.style.display ="none";
});
['easy-btn', 'normal-btn', 'hard-btn'].forEach(btnId => {
    document.getElementById(btnId).addEventListener('click', () => {
        difficultySelection.style.display = 'none';
        document.getElementById('background-overlay').style.display = 'none';
    });
});

backBtn.addEventListener('click', () => {
    difficultySelection.style.display = 'none'; // Zatvara selektor težine
    mainButtons.style.display = 'flex';
    document.getElementById('background-overlay').style.display = 'none'; // Sakriva overlay
    document.getElementById('moves').style.display = 'none';
});
// Event listeneri za odabir težine
easyBtn.addEventListener('click', () => {
    selectedDifficulty = 'easy';
    lives = 3;
    startGame();
    difficultySelection.style.display = 'none';
});

normalBtn.addEventListener('click', () => {
    selectedDifficulty = 'normal';
    lives = 2;
    startGame();
    difficultySelection.style.display = 'none';
});

hardBtn.addEventListener('click', () => {
    selectedDifficulty = 'hard';
    lives = 1;
    startGame();
    difficultySelection.style.display = 'none';
});

// Event listeneri za uputstvo
instructionsBtn.addEventListener('click', showInstructions);
backBtnInstructions.addEventListener('click', hideInstructions);
function showInstructions() {
    instructionsModal.classList.add('show'); // Prikazuje modal
    document.body.classList.add('instructions-active'); // Menja boju pozadine
}
function hideInstructions() {
    instructionsModal.classList.remove('show'); // Sakriva modal
    document.body.classList.remove('instructions-active'); // Vraća boju pozadine na normalnu
}
// Event listener za Time Attack dugme
timeAttackBtn.addEventListener('click', startTimeAttackMode);
function updateInfoTextColor() {
    const infoTextColor = level.infoTextColor || '#ffffff';
    const infoElements = document.querySelectorAll('#header-container .info p, #header-container .info span');
    infoElements.forEach(element => {
        element.style.color = infoTextColor;
    });

    // Apply color to hybrid header
    const hybridInfoElements = document.querySelectorAll('#header-container-hybrid .info p, #header-container-hybrid .info span');
    hybridInfoElements.forEach(element => {
        element.style.color = infoTextColor;
    });
}
function revealAssistanceCards() {
    
    if (!level || !gameBoard) {
        console.error('Level ili gameBoard je undefined ili null');
        return;
        
    }
  /* if (isBoardLocked) {
        console.log("Board is locked. Assistance cards will not be revealed.");
        return;
    }*/
    
    if (level.maxAssistPerLevel !== undefined) {
        if (!level.currentAssistCount) {
            level.currentAssistCount = 0;
        }
        if (level.currentAssistCount >= level.maxAssistPerLevel) {
            console.log("Max assist per level reached.");
            clearInterval(assistIntervalId);
            return;
        }
        level.currentAssistCount += 1;
    }
    flipSound.play();
    // Pronađi sve kartice koje nisu uparene, nisu otkrivene kao pomoć i nisu trenutno otkrivene
    const availableCards = Array.from(gameBoard.querySelectorAll('.card'))
        .filter(card => !card.classList.contains('matched') && !card.classList.contains('flipped') && !card.classList.contains('assisted'));
    console.log(`Available cards for assistance: ${availableCards.length}`);
    if (availableCards.length === 0) {
        console.log("No available cards to reveal for assistance.");
        return; // Nema dostupnih kartica za pomoć
    }
    // Nasumično odaberi kartice za pomoć
    const shuffled = shuffleArray(availableCards);
    const assistanceCards = shuffled.slice(0, level.assistCardsCount);
    console.log("Assistance cards selected:", assistanceCards);
    // Otvori odabrane kartice
    assistanceCards.forEach(card => {
       
        card.classList.add('flipped', 'assisted'); // Dodajte 'assisted' klasu za identifikaciju pomoćnih kartica
    });
    // Nakon assistRevealTime, sakrij pomoćne kartice ako nisu uparene
    setTimeout(() => {
        assistanceCards.forEach(card => {
            if (!card.classList.contains('matched')) {
                card.classList.remove('flipped', 'assisted');
                console.log("Assistance card hidden:", card);
            }
        });
    }, level.assistRevealTime);
}


function showDifficultySelection() {
    // Prikaži selektor težine
    difficultySelection.style.display = 'block';
    // Sakrij glavna dugmad
    mainButtons.style.display = 'none';
}
function startPractice() {
    mainButtons.style.display ="none";
    isPracticeMode = true;
    isTimeAttackMode = false; // Osiguravamo da nije Time Attack mod
    // Preuzimanje unesenih vrijednosti
    const rows = parseInt(document.getElementById('practice-rows').value);
    const cols = parseInt(document.getElementById('practice-cols').value);
    const matchCards = parseInt(document.getElementById('practice-match-cards').value);
    const solveTime = parseInt(document.getElementById('practice-solve-time').value);
    const flipBackTime = parseInt(document.getElementById('practice-flip-back-time').value) || 1500;
    const mismatchTime = parseInt(document.getElementById('practice-mismatch-time').value) || 500;
    const matchDelayTime = parseInt(document.getElementById('practice-match-delay-time').value) || 500;
    const cardColor = document.getElementById('practice-card-color').value || "#ff6666";
    const bgColor = document.getElementById('practice-bg-color').value || "#f4f4f9";
    const bgImageInput = document.getElementById('practice-bg-image');
    const musicInput = document.getElementById('practice-music');
    const numberOfCardsToShow = parseInt(document.getElementById('practice-cards-to-show').value) || 0;
    const previewTime = parseInt(document.getElementById('practice-preview-time').value) || 0;
    const musicVolume = parseFloat(document.getElementById('practice-music-volume').value);
    const cardBackImageInput = document.getElementById('practice-card-back-image');
    classicModeBtn.style.display = 'none';
    // Validacija unosa
    const totalCards = rows * cols;
    if (totalCards % matchCards !== 0) {
        alert("Ukupan broj kartica mora biti djeljiv sa brojem kartica za uparivanje.");
        return;
    }
    // Kreiranje prilagođenog nivoa
    level = {
        name: "Vježba",
        grid: { cols: cols, rows: rows },
        cardColor: cardColor,
        backgroundColor: bgColor,
        backgroundImage: "backgrounds/vjezba.webp",
        music: "",
        flipBackTime: flipBackTime,
        flipBackTimeUnpair: 800,
        mismatchTime: mismatchTime,
        matchDelayTime: matchDelayTime,
        solveTime: solveTime,
        matchCards: matchCards,
        numberOfCardsToShow: numberOfCardsToShow,
        previewTime: previewTime,
        musicVolume: musicVolume,
        cardBackImage: ""
    };
    let numberOfCards = parseInt(document.getElementById('practice-match-cards').value);
    // Postavi broj kartica u info panelu
    infoPanel.style.color = '#FFD70f'; // Postavlja boju na žutu (gold)
    // Učitavanje pozadinske slike ako je izabrana
    if (bgImageInput.files && bgImageInput.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            level.backgroundImage = e.target.result;
            proceedToPractice();
        };
        reader.readAsDataURL(bgImageInput.files[0]);
    } else {
        proceedToPractice();
    }
    function proceedToPractice() {
        // Učitavanje pozadinske muzike ako je izabrana
        if (musicInput.files && musicInput.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                level.music = e.target.result;
                proceedToCardBackImage();
            };
            reader.readAsDataURL(musicInput.files[0]);
        } else {
            proceedToCardBackImage();
        }
    }
    function proceedToCardBackImage() {
        // Učitavanje slike za poleđinu kartice ako je izabrana
        if (cardBackImageInput.files && cardBackImageInput.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                level.cardBackImage = e.target.result;
                setupPracticeGame();
            };
            reader.readAsDataURL(cardBackImageInput.files[0]);
        } else {
            setupPracticeGame();
        }
    }
    function setupPracticeGame() {
        // Pokretanje u fullscreen modu
        //openFullscreen();
        // Dodajemo klasu za animaciju
        document.body.classList.add('fade-out');
        setTimeout(() => {
            document.body.classList.remove('fade-out');
            practiceSettings.style.display = 'none';
            logo.style.display = 'none';
            headerContainer.style.display = 'flex';
            //logoSmall.style.display = 'block';
            startGameBtn.style.display = 'none';
            practiceBtn.style.display = 'none';
            timeAttackBtn.style.display = 'none';
            instructionsBtn.style.display = 'none';
            gameBoard.style.display = 'grid';
            infoPanel.style.display = 'flex';
            document.body.style.backgroundColor = level.backgroundColor;
            if (bgMusic) {
                bgMusic.pause();
                bgMusic.currentTime = 0;
            }
            // Pokretanje pozadinske muzike ako postoji
            if (level.music) {
                bgMusic = new Audio(level.music);
                bgMusic.loop = true;
                bgMusic.volume = level.musicVolume;
                bgMusic.play();
            }
            createBoard();
        }, 500); // Vrijeme trajanja animacije
    }
}
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]]; // Zameni elemente
    }
    return array;
}
function logTextColors() {
    // Selektujemo sve elemente unutar `header-container`
    const headerContainer = document.getElementById('header-container');
    const elements = headerContainer.querySelectorAll('*');
    elements.forEach((element, index) => {
        // Uzimamo `color` stil za svaki element
        const textColor = window.getComputedStyle(element).color;
    });
}

function createBoard() {

clearAllTimeouts();
clearCardFlipTimeouts();
bns = true; 
if (assistIntervalId) {
    clearInterval(assistIntervalId);
    assistIntervalId = null;
}
isBoardLocked = true;
console.log('createBoard called, isBombMode:', isBombMode);

// Clear any existing timer interval
if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
}

consecutiveWrongMatches = 0;
level.currentAssistCount = 0;

// Check for bombs or special cards to decide grid creation
if (
    (level.bigBombs && level.bigBombs > 0) ||
    (level.smallBombs && level.smallBombs > 0) ||
    (level.specialCards && Object.values(level.specialCards).some(card => card > 0))
) {
    createBombGrid();
    return;
}

// Set up assistance interval if applicable
if (
    (level.assistMode === "time" || level.assistMode === "both") &&
    level.assistInterval &&
    level.assistCardsCount > 0
) {
    assistIntervalId = setInterval(() => {
        console.log("Assist interval triggered.");
        revealAssistanceCards();
    }, level.assistInterval);
    console.log(`Assist interval set: every ${level.assistInterval} ms`);
} else {
    console.log(
        "Assist interval not set. Either assistMode does not include time or parameters are not defined."
    );
}

// Determine game mode and update UI elements accordingly
if (isTimeAttackMode) {
    currentGameMode = 'Dokle vise';
}
if (isTimeAttackMode) {
    levelDisplay.textContent = currentTimeAttackLevelIndex + 1;
    remainingTime = timeAttackRemainingTime;
} else if (level.moves && level.moves > 0) {
    isClassicMode = true;
    remainingMoves = level.moves + testMode + kupljenipoteziskroz + kupljenipotezi;
    levelDisplay.textContent = isPracticeMode ? '-' : currentLevelIndex + 1;

    const timerContainer = document.querySelector('.timer-container');
    const movesContainer = document.querySelector('.moves-container');
    if (timerContainer && movesContainer) {
        timerContainer.style.display = 'none';
        movesContainer.style.display = 'block';
        document.getElementById('moves').textContent = remainingMoves > 0 ? remainingMoves : '∞';
    }
    scoreDisplayMoves.textContent = score;
    cardsToMatchMoves.textContent = level.matchCards;
} else {
    isClassicMode = false;
    remainingTime = level.solveTime + testMode + kupljenovrijeme + kupljenovrijemeskroz;
    levelDisplay.textContent = isPracticeMode ? '-' : currentLevelIndex + 1;

    const timerContainer = document.querySelector('.timer-container');
    const movesContainer = document.querySelector('.moves-container');
    if (timerContainer && movesContainer) {
        timerContainer.style.display = 'block';
        movesContainer.style.display = 'none';
        timerDisplay.textContent = remainingTime;
    }
    scoreDisplayTimer.textContent = score;
    cardsToMatchTimer.textContent = level.matchCards;
}

// Reset game board and related variables
gameBoard.innerHTML = '';
gameBoard.style.display = '';
gameBoard.style.flexDirection = '';
gameBoard.style.gridTemplateColumns = '';
gameBoard.style.gap = '';
matchedCards = 0;
selectedCards = [];
document.body.style.backgroundColor = level.backgroundColor;

// Set background image if specified
if (level.backgroundImage) {
    // Provjerava postoji li .jpg na kraju i uklanja ga prije dodavanja teme
    let baseImage = level.backgroundImage.endsWith('.jpg') 
        ? level.backgroundImage.slice(0, -4) 
        : level.backgroundImage;

    let themedBackground = `${baseImage}${tema}.jpg`;
    console.log("Pokušava učitati sliku:", themedBackground); 
    document.body.style.backgroundImage = `url(${themedBackground})`;
    document.body.style.backgroundSize = 'cover';
    document.body.style.backgroundPosition = 'center center';
} else {
    console.log("Nema slike za učitavanje, postavljam prazan background.");
    document.body.style.backgroundImage = '';
}

let totalCards = 0;
let maxCardsInRow = 0;
const availableWidth = window.innerWidth;
const availableHeight = window.innerHeight - 42;
let generatedCards = []; // Ovdje ćemo privremeno čuvati sve kartice (DOM elemente)

// Generate cards based on the grid type
if (Array.isArray(level.grid) && Array.isArray(level.grid[0])) {
    // Grid je 2D niz
    const levelType = 'matrix';
    gameBoard.style.display = 'flex';
    gameBoard.style.flexDirection = 'column';
    gameBoard.style.gap = '7px';

    level.grid.forEach(row => {
        let rowLength = row.length;
        if (rowLength > maxCardsInRow) {
            maxCardsInRow = rowLength;
        }
        row.forEach(cell => {
            if (cell === 'k') {
                totalCards++;
            }
        });
    });
    document.documentElement.style.setProperty('--max-cards-in-row', maxCardsInRow);

    // Odaberi kartice
    const numUniqueCards = totalCards / level.matchCards;

    // **Odabir tačno jedne slike iz mandatoryImages**
    let mandatoryImage = mandatoryImages[Math.floor(Math.random() * mandatoryImages.length)];

    // Filtriraj currentImages da ukloni sve slike koje su u mandatoryImages
    let availableImages = currentImages.filter(img => !mandatoryImages.includes(img));

    // Provjera da li ima dovoljno dostupnih slika
    if (availableImages.length < (numUniqueCards - 1)) {
        console.error("Nema dovoljno dostupnih slika u currentImages za odabir.");
        return;
    }

    // Odaberi preostale potrebne slike iz availableImages
    let selectedImages = shuffleArray(availableImages).slice(0, numUniqueCards - 1);

    // Dodaj obaveznu sliku
    selectedImages.unshift(mandatoryImage);

    // Kreiraj niz sa ponovljenim slikama prema level.matchCards
    let cardImages = [];
    selectedImages.forEach(image => {
        for (let i = 0; i < level.matchCards; i++) {
            cardImages.push(image);
        }
    });

    // Promiješaj kartice
    cardImages = shuffleArray(cardImages);
    let imageIndex = 0;

    // Kreiraj grid
    level.grid.forEach((row, rowIndex) => {
        let rowDiv = document.createElement('div');
        rowDiv.classList.add('row');
        const numCols = row.length;
        rowDiv.style.setProperty('--max-cards-in-row', numCols);

        row.forEach((cell, colIndex) => {
            if (cell === 'k') {
                let card = document.createElement('div');
                card.classList.add('card', 'showing');
                card.dataset.image = cardImages[imageIndex++];
                if (card.dataset.image === mandatoryImage) {
                    card.classList.add('mandatory-card');
                }

                // Ako ima cardBackImage, stavi u backgroundImage
                // ali ostavi boju "praznu" (naknadno ćemo postaviti boju/gradient).
                if (level.cardBackImage) {
                    card.style.backgroundImage = `url(${level.cardBackImage})`;
                    card.style.backgroundSize = 'cover';
                    card.style.backgroundPosition = 'center center';
                } else {
                    card.style.backgroundImage = '';
                }

                card.innerHTML = `<img src="${card.dataset.image}" alt="Memory Image">`;
                rowDiv.appendChild(card);
                generatedCards.push(card);

                // Attach event listeners
                card.addEventListener('click', flipCard);
                card.addEventListener('animationend', () => {
                    card.classList.remove('showing');
                });
                cardAppearSound.play();
            } else if (cell === 'p') {
                // Placeholder
                let placeholder = document.createElement('div');
                placeholder.classList.add('placeholder');
                rowDiv.appendChild(placeholder);
            }
        });
        calculateMaxHeight(level.grid, levelType, availableWidth, availableHeight);
        gameBoard.appendChild(rowDiv);
    });
} else if (Array.isArray(level.grid)) {
    // Grid je 1D niz
    const levelType = 'array'
    gameBoard.style.display = 'flex';
    gameBoard.style.flexDirection = 'column';
    gameBoard.style.gap = '7px';

    totalCards = level.grid.reduce((a, b) => a + b, 0);
    maxCardsInRow = Math.max(...level.grid);
    document.documentElement.style.setProperty('--max-cards-in-row', maxCardsInRow);

    // Odaberi kartice
    const numUniqueCards = totalCards / level.matchCards;

    // **Odabir tačno jedne slike iz mandatoryImages**
    let mandatoryImage = mandatoryImages[Math.floor(Math.random() * mandatoryImages.length)];

    // Filtriraj currentImages da ukloni sve slike koje su u mandatoryImages
    let availableImages = currentImages.filter(img => !mandatoryImages.includes(img));

    // Provjera da li ima dovoljno dostupnih slika
    if (availableImages.length < (numUniqueCards - 1)) {
        console.error("Nema dovoljno dostupnih slika u currentImages za odabir.");
        return;
    }

    // Odaberi preostale potrebne slike iz availableImages
    let selectedImages = shuffleArray(availableImages).slice(0, numUniqueCards - 1);

    // Dodaj obaveznu sliku
    selectedImages.unshift(mandatoryImage);

    // Kreiraj niz sa ponovljenim slikama prema level.matchCards
    let cardImages = [];
    selectedImages.forEach(image => {
        for (let i = 0; i < level.matchCards; i++) {
            cardImages.push(image);
        }
    });

    // Promiješaj kartice
    cardImages = shuffleArray(cardImages);
    let imageIndex = 0;

    // Kreiraj grid
    level.grid.forEach((numCardsInRow, rowIndex) => {
        let rowDiv = document.createElement('div');
        rowDiv.classList.add('row');
        rowDiv.style.setProperty('--max-cards-in-row', maxCardsInRow);

        // Set alignment class
        if (level.rowAlignment) {
            rowDiv.classList.add(`align-${level.rowAlignment}`);
        } else {
            rowDiv.classList.add('align-center');
        }

        for (let colIndex = 0; colIndex < numCardsInRow; colIndex++) {
            let card = document.createElement('div');
            card.classList.add('card', 'showing');
            card.dataset.image = cardImages[imageIndex++];
            if (card.dataset.image === mandatoryImage) {
                card.classList.add('mandatory-card');
            }

            if (level.cardBackImage) {
                card.style.backgroundImage = `url(${level.cardBackImage})`;
                card.style.backgroundSize = 'cover';
                card.style.backgroundPosition = 'center center';
            } else {
                card.style.backgroundImage = '';
            }

            card.innerHTML = `<img src="${card.dataset.image}" alt="Memory Image">`;
            rowDiv.appendChild(card);
            generatedCards.push(card);

            // Attach event listeners
            card.addEventListener('click', flipCard);
            card.addEventListener('animationend', () => {
                card.classList.remove('showing');
            });
            cardAppearSound.play();
        }
        calculateMaxHeight(level.grid, levelType, availableWidth, availableHeight);
        gameBoard.appendChild(rowDiv);
    });
} else if (typeof level.grid === 'object' && level.grid.cols && level.grid.rows) {
    // Grid je objekt sa 'cols' i 'rows'
    const levelType = 'cols-rows';
    gameBoard.style.display = 'grid';
    gameBoard.style.gridTemplateColumns = `repeat(${level.grid.cols}, 1fr)`;
    gameBoard.style.gap = '7px';

    totalCards = level.grid.cols * level.grid.rows;

    // Odaberi kartice
    const numUniqueCards = totalCards / level.matchCards;

    // **Odabir tačno jedne slike iz mandatoryImages**
    let mandatoryImage = mandatoryImages[Math.floor(Math.random() * mandatoryImages.length)];

    // Filtriraj currentImages da ukloni sve slike koje su u mandatoryImages
    let availableImages = currentImages.filter(img => !mandatoryImages.includes(img));

    // Provjera da li ima dovoljno dostupnih slika
    if (availableImages.length < (numUniqueCards - 1)) {
        console.error("Nema dovoljno dostupnih slika u currentImages za odabir.");
        return;
    }

    // Odaberi preostale potrebne slike iz availableImages
    let selectedImages = shuffleArray(availableImages).slice(0, numUniqueCards - 1);

    // Dodaj obaveznu sliku
    selectedImages.unshift(mandatoryImage);

    // Kreiraj niz sa ponovljenim slikama prema level.matchCards
    let cardImages = [];
    selectedImages.forEach(image => {
        for (let i = 0; i < level.matchCards; i++) {
            cardImages.push(image);
        }
    });

    // Promiješaj kartice
    cardImages = shuffleArray(cardImages);

    // Kreiraj grid
    for (let i = 0; i < totalCards; i++) {
        let card = document.createElement('div');
        card.classList.add('card', 'showing');
        card.dataset.image = cardImages[i];
        if (card.dataset.image === mandatoryImage) {
            card.classList.add('mandatory-card');
        }

        if (level.cardBackImage) {
            card.style.backgroundImage = `url(${level.cardBackImage})`;
            card.style.backgroundSize = 'cover';
            card.style.backgroundPosition = 'center center';
        } else {
            card.style.backgroundImage = '';
        }

        card.innerHTML = `<img src="${card.dataset.image}" alt="Memory Image">`;
        calculateMaxHeight(level.grid, levelType, availableWidth, availableHeight);
        gameBoard.appendChild(card);
        generatedCards.push(card);

        // Attach event listeners
        card.addEventListener('click', flipCard);
        card.addEventListener('animationend', () => {
            card.classList.remove('showing');
        });
        cardAppearSound.play();
    }
} else {
    console.error("The level has an unknown 'grid' property format.");
    return;
}

// =================== DODJELA BOJA KARTICAMA NA OSNOVU colorScheme i gradient ===================
// Ovdje pozivamo našu pomoćnu funkciju i prosljeđujemo joj parametre.
// Dakle, u svom level objektu moraš imati npr.
// level.colorScheme = "uniformRandom" ili "randomAll" ili "randomPairs"
// level.gradient    = "none" ili "horizontal" ili "vertical" ili "radial" ili "diagonal"
// (prilagodi kako ti odgovara)
assignColorsToCards({
    cards: generatedCards,
    matchCards: level.matchCards,
    colorScheme: level.colorScheme || 'uniformRandom', 
    gradient: level.gradient || 'none'
});
// =================================================================================================

// Show cards at the start if preview time is specified
if (level.previewTime > 0) {
    // Pause the timer during preview
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    showCardsAtStart(() => {
        isBoardLocked = false; // Unlock the board after preview
        if (!isClassicMode && !isPaused) {
            startTimer(); // Start the timer after preview if not paused
            if (robot > 0 && igralitajrobot === "jasta_nego_igra"){ console.log("Robot igra: simulatePlayWithAccuracy() pozvan.");
                    simulatePlayWithAccuracy();}
        }
        if (isClassicMode && !isPaused) {
            if (robot > 0 && igralitajrobot === "jasta_nego_igra"){ console.log("Robot igra: simulatePlayWithAccuracy() pozvan.");
                    simulatePlayWithAccuracy();}
        }
    });
} else {
    isBoardLocked = false; // Unlock the board if no preview
    if (!isClassicMode && !isPaused) {
        startTimer(); // Start the timer immediately if not paused
        if (robot > 0 && igralitajrobot === "jasta_nego_igra"){ console.log("Robot igra: simulatePlayWithAccuracy() pozvan.");
        simulatePlayWithAccuracy();}
        
    }
}

totalMatchingCards = totalCards;
globalTotalMatchingCards = totalMatchingCards; 
logTextColors(); // Assuming this function is defined elsewhere


           
}


function showCardsAtStart(callback) {
    levelCompleted = false;

    isBoardLocked = true;

    // Pause the timer during preview
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }

    let cards = Array.from(document.querySelectorAll('.card'));
    let cardsToShow;
    if (level.numberOfCardsToShow >= cards.length || level.numberOfCardsToShow === 0) {
        cardsToShow = cards;
    } else {
        cardsToShow = [];
        let shuffledCards = shuffleArray(cards);
        cardsToShow = shuffledCards.slice(0, level.numberOfCardsToShow);
    }
    cardsToShow.forEach(card => {
        card.classList.add('flipped');
    });
    setTimeout(() => {
        cardsToShow.forEach(card => {
            card.classList.remove('flipped');
        });
        isBoardLocked = false; // Unlock the board after preview
        if (callback) callback(); // Start the timer after preview
    }, level.previewTime + kupljenoprikazivanje + kupljenoprikazivanjeskroz);
   
}
function handleErrorSeries(cards) {
    // Prvo, očistimo postojeće flipBackTimeout za svaku karticu
        cards.forEach(card => {
            if (card.flipBackTimeout) {
            clearTimeout(card.flipBackTimeout);
            card.flipBackTimeout = null;
        }
    });
    // Flip i primjena error klase na sve kartice istovremeno
        cards.forEach(card => {
         card.dataset.originalBackground = card.style.background;
         card.style.backgroundImage = "none";
         card.classList.add('flipped', 'error'); // Okreni karticu i primijeni vizualni efekt greške
         card.classList.remove('selected'); // Ukloni 'selected' klasu
    });
    // Nakon flipBackTimeUnpair, okreni nazad kartice i ukloni error klasu
    setTimeout(() => {
            cards.forEach(card => {
                card.classList.remove('flipped', 'error'); // Sakrij karticu i ukloni klase
                 if (card.dataset.originalBackground) {
                card.style.background = card.dataset.originalBackground;
}
        });
    }, level.flipBackTimeUnpair);
}
function handleSpecialCard(card) {
    if (isPaused || isBoardLocked) return;
    const specialCard = event.currentTarget;
    let specialType = specialCard.dataset.type;
    
    if (specialType === 'randomCard') {
        // Definišemo dostupne specijalne kartice prema režimu igre
        let availableSpecialCards = [
            'rotateBoard', 'increaseTime', 'decreaseTime', 'increasePoints',
            'decreasePoints', 'helpCard', 'freezeCard', 'randomMatch',
            'doublePoints', 'halfPoints', 'bonusCard', 'increaseMoves',
            'decreaseMoves', 'bwCard', 'bigbomb', 'smallbomb'
        ];

        // Filtriramo dostupne kartice u zavisnosti od režima igre
        if (isClassicMode) {
            availableSpecialCards = availableSpecialCards.filter(card => !['increaseTime', 'decreaseTime'].includes(card));
        } else if (isTimeAttackMode || isTimeMode) {
            availableSpecialCards = availableSpecialCards.filter(card => !['increaseMoves', 'decreaseMoves'].includes(card));
        }

        // Nasumično biramo specijalnu karticu
        const randomIndex = Math.floor(Math.random() * availableSpecialCards.length);
        specialType = availableSpecialCards[randomIndex];

        // Pretvaramo `randomCard` u izabranu specijalnu karticu
        specialCard.dataset.type = specialType;
        specialCard.classList.add('converted-to-special');
    }

    // Nastavljamo kao da je kliknuta specifična kartica
    if (specialCard.classList.contains('flipped')) return;
    specialCard.classList.add('flipped', 'special-clicked');
    
    // Reprodukcija zvuka specijalne kartice
    specialSound = new Audio(`sounds/${specialType}.mp3`);
    specialSound.play();
    activeSpecialSounds.push(specialSound);

    // Smanjivanje poteza u Classic ili Hybrid modu
    if ((isClassicMode && level.moves > 0) || isHybridMode) {
        remainingMoves--;
        if (isHybridMode) {
            movesHybrid.textContent = remainingMoves;
        } else {
            document.getElementById('moves').textContent = remainingMoves;
        }
        if (remainingMoves <= 0) {
            if (isHybridMode) {
                gameOverHybrid('moves');
            } else {
                gameOverClassic();
            }
            return;
        }
    }

    // Aktiviranje specijalnog efekta i prosleđivanje `event` u funkciju
    triggerSpecialCardEffect(specialType, event);

    // Nakon što efekat bude primenjen, uklanjamo događaj
    specialCard.removeEventListener('click', handleSpecialCardClick);

    // Provera preostalih poteza i vremena
    if ((isClassicMode && remainingMoves <= 0) || (isHybridMode && remainingMoves <= 0)) {
        if (isHybridMode) {
            gameOverHybrid('moves');
        } else {
            gameOverClassic();
        }
    }
    if (isHybridMode && remainingTime <= 0) {
        gameOverHybrid('time');
    }
}
function flipCard() {
    if (isPaused || isBoardLocked) return;
    if (this.classList.contains('matched')) return;
    if (this.classList.contains('selected')) return;
    if (this.classList.contains('error')) return;
    if (isBombMode && this.dataset.type && this.dataset.type !== 'card') {
    // To znači da je specijalna kartica
    console.log("Aktiviram specijalnu karticu:", this.dataset.type);
    handleSpecialCard(this);
    return;
  }

    // Dodavanje klasa za odabrane kartice
    this.classList.add('selected', 'flipped');
    selectedCards.push(this);

    // Ovisno o broju flipova, pusti različit zvuk
    if (flipCounter % 2 === 0) {
        flipSound.play();
    } else {
        flipSound2.play();
    }
    flipCounter++;

    // Ako postoji prethodni timeout za vraćanje kartica, poništi ga
    if (this.flipBackTimeout) {
        clearTimeout(this.flipBackTimeout);
    }

    // Postavi novi timeout da kartica nestane nakon određenog vremena
    this.flipBackTimeout = setTimeout(() => {
        if (!this.classList.contains('matched')) {
            this.classList.remove('flipped'); // Sakrij karticu
        }
    }, level.flipBackTime);

    // Provjera mogućnosti uparivanja nakon svakog odabira
    if (selectedCards.length > 1) {
        const firstImage = selectedCards[0].dataset.image;
        const allMatchSoFar = selectedCards.every(card => card.dataset.image === firstImage);

        if (!allMatchSoFar) {
            // Ako nema mogućeg uparivanja, tretiraj kao neuspješan meč odmah
            console.log("Early mismatch detected. Triggering mismatch handling.");

            // Neuspješan meč
            mismatchSound.play();
            consecutiveMatches = 0; // Resetuj brojač uzastopnih mečeva
            streakCards = [];
            score -= Math.round(level.nonMatchedPenalty * pointsModifier * ((currentLevelIndex / 30) + 1));
            updateScoreDisplay(score, 'decrease');

            // Vizualni efekti za pogrešan meč
            handleErrorSeries(selectedCards.slice());
            isBoardLocked = true;

            setTimeout(() => {
                resetBoard();
                if (!robotPlaying) {
    isBoardLocked = false;};
            }, level.mismatchTime);

            // Smanjenje preostalih poteza u Classic ili Hybrid modu
            if (!isTimeAttackMode && ((isClassicMode && level.moves > 0) || isHybridMode)) {
                remainingMoves--;
                if (isHybridMode) {
                    movesHybrid.textContent = remainingMoves;
                } else {
                    document.getElementById('moves').textContent = remainingMoves;
                }

                // Provjera da li su preostali potezi 0
                if (remainingMoves === 0) {
                    if (matchedCards === totalMatchingCards) {
                  
                        // Ako su sve kartice uparene, prelazimo na sljedeći nivo
                        setTimeout(() => {
                       
                            levelUp(); // Prelazak na sljedeći nivo
                            if (!robotPlaying) {
                                isBoardLocked = false;};
                        }, 448); // Mali delay radi glatkog prelaska
                    } else {
                        // Nije sve upareno, igra se završava
                        if (isHybridMode) {
                            setTimeout(() => gameOverHybrid('moves'), level.flipBackTimeUnpair);
                        } else {
                            setTimeout(gameOverClassic, level.flipBackTimeUnpair);
                        }
                    }
                    return;
                }
            }

            // Ažuriranje brojača uzastopnih pogrešnih mečeva ako je asistencija uključena
            if (level.assistMode === "event" || level.assistMode === "both") {
                consecutiveWrongMatches += 1;
                console.log(`Consecutive wrong matches: ${consecutiveWrongMatches}`);
                if (consecutiveWrongMatches >= level.assistTriggerConsecutiveFails) {
                    console.log("Consecutive wrong matches threshold reached. Triggering assistance.");
                    revealAssistanceCards();
                    consecutiveWrongMatches = 0;
                }
            }

            // Reset selectedCards
            selectedCards = [];
            return; // Prekid funkcije jer je meč već obrađen
        }
    }

    // Ako je odabrano dovoljno kartica, provjeri da li su meč
    if (selectedCards.length === level.matchCards) {
        checkMatch();
    }
}

function checkMatch() {
    console.log("checkMatch called with selectedCards:", selectedCards);

    // Provjera da li je selectedCards prazan
    if (!selectedCards || selectedCards.length === 0) { 
        console.warn('checkMatch called with empty selectedCards.');
        return;
    }

    // Provjera da li svi elementi u selectedCards postoje
    for (let i = 0; i < selectedCards.length; i++) {
        if (!selectedCards[i]) {
            console.error(`selectedCards[${i}] is undefined.`);
            return;
        }
    }

    // Provjera da li je broj odabranih kartica jednak broju potrebnih za uparivanje
    if (selectedCards.length !== level.matchCards) {
        console.warn(`Expected ${level.matchCards} cards for a match, but got ${selectedCards.length}.`);
        return;
    }

    const firstImage = selectedCards[0].dataset.image;
    const allMatch = selectedCards.every(card => card.dataset.image === firstImage);

    if (allMatch) {
        console.log("All selected cards match.");

        // Uspješan meč
        isBoardLocked = true;

        // Dodavanje/uklanjanje klasa karticama
        selectedCards.forEach(card => {
            card.classList.remove('assisted');
            card.classList.add('matched', 'flipped');
            card.classList.remove('selected');
            card.style.backgroundImage = "none";
        });

        setTimeout(() => {
            matchSound.play();
        }, 0);

        if (isTimeAttackMode) {
            // Time Attack Mode logika
            console.log("Time Attack Mode is active.");
            console.log("Consecutive Matches:", consecutiveMatches);
            console.log("Streak Threshold:", streakThreshold);
            let ispravkazaredom = consecutiveMatches + 1;
            if (ispravkazaredom >= streakThreshold) {
                timeAttackRemainingTime += Math.round(selectedCards.length * 1.3 + (ispravkazaredom * 0.48));
            } else {
                timeAttackRemainingTime += Math.round(selectedCards.length * 1.5);
            }
            remainingTime = timeAttackRemainingTime;
            timerDisplay.textContent = remainingTime;
        }

        // Ažuriranje rezultata
        score += Math.round(selectedCards.length * level.pointsPerMatch * pointsModifier * duplipoeni * duplipoeniskroz * ((currentLevelIndex / 20) + 1));

        zivotna_provjera();
        updateScoreDisplay(score, 'increase');
        matchedCards += selectedCards.length;

        // Povećanje brojača uzastopnih mečeva
        consecutiveMatches += 1;
        console.log(`Consecutive matches: ${consecutiveMatches}`);

        // Dodavanje uparene kartice u streakCards
        streakCards = streakCards.concat(selectedCards);

        // Provjera streak bonusa
        if (consecutiveMatches >= streakThreshold) {
            console.log("Streak threshold reached. Applying streak bonus.");
            applauseSound.play();
            let extraPoints = Math.round(consecutiveMatches * level.ConMatch * pointsModifier * duplipoeni * duplipoeniskroz ) * 3;
            score += extraPoints;
            zivotna_provjera();
            updateScoreDisplay(score, 'increase');
            flashBackground();
            flashStreakCards();
        }

        // Provjera da li je nivo kompletiran
        if (matchedCards === totalMatchingCards) {
            console.log("All matching cards have been matched. Level completed.");
            levelCompleted = true;
            if (isClassicMode || isHybridMode) {
                remainingMoves--;
                if (isHybridMode) {
                    movesHybrid.textContent = remainingMoves;
                } else {
                    document.getElementById('moves').textContent = remainingMoves;
                }
            }
            clearInterval(timerInterval);
            setTimeout(() => {
                levelUp();
                if (!robotPlaying) {
    isBoardLocked = false;};
                if (assistIntervalId) {
                    clearInterval(assistIntervalId);
                    assistIntervalId = null;
                }
            }, 500);
        } else {
            // Smanjivanje poteza samo ako nivo nije kompletiran
            if (!isTimeAttackMode && ((isClassicMode && level.moves > 0) || isHybridMode)) {
                remainingMoves--;
                console.log(`Moves remaining: ${remainingMoves}`);
                if (isHybridMode) {
                    movesHybrid.textContent = remainingMoves;
                } else {
                    document.getElementById('moves').textContent = remainingMoves;
                }

                // Provjera za game over samo ako nivo nije kompletiran
                if (remainingMoves <= 0) {
                    console.log("No remaining moves. Checking game over conditions.");
                    setTimeout(() => {
                        if (isHybridMode) {
                            gameOverHybrid('moves');
                        } else if (isClassicMode) {
                            gameOverClassic();
                        }
                    }, 624);
                    return;
                }
            }

            // Nastavak igre
            setTimeout(() => {
                resetBoard();
                if (!robotPlaying) {
    isBoardLocked = false;};
            }, level.matchDelayTime);
        }

        // Resetovanje brojača uzastopnih pogrešnih mečeva ako je asistencija uključena
        if (level.assistMode === "event" || level.assistMode === "both") {
            console.log("Resetting consecutiveWrongMatches due to successful match.");
            consecutiveWrongMatches = 0;
        }

    } else {
        console.log("Selected cards do not match.");

        // Neuspješan meč
        mismatchSound.play();
        consecutiveMatches = 0;
        streakCards = [];

        // Ažuriranje rezultata
        score -= Math.round(level.nonMatchedPenalty * pointsModifier * ((currentLevelIndex / 30) + 1));
        updateScoreDisplay(score, 'decrease');

        // Vizualni efekti za pogrešan meč
        handleErrorSeries(selectedCards.slice());
        isBoardLocked = true;

        setTimeout(() => {
            resetBoard();
            if (!robotPlaying) {
    isBoardLocked = false;};
        }, level.mismatchTime);

        // Smanjivanje poteza za neuspješan meč u Classic ili Hybrid modu
        if (!isTimeAttackMode && ((isClassicMode && level.moves > 0) || isHybridMode)) {            
            remainingMoves--;
            console.log(`Moves remaining after mismatch: ${remainingMoves}`);
            if (isHybridMode) {
                movesHybrid.textContent = remainingMoves;
            } else {
                document.getElementById('moves').textContent = remainingMoves;
            }

            // Provjera da li su preostali potezi 0
            if (remainingMoves <= 0) {
                console.log("No remaining moves after mismatch.");
                if (matchedCards === totalMatchingCards) {
                    // Ako su sve kartice uparene, prelazimo na sljedeći nivo
                    setTimeout(() => {
                        levelUp(); // Prelazak na sljedeći nivo
                        if (!robotPlaying) {
    isBoardLocked = false;};
                        if (assistIntervalId) {
                            clearInterval(assistIntervalId);
                            assistIntervalId = null;
                        }
                    }, 500);
                } else {
                    // Nije sve upareno, igra se završava
                    if (isHybridMode) {
                        setTimeout(() => gameOverHybrid('moves'), level.flipBackTimeUnpair);
                    } else {
                        setTimeout(gameOverClassic, level.flipBackTimeUnpair);
                    }
                }
                return;
            }
        }

        // Ažuriranje brojača uzastopnih pogrešnih mečeva ako je asistencija uključena
        if (level.assistMode === "event" || level.assistMode === "both") {
            consecutiveWrongMatches += 1;
            console.log(`Consecutive wrong matches: ${consecutiveWrongMatches}`);
            if (consecutiveWrongMatches >= level.assistTriggerConsecutiveFails) {
                console.log("Consecutive wrong matches threshold reached. Triggering assistance.");
                revealAssistanceCards();
                consecutiveWrongMatches = 0;
            }
        }
    }

    // Reset selectedCards
    selectedCards = [];
}

let brojacstreak = 0;
function flashStreakCards() {
    brojacstreak++;
    if ("vibrate" in navigator) {
            navigator.vibrate(150,30,150);
        } else {
            console.log("Vibration not supported on this device.");
        }
    triggerScreenShakestreak();
    // Add flash-yellow class to streak cards and manage timeouts per card
    streakCards.forEach(card => {
        // Add 'flash-yellow' class
        card.classList.add('flash-yellow');
        card.style.backgroundImage = "none";
        
        // Clear any existing timeout for this card
        if (card.flashYellowTimeout) {
            clearTimeout(card.flashYellowTimeout);
        }
        
        // Set a new timeout to remove 'flash-yellow' after 1 second
        card.flashYellowTimeout = setTimeout(() => {
            card.classList.remove('flash-yellow');
            card.flashYellowTimeout = null;
        }, 1221); // Flash duration in milliseconds
    });
}
function flashBackground() {
    // Create a temporary overlay
    const flashOverlay = document.createElement('div');
    flashOverlay.classList.add('flash-overlay');
    document.body.appendChild(flashOverlay);
    // Remove the overlay after 400 ms
    setTimeout(() => {
        flashOverlay.remove();
    }, 1200);
}
function resetBoard() {
    selectedCards = [];
}
function updateScoreDisplay(newScore, changeType) {
    let scoreElement;
    if (isHybridMode) {
        scoreDisplayHybrid.textContent = newScore;
        scoreElement = scoreDisplayHybrid;
    } else if (isClassicMode) {
        // Ažuriraj prikaz poena u klasičnom modu
        scoreDisplayMoves.textContent = newScore;
        scoreElement = scoreDisplayMoves;
    } else {
        // Ažuriraj prikaz poena u standardnom modu
        scoreDisplayTimer.textContent = newScore;
        scoreElement = scoreDisplayTimer;
    }
    // Dodaj efekat animacije
    if (changeType === 'increase') {
        scoreElement.classList.add('score-up');
    } else if (changeType === 'decrease') {
        scoreElement.classList.add('score-down');
    }
    // Ukloni klasu nakon što animacija završi
    setTimeout(() => {
        scoreElement.classList.remove('score-up', 'score-down');
    }, 500); // 500ms treba biti jednako trajanju animacije u CSS-u
}
function triggerGlowEffect() {
    const gameBoard = document.getElementById('game-board');
    gameBoard.classList.add('glow');
    setTimeout(() => {
        gameBoard.classList.remove('glow');
    }, 3000); // Glow for 3 seconds
}
function calculateTotalCards() {
    if (Array.isArray(level.grid)) {
        if (Array.isArray(level.grid[0])) {
            // Grid is a 2D array with 'k' and 'p' values
            let totalCards = 0;
            level.grid.forEach(row => {
                row.forEach(cell => {
                    if (cell === 'k') totalCards++;
                });
            });
            return totalCards;
        } else {
            // Grid is an array of numbers
            return level.grid.reduce((a, b) => a + b, 0);
        }
    } else {
        // Grid is an object with cols and rows
        return level.grid.cols * level.grid.rows;
    }
}
function timeUp() {
    stopRobotPlay();
    if (levelCompleted) return;

    da_li_je_game_over = true;
    saveCurrentResult();
    if (isHybridMode) {
        gameOverHybrid("time");
        return;
    }

    if (matchedCards === calculateTotalCards()) {

        levelUp();
        return;
    }

    isBoardLocked = true;

    if (!isClassicMode) {
        setTimeout(() => {
            if (isTimeAttackMode) {
                clearInterval(timerInterval);
                timerInterval = null;

                let totalSeconds = Math.floor((Date.now() - startTime) / 1000);
                let tminutes = Math.floor(totalSeconds / 60);
                let tseconds = totalSeconds % 60;

                finalScoreTimeUp.innerHTML = `Trajanje igre:<br>${tminutes} m. i ${tseconds} s.<br>Ukupno: ${score} 💎`;
                gameOverTUSound.play();

                timeUpMsg.style.display = 'flex';
                timeUpMsg.style.position = 'absolute';
                timeUpMsg.style.top = '50%';
                timeUpMsg.style.left = '50%';
                timeUpMsg.style.transform = 'translate(-50%, -50%)';

                // Uklanjanje klase 'hidden' kako bi dugmići bili vidljivi u DOM-u
                continueButton.classList.remove('hidden');
                useLifeButton.classList.remove('hidden');
                restartButton.classList.remove('hidden');

                // Dodavanje klase 'hidden-button' za poluprovidne i neklikabilne dugmiće
                continueButton.classList.add('hidden-button');
                useLifeButton.classList.add('hidden-button');
                restartButton.classList.add('hidden-button');

                // Prikaz dugmića nakon 1500ms
                setTimeout(() => {
                    // U ovom režimu samo restart dugmić se prikazuje
                    restartButton.classList.remove('hidden-button');
                    restartButton.classList.add('visible-button');
                    console.log('Restart button je sada vidljiv i klikabilan.');
                }, 1500);
            } else {
                pauseTimer();
                isBoardLocked = true;
                document.body.style.backgroundColor = 'black';

                let totalCards = calculateTotalCards();
                let nonMatchedCards = totalCards - matchedCards;
                let penaltyPoints = Math.round((nonMatchedCards * level.penaltyPoints) + (currentLevelIndex + 1) * 9.5);
                let additionalSeconds = nonMatchedCards * 2;

                timeUpMsg.querySelector('h2').textContent = "Vrijeme isteklo!";
                finalScoreTimeUp.innerHTML = `Ukupno osvojeno:<br><span style="color: #adff2f;">${score} 💎</span>`;
                timeUpMsg.style.display = 'flex';
                timeUpMsg.style.position = 'absolute';
                timeUpMsg.style.top = '50%';
                timeUpMsg.style.left = '50%';
                timeUpMsg.style.transform = 'translate(-50%, -50%)';
                timeUpMsg.classList.add('fade-in');
                endSound.play();

                // Ažuriranje dugmića
                continueButton.textContent = `Nastavi igru (-${penaltyPoints} 💎)`;
                continueButton.dataset.penalty = penaltyPoints;
                continueButton.dataset.additionalSeconds = additionalSeconds;

                useLifeButton.dataset.additionalSeconds = additionalSeconds;

                // Uklanjanje klase 'hidden' kako bi dugmići bili vidljivi u DOM-u
                continueButton.classList.remove('hidden');
                useLifeButton.classList.remove('hidden');
                restartButton.classList.remove('hidden');

                // Dodavanje klase 'hidden-button' za poluprovidne i neklikabilne dugmiće
                continueButton.classList.add('hidden-button');
                useLifeButton.classList.add('hidden-button');
                restartButton.classList.add('hidden-button');

                // Prikaz dugmića nakon 1200ms
                setTimeout(() => {
                    if (score >= penaltyPoints) {
                        continueButton.classList.remove('hidden-button');
                        continueButton.classList.add('visible-button');
                        console.log('Continue button je sada vidljiv i klikabilan.');
                    }

                    if (lives > 0) {
                        useLifeButton.classList.remove('hidden-button');
                        useLifeButton.classList.add('visible-button');
                        console.log('Use Life button je sada vidljiv i klikabilan.');
                    }

                    restartButton.classList.remove('hidden-button');
                    restartButton.classList.add('visible-button');
                    console.log('Restart button je sada vidljiv i klikabilan.');
                }, 1900);
            }
        }, 500); // Početno kašnjenje prije prikaza poruke
    }
}

function gameOverClassic() {
    stopRobotPlay();
    saveCurrentResult();
    clearInterval(timerInterval);
    da_li_je_game_over = true;
    isBoardLocked = true;

    // Izračunavanje kaznenih bodova i dodatnih poteza
    let totalCards = calculateTotalCards();
    let nonMatchedCards = totalCards - matchedCards;
    let penaltyPoints = Math.round((nonMatchedCards * level.penaltyPoints) + (currentLevelIndex + 1) * 9.5);
    let additionalMoves = nonMatchedCards + (level.addMoves !== undefined ? level.addMoves : 2);

    // Ažuriranje teksta i atributa dugmića
    continueButton.textContent = `Nastavi igru (-${penaltyPoints} 💎)`;
    continueButton.dataset.penalty = penaltyPoints;
    continueButton.dataset.additionalMoves = additionalMoves;

    useLifeButton.dataset.additionalMoves = additionalMoves;

    // Postavljanje poruke za kraj igre
    timeUpMsg.querySelector('h2').textContent = "Nema više poteza!";
    finalScoreTimeUp.innerHTML = `Ukupno osvojeno:<br><span style="color: #adff2f;">${score} 💎</span>`;
    nomovesSound.play();

    timeUpMsg.style.display = 'flex';
    timeUpMsg.style.position = 'absolute';
    timeUpMsg.style.top = '50%';
    timeUpMsg.style.left = '50%';
    timeUpMsg.style.transform = 'translate(-50%, -50%)';

    // Uklanjanje klase 'hidden' kako bi dugmići bili vidljivi u DOM-u
    continueButton.classList.remove('hidden');
    useLifeButton.classList.remove('hidden');
    restartButton.classList.remove('hidden');

    // Dodavanje klase 'hidden-button' za poluprovidne i neklikabilne dugmiće
    continueButton.classList.add('hidden-button');
    useLifeButton.classList.add('hidden-button');
    restartButton.classList.add('hidden-button');

    // Prikaz dugmića nakon 1200ms
    setTimeout(() => {
        if (score >= penaltyPoints) {
            continueButton.classList.remove('hidden-button');
            continueButton.classList.add('visible-button');
            console.log('Continue button je sada vidljiv i klikabilan.');
        }

        if (lives > 0) {
            useLifeButton.classList.remove('hidden-button');
            useLifeButton.classList.add('visible-button');
            console.log('Use Life button je sada vidljiv i klikabilan.');
        }

        restartButton.classList.remove('hidden-button');
        restartButton.classList.add('visible-button');
        console.log('Restart button je sada vidljiv i klikabilan.');
    }, 1900);

    // Resetovanje selektovanih kartica ako ih ima
    if (selectedCards.length > 0) {
        selectedCards.forEach(card => {
            if (!card.classList.contains('matched')) {
                card.classList.remove('selected');
                card.classList.remove('flipped');
            }
        });
        selectedCards.length = 0;
    }

    // Održavanje stanja svih uparenih kartica
    const allMatchedCards = document.querySelectorAll('.card.matched');
    allMatchedCards.forEach(card => {
        card.classList.add('flipped');
    });
}

function gameOverHybrid(reason) {
    stopRobotPlay();
    saveCurrentResult();
    clearInterval(timerInterval);
    isBoardLocked = true;
    da_li_je_game_over = true;

    // Postavljanje poruke i zvuka na osnovu razloga za game over
    if (reason === 'time') {
        timeUpMsg.querySelector('h2').textContent = "Vrijeme isteklo!";
        endSound.play();
    } else if (reason === 'moves') {
        timeUpMsg.querySelector('h2').textContent = "Nema više poteza!";
        nomovesSound.play();
    }

    finalScoreTimeUp.innerHTML = `Ukupno osvojeno:<br><span style="color: #adff2f;">${score} 💎</span>`;
    timeUpMsg.style.display = 'flex';
    timeUpMsg.style.position = 'absolute';
    timeUpMsg.style.top = '50%';
    timeUpMsg.style.left = '50%';
    timeUpMsg.style.transform = 'translate(-50%, -50%)';

    // Izračunavanje kaznenih bodova, dodatnih poteza i dodatnih sekundi
    let totalCards = calculateTotalCards();
    let nonMatchedCards = totalCards - matchedCards;
    let penaltyPoints = Math.round((nonMatchedCards * level.penaltyPoints) + (currentLevelIndex + 1) * 9.5);
    let additionalMoves = nonMatchedCards + (level.addMoves !== undefined ? level.addMoves : 2);
    let additionalSeconds = nonMatchedCards * 2;

    // Ažuriranje teksta i atributa dugmića
    continueButton.textContent = `Nastavi igru (-${penaltyPoints} 💎)`;
    continueButton.dataset.penalty = penaltyPoints;
    continueButton.dataset.additionalMoves = additionalMoves;
    continueButton.dataset.additionalSeconds = additionalSeconds;

    useLifeButton.dataset.additionalMoves = additionalMoves;
    useLifeButton.dataset.additionalSeconds = additionalSeconds;

    // Uklanjanje klase 'hidden' kako bi dugmići bili vidljivi u DOM-u
    continueButton.classList.remove('hidden');
    useLifeButton.classList.remove('hidden');
    restartButton.classList.remove('hidden');

    // Dodavanje klase 'hidden-button' za poluprovidne i neklikabilne dugmiće
    continueButton.classList.add('hidden-button');
    useLifeButton.classList.add('hidden-button');
    restartButton.classList.add('hidden-button');

    // Prikaz dugmića nakon 1200ms
    setTimeout(() => {
        if (score >= penaltyPoints) {
            continueButton.classList.remove('hidden-button');
            continueButton.classList.add('visible-button');
            console.log('Continue button je sada vidljiv i klikabilan.');
        }

        if (lives > 0) {
            useLifeButton.classList.remove('hidden-button');
            useLifeButton.classList.add('visible-button');
            console.log('Use Life button je sada vidljiv i klikabilan.');
        }

        restartButton.classList.remove('hidden-button');
        restartButton.classList.add('visible-button');
        console.log('Restart button je sada vidljiv i klikabilan.');
    }, 1900);

    // Pauziranje igre
    pauseTimer();
}



function startNextLevel() {
    consecutiveMatches = 0;
    let gameBoardElement = document.getElementById('game-board');
    gameBoardElement.classList.remove('rotate-center');
  
    levelCompleteMsg.style.display = 'none';
    gameBoard.style.display = 'grid';
    infoPanel.style.display = 'flex';
    currentLevelIndex++;
    if (currentLevelIndex >= levels.length) {
        // If all levels are completed
        gameCompletedMsg.style.display = 'block';
        // Update the content of `final-score-game-over` with the final score
        finalScoreGameOver.innerHTML = `<p style="font-size: 2rem;">Ukupno osvojeni poeni: ${score}</p>`;
        // Add bounce effect animation to the final score
        finalScoreGameOver.classList.add('bounce-effect');
        if (bgMusic) {
            bgMusic.pause();
            bgMusic.currentTime = 0;
        }
        return;
    }
    level = levels[currentLevelIndex];
    if (bgMusic) {
        bgMusic.pause();
        bgMusic.currentTime = 0;
    }
    // Start background music for the new level
    if (level.music) {
        bgMusic = new Audio(level.music);
        bgMusic.loop = true;
        bgMusic.volume = 1; // You can adjust the volume
        bgMusic.play();
    }
    updateInfoTextColor();
}
function clearAllTimeouts() {
    if (helpRevealTimeout) {
        clearTimeout(helpRevealTimeout);
        helpRevealTimeout = null;
    }
    // Clear any other timeouts if necessary
}
function clearCardFlipTimeouts() {
    const allCards = document.querySelectorAll('.card');
    allCards.forEach(card => {
        if (card.flipBackTimeout) {
            clearTimeout(card.flipBackTimeout);
            card.flipBackTimeout = null;
        }
    });
}
function levelUp() {
    stopRobotPlay();
    resetKupovineNivo();

let preostaloVrijemeBonus; let uzastopnoSlaganjeBonus; let bonusPoints; let zivotbonus; let prethodnipoeni; let radnipoeni; let preostaliPoteziBonus;
prethodnipoeni = score2;
radnipoeni = score - score2;

let numUniqueCards = globalTotalMatchingCards / level.matchCards;
if (numUniqueCards > 0) {
suspiciousRatio = consecutiveMatches / numUniqueCards;
}

// Provjera sumnjivog ponasanja nakon 20. levela (odnosno levelIndex >= 20)
if (currentLevelIndex >= 20 && suspiciousRatio >= 0.7) {
suspiciousActive = true;
suspiciousPenaltyCount++;}
continueCount = 0;

document.body.style.filter = 'grayscale(0%)';
cancelOverlay();

// Clear timers and intervals
if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
}
setTimeout(revealAllCards, 400);
clearAllIntervals();
level.currentAssistCount = 0;
resetSpecialEffects();

removePassiveOverlay();
addPassiveOverlay();
// level.assistCardsCount = 0;
isBoardLocked = true;
fadeOutAllAudio(1200);

if (level.assistMode === "event" || level.assistMode === "both") {
    consecutiveWrongMatches = 0;
}

// Play level-up animations and sounds based on the mode
if (isTimeAttackMode) {
    da_li_je_game_over = false;
    // Time Attack Mode: Apply hiding animation
    cardHideSound.play();
    if ("vibrate" in navigator) {
        navigator.vibrate(448);
    } else {
        console.log("Vibration not supported on this device.");
    }

    // Add hiding animation
    let gameBoardElement = document.getElementById('game-board');
    gameBoardElement.classList.add('hiding');
    setTimeout(() => {
        gameBoardElement.classList.remove('hiding');
    }, 748);
} else {
    // Other modes: confetti and other effects
    confetti({
        particleCount: 824,
        spread: 480,
        origin: { y: 0.4 },
        scalar: 2
    });
    isBoardLocked = true;
    levelUpSound.volume = 1.0;
    levelUpSound.play();

    // Apply rotate-center effect
    let gameBoardElement = document.getElementById('game-board');
    gameBoardElement.classList.add('rotate-center');
}

// Remove 'rotated' class if necessary
if (rmc === true) {
    gameBoard.classList.remove('rotated');
    rmc = false;
}

isBoardLocked = true; // Lock the board during transition

// Determine the next level index and the next level object
let nextLevelIndex = currentLevelIndex + 1;
let nextLevel = levels[nextLevelIndex]; // Assuming 'levels' is your array of level objects

// References to DOM elements
const levelUpMsg = document.getElementById('level-up-msg');
const finalScoreOverlay = document.getElementById('final-score-overlay');

const gameCompletedMsg = document.getElementById('game-completed-msg');

nextLevelBtnOverlay.classList.remove('visible-button');
nextLevelBtnOverlay.classList.add('hidden-button');

// Initialize message variable
let levelCompletionMessage = '';

// Handle different game modes
if (isHybridMode) {
    // Hybrid Mode Logic
    let bonusPoints = 0;
    if (bns === false || currentLevelIndex >= 20 && suspiciousRatio >= 0.7) {
        preostaliPoteziBonus = preostaloVrijemeBonus = uzastopnoSlaganjeBonus = 0; zivotbonus = duplibonus * duplibonusskroz * lives * 63;
        bonusPoints = zivotbonus;
    } else {
        preostaliPoteziBonus = duplibonus * duplibonusskroz * Math.round(remainingMoves * (level.MultiRemainMoves) / 2);
        preostaloVrijemeBonus = duplibonus * duplibonusskroz * Math.round((remainingTime * level.MultiRemainTime) / 2)
        uzastopnoSlaganjeBonus = duplibonus * duplibonusskroz * Math.round(brojacstreak * (currentLevelIndex + 1) * 7.42);
        zivotbonus = duplibonus * duplibonusskroz * lives * 63;

// Izračunaj ukupno bonus poena
        //bonusPoints = preostaliPoteziBonus + uzastopnoSlaganjeBonus + zivotbonus;
        bonusPoints = preostaliPoteziBonus + preostaloVrijemeBonus + uzastopnoSlaganjeBonus + zivotbonus;
    
    }
    score += bonusPoints;
        medaljap = score - prethodnipoeni;
    loadInitialGold();
    zivotna_provjera(); // Life check function
    updateScoreDisplay(score, 'increase');

    // Display bonus points
    levelCompletionMessage = `<p>Osvojeno: <br><span style="color: lightgreen;">${bonusPoints}</span> bonus 💎</p>
                              <p>UKUPNO: <span style="color: lightgreen;">${score}</span> 💎</p>`;
    finalScoreOverlay.innerHTML = levelCompletionMessage;

    if (nextLevelIndex >= levels.length) {
        // Game completed
        levelUpMsg.style.display = 'none';
        gameCompletedMsg.style.display = 'block';
        finalScoreGameOver.innerHTML = `<p style="font-size: 2rem;">Bravo!<br>Igra je završena.<br>Ukupno: ${score} 💎</p>`;
        if (bgMusic) {
            bgMusic.pause();
            bgMusic.currentTime = 0;
        }
        levelUpSound.pause();
        gameOverSound.play();
        return;
    } else {
        // More levels are available
        const lines = [
            `<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Preostalo vrijeme: <span style="color: lightgreen;">${preostaloVrijemeBonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Preostali potezi: <span style="color: lightgreen;">${preostaliPoteziBonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Uzastopno slaganje: <span style="color: lightgreen;">${uzastopnoSlaganjeBonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Životi: <span style="color: lightgreen;">${zivotbonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.6em;"><span style="color: yellow;">Ukupan bonus:</span> <span style="color: lightgreen;">${bonusPoints}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Prethodno: <span style="color: lightgreen;">${prethodnipoeni}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Ukupno za slaganje: <span style="color: lightgreen;">${radnipoeni}</span> 💎</p>`,
`<hr class="hidden-line">`,
`<p id="final-score" class="dynamic-line hidden-line" style="font-size: 0.7em;">UKUPNO: <span style="color: lightgreen;">${score}</span> 💎</p>`
];
finalScoreOverlay.style.opacity = 1; // Pobrinemo se da je vidljivo
//const levelUpSound = new Audio('sounds/levelup.mp3');
//levelUpSound.play();
addLinesWithAnimation(finalScoreOverlay, lines, 150);

// Prikaži nivo poruku
levelUpMsg.style.display = 'block';

// Dodaj animaciju pulsiranja na finalni skor
setTimeout(() => {
const finalScore = document.getElementById("final-score");
if (finalScore) {
    finalScore.classList.add("pulse2");
}
}, lines.length * 150); // Pulsiranje počinje nakon što se sve linije dodaju
setTimeout(() => {
nextLevelBtnOverlay.classList.remove('hidden-button');
nextLevelBtnOverlay.classList.add('visible-button');
nextLevelBtnOverlay.innerHTML = `Klikni za sljedeći nivo`;
}, lines.length * 150 + 600); // vrijeme za pojavu dugmeta
        nextLevelBtnOverlay.onclick = () => {
            fadeOutSound(levelUpSound, 1200);
            levelUpMsg.style.display = 'none';

            // Show notification before starting the next level
            if (isTimeAttackMode) {
                // Update level index and proceed directly
                currentLevelIndex = nextLevelIndex;
                level = levels[currentLevelIndex];
                proceedToNextLevel();
            } else {
                // Show the notification first
                showLevelNotification(nextLevel, () => {
                    // Update level index after notification is dismissed
                    currentLevelIndex = nextLevelIndex;
                    level = levels[currentLevelIndex];
                    proceedToNextLevel();
                });
            }
        };
    }
} else if (isTimeAttackMode) {
    // Time Attack Mode Handling
    currentTimeAttackLevelIndex++;
    if (currentTimeAttackLevelIndex >= timeAttackLevels.length) {
        // All Time Attack levels completed
        gameCompletedMsg.style.display = 'block';
        // Calculate total playtime
        let totalSeconds = Math.floor((Date.now() - startTime) / 1000);
        let tminutes = Math.floor(totalSeconds / 60);
        let tseconds = totalSeconds % 60;
        // Update final score with playtime
        finalScoreGameOver.innerHTML = `<p style="font-size: 2rem;">Ukupno osvojeni poeni: ${score}</p><p>Ukupno vrijeme igranja: ${tminutes} m. i ${tseconds} s.</p>`;
        // Add bounce effect
        finalScoreGameOver.classList.add('bounce-effect');
        if (bgMusic) {
            bgMusic.pause();
            bgMusic.currentTime = 0;
        }
        // Play game over sound
        gameOverTUSound.play();
        return;
    }
    level = timeAttackLevels[currentTimeAttackLevelIndex];
    startTimeAttackLevel();
} else if (isClassicMode) {
    // Classic Mode Logic
    let bonusPoints = 0;
    if (bns === false || currentLevelIndex >= 20 && suspiciousRatio >= 0.7) {
        preostaliPoteziBonus = preostaloVrijemeBonus = uzastopnoSlaganjeBonus = 0; zivotbonus = duplibonus * duplibonusskroz * lives * 63;
        bonusPoints = zivotbonus;
    } else {
        preostaliPoteziBonus = duplibonus * duplibonusskroz * Math.round(remainingMoves * (level.MultiRemainMoves));
        uzastopnoSlaganjeBonus = duplibonus * duplibonusskroz * Math.round(brojacstreak * (currentLevelIndex + 1) * 7.42);
        zivotbonus = duplibonus * duplibonusskroz * lives * 63;

// Izračunaj ukupno bonus poena
        bonusPoints =  preostaliPoteziBonus + uzastopnoSlaganjeBonus + zivotbonus;
    }
    // Add Bonus Points to Score
    score += bonusPoints;
    medaljap = score - prethodnipoeni;
    loadInitialGold();

    zivotna_provjera();
    updateScoreDisplay(score, 'increase');

    if (nextLevelIndex >= levels.length) {
        // All Classic levels completed
        levelUpMsg.style.display = 'none';
        gameCompletedMsg.style.display = 'block';
        finalScoreGameOver.innerHTML = `<p style="font-size: 2rem;">Bravo!<br>Igra je završena.<br>Ukupno: ${score} 💎</p>`;
        // Stop music and play game over sound
        if (bgMusic) {
            bgMusic.pause();
            bgMusic.currentTime = 0;
        }
        levelUpSound.pause();
        gameOverSound.play();
        return;
    } else {
        const lines = [
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Preostali potezi: <span style="color: lightgreen;">${preostaliPoteziBonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Uzastopno slaganje: <span style="color: lightgreen;">${uzastopnoSlaganjeBonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Životi: <span style="color: lightgreen;">${zivotbonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.6em;"><span style="color: yellow;">Ukupan bonus:</span> <span style="color: lightgreen;">${bonusPoints}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Prethodno: <span style="color: lightgreen;">${prethodnipoeni}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Ukupno za slaganje: <span style="color: lightgreen;">${radnipoeni}</span> 💎</p>`,
`<hr class="hidden-line">`,
`<p id="final-score" class="dynamic-line hidden-line" style="font-size: 0.7em;">UKUPNO: <span style="color: lightgreen;">${score}</span> 💎</p>`
];
finalScoreOverlay.style.opacity = 1; // Pobrinemo se da je vidljivo
//const levelUpSound = new Audio('sounds/levelup.mp3');
//levelUpSound.play();
addLinesWithAnimation(finalScoreOverlay, lines, 150);

// Prikaži nivo poruku
levelUpMsg.style.display = 'block';

// Dodaj animaciju pulsiranja na finalni skor
setTimeout(() => {
const finalScore = document.getElementById("final-score");
if (finalScore) {
    finalScore.classList.add("pulse2");
}
}, lines.length * 150); // Pulsiranje počinje nakon što se sve linije dodaju
setTimeout(() => {
nextLevelBtnOverlay.classList.remove('hidden-button');
nextLevelBtnOverlay.classList.add('visible-button');
nextLevelBtnOverlay.innerHTML = `Klikni za sljedeći nivo`;
}, lines.length * 150 + 600); // vrijeme za pojavu dugmeta
        nextLevelBtnOverlay.onclick = () => {
            fadeOutSound(levelUpSound, 1200);
            levelUpMsg.style.display = 'none';

            // Show notification before starting the next level
            if (isTimeAttackMode) {
                // Update level index and proceed directly
                currentLevelIndex = nextLevelIndex;
                level = levels[currentLevelIndex];
                proceedToNextLevel();
            } else {
                // Show the notification first
                showLevelNotification(nextLevel, () => {
                    // Update level index after notification is dismissed
                    currentLevelIndex = nextLevelIndex;
                    level = levels[currentLevelIndex];
                    proceedToNextLevel();
                });
            }
        };
    }
} else {
    // Standard/Practice Mode Handling
    let bonusPoints = 0;
    if (bns === false || currentLevelIndex >= 20 && suspiciousRatio >= 0.7) {
        preostaliPoteziBonus = preostaloVrijemeBonus = uzastopnoSlaganjeBonus = 0; zivotbonus = duplibonus * duplibonusskroz * lives * 63;
        bonusPoints = zivotbonus;
    } else {
preostaloVrijemeBonus = duplibonus * duplibonusskroz * Math.round(remainingTime * (level.MultiRemainTime));
uzastopnoSlaganjeBonus = duplibonus * duplibonusskroz * Math.round(brojacstreak * (currentLevelIndex + 1) * 7.42);
zivotbonus = duplibonus * duplibonusskroz * lives * 63;
bonusPoints = preostaloVrijemeBonus + uzastopnoSlaganjeBonus + zivotbonus;
    }
    // Add Bonus Points to Score
    score += bonusPoints;
    medaljap = score - prethodnipoeni;
    loadInitialGold();
    zivotna_provjera();
    updateScoreDisplay(score, 'increase');

    if (isPracticeMode) {
        // Practice Mode Completion
        finalScoreOverlay.innerHTML = `<p>Vježba je završena! Osvojili ste ukupno ${score} poena.</p>`;
        levelUpMsg.style.display = 'block';
        nextLevelBtnOverlay.textContent = 'Završi igru';
        nextLevelBtnOverlay.onclick = () => {
            levelUpMsg.style.display = 'none';
            gameCompletedMsg.style.display = 'block';
            finalScoreGameOver.innerHTML = `<p style="font-size: 2rem;">Vježba je završena! Osvojili ste ukupno ${score} poena.</p>`;
            levelUpSound.pause();
            levelUpSound.currentTime = 0;
            gameOverSound.play();
        };
    } else {
        if (nextLevelIndex >= levels.length) {
            // All Standard levels completed
            levelUpMsg.style.display = 'none';
            gameCompletedMsg.style.display = 'block';
            finalScoreGameOver.innerHTML = `<p style="font-size: 2rem;">Bravo!<br>Igra je završena.<br>Ukupno: ${score} 💎</p>`;
            if (bgMusic) {
                bgMusic.pause();
                bgMusic.currentTime = 0;
            }
            levelUpSound.pause();
            gameOverSound.play();
            return;
        } else {
          //  nextLevelBtnOverlay.classList.add('hidden-button');
            const lines = [
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Preostalo vrijeme: <span style="color: lightgreen;">${preostaloVrijemeBonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Uzastopno slaganje: <span style="color: lightgreen;">${uzastopnoSlaganjeBonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Životi: <span style="color: lightgreen;">${zivotbonus}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.6em;"><span style="color: yellow;">Ukupan bonus:</span> <span style="color: lightgreen;">${bonusPoints}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Prethodno: <span style="color: lightgreen;">${prethodnipoeni}</span> 💎</p>`,
`<p class="dynamic-line hidden-line" style="font-size: 0.5em;">Ukupno za slaganje: <span style="color: lightgreen;">${radnipoeni}</span> 💎</p>`,
`<hr class="hidden-line">`,
`<p id="final-score" class="dynamic-line hidden-line" style="font-size: 0.7em;">UKUPNO: <span style="color: lightgreen;">${score}</span> 💎</p>`
];
finalScoreOverlay.style.opacity = 1; // Pobrinemo se da je vidljivo
//const levelUpSound = new Audio('sounds/levelup.mp3');
//levelUpSound.play();
addLinesWithAnimation(finalScoreOverlay, lines, 150);

// Prikaži nivo poruku
levelUpMsg.style.display = 'block';

// Dodaj animaciju pulsiranja na finalni skor
setTimeout(() => {
const finalScore = document.getElementById("final-score");
if (finalScore) {
    finalScore.classList.add("pulse2");
}
}, lines.length * 150); // Pulsiranje počinje nakon što se sve linije dodaju
setTimeout(() => {
nextLevelBtnOverlay.classList.remove('hidden-button');
nextLevelBtnOverlay.classList.add('visible-button');
nextLevelBtnOverlay.innerHTML = `Klikni za sljedeći nivo`;
}, lines.length * 150 + 600); // vrijeme za pojavu dugmeta
            nextLevelBtnOverlay.onclick = () => {
                fadeOutSound(levelUpSound, 1200);
                levelUpMsg.style.display = 'none';
             

                // Show notification before starting the next level
                if (isTimeAttackMode) {
                    // Update level index and proceed directly
                    currentLevelIndex = nextLevelIndex;
                    level = levels[currentLevelIndex];
                    proceedToNextLevel();
                } else {
                    // Show the notification first
                    showLevelNotification(nextLevel, () => {
                        // Update level index after notification is dismissed
                        currentLevelIndex = nextLevelIndex;
                        level = levels[currentLevelIndex];
                        
                        proceedToNextLevel();
                    });
                }
            };
        }
    }
}
kupljenipotezi = 0; kupljenovrijeme = 0; duplipoeni = 1; duplibonus = 1;
}

function addLinesWithAnimation(container, lines, delay) {
    container.innerHTML = ""; // Resetuj sadržaj
    lines.forEach((line, index) => {
        const tempDiv = document.createElement("div");
        tempDiv.innerHTML = line;
        const lineElement = tempDiv.firstChild;

        setTimeout(() => {
            container.appendChild(lineElement); // Dodaj liniju
            requestAnimationFrame(() => {
                lineElement.classList.remove("hidden-line"); // Ukloni klasu sakrivanja
                lineElement.classList.add("visible-line"); // Dodaj klasu prikazivanja
            });
        }, index * delay);
    });
}
function updateUIForCurrentMode() {
    // Hide all headers first
    headerContainer.style.display = 'none';
    headerContainerHybrid.style.display = 'none';

    // Hide all timer and moves containers
    document.querySelector('.timer-container').style.display = 'none';
    document.querySelector('.moves-container').style.display = 'none';
    document.querySelector('.hybrid-container').style.display = 'none';

    // Show the appropriate header and containers based on mode
    if (isHybridMode) {
        headerContainerHybrid.style.display = 'flex';
        document.querySelector('.hybrid-container').style.display = 'block';
    } else {
        headerContainer.style.display = 'flex';
        if (isClassicMode) {
            document.querySelector('.moves-container').style.display = 'block';
        } else if (isTimeAttackMode) {
            document.querySelector('.timer-container').style.display = 'block';
            // Hide the lives display in Time Attack mode
            const livesDisplay = document.getElementById('lives-display');
            if (livesDisplay) {
                livesDisplay.style.display = 'none';
            }
        } else {
            // Ensure lives display is shown in other modes
            const livesDisplay = document.getElementById('lives-display');
            if (livesDisplay) {
                livesDisplay.style.display = 'inline';
            }
        }
    }
    // Update level number display
    if (isHybridMode) {
        levelDisplayHybrid.textContent = isPracticeMode ? '-' : currentLevelIndex + 1;
    } else if (isTimeAttackMode){
        levelDisplay.textContent ='👍';
    } else {
        levelDisplay.textContent = isPracticeMode ? '-' : currentLevelIndex + 1;
    }

    // Update other UI elements if necessary
    updateInfoTextColor();
}


function resetInfoPanelStyles() {
    consecutiveWrongMatches = 0;
    const headerContainer = document.getElementById('header-container');
    headerContainer.style.display = 'flex';
    headerContainer.style.visibility = 'visible';
    headerContainer.style.opacity = '1';
    headerContainer.style.zIndex = 'auto';
    const elements = headerContainer.querySelectorAll('*');
    elements.forEach((element) => {
        element.style.display = '';
        element.style.visibility = '';
        element.style.opacity = '';
        element.style.zIndex = '';
        element.style.color = '';
    });
    // Ukloni "Klasika" specifične klase
    infoPanel.classList.remove('classic-mode');
}
function resetGame() {
    if (continueCount >= maxContinues) {
            disableContinueButton();
        }
    scorep = medaljap = 0; updatePlayerName();
    resetShop();
    let kupljenoprikazivanjeskroz = 0;
let kupljenovrijemeskroz = 0;
let kupljenipoteziskroz = 0;
let kupljenoprikazivanje = 0;
let kupljenovrijeme = 0;
let kupljenipotezi = 0;
let duplipoeniskroz = 1;
let duplipoeni = 1;
    destroyAllTimers();
    brojacstreak = 0;
    saveCurrentResult();
    cancelOverlay();
    da_li_je_game_over = false;
    provjerateme();
    const backgroundLayer = document.getElementById("background-layer");
const transitionLayer = document.getElementById("transition-layer");
    backgroundLayer.style.display = "block"; // ili "flex" ako je ranije bio fleksibilan prikaz
transitionLayer.style.display = "block";
milestone = 0;
    document.body.style.filter = 'grayscale(0%)';
   // removeAllOverlays();
    resetSpecialEffects();
    fadeOutAllAudio(1200);
    document.getElementById('header-container-hybrid').style.display = 'none';
    bns = true;
    rmc = false;
    levelCompleted = false;
   
    gameBoard.classList.remove('rotated');
    clearAllIntervals();
    timerInterval = null;
    if (assistIntervalId) {
        clearInterval(assistIntervalId);
        assistIntervalId = null;
    }
    if (level) {
        level.currentAssistCount = 0;
    }
    resetInfoPanelStyles();
    clearInterval(timerInterval);
    consecutiveMatches = 0;
    consecutiveWrongMatches = 0;
    // Reset all mode flags
    isBombMode = false; // Reset Bomb Mode flag
    isHybridMode = false;
    if (isTimeAttackMode){
        syncLocalStorageWithServer(); 
    }
    isTimeAttackMode = false;
    timeAttackRemainingTime = INITIAL_TIME_ATTACK_TIME;
    currentTimeAttackLevelIndex = 0;
    isClassicMode = false;
    isPracticeMode = false; // Reset practice mode
    // Reset levels
    //levels = elevels; // Clear levels array
    currentLevelIndex = 0;
    level = null;
    score = 0;
    matchedCards = 0;
    selectedCards = [];
    isBoardLocked = false;
    remainingTime = 0;
    remainingMoves = 0;
    isPaused = false;
    logo.style.display = 'block';
    headerContainer.style.display = 'none';
    gameBoard.style.display = 'none';
    infoPanel.style.display = 'none';
    document.body.style.backgroundColor = '#f4f4f9';
    startGameBtn.style.display = 'block';
    playerInfoDiv.classList.remove("hidden");
    BombBtn.style.display = 'inline-block';
    practiceBtn.style.display = 'block';
    timeAttackBtn.style.display = 'block';
    classicModeBtn.style.display = 'block'; // Show "Classic" button
    instructionsBtn.style.display = 'block';
    gameBoard.innerHTML = '';
    timeUpMsg.style.display = 'none';
    restartButton.classList.add('hidden');
    continueButton.classList.add('hidden'); // Hide continue button
    [continueButton, useLifeButton, restartButton].forEach(button => {
        button.classList.add('hidden');
        button.classList.remove('visible-button', 'hidden-button');
    });
    levelCompleteMsg.style.display = 'none';
    gameCompletedMsg.style.display = 'none';
    pauseOverlay.style.display = 'none';
    difficultySelection.style.display = 'none'; // Hide difficulty selection
    selectedDifficulty = null; // Reset selected difficulty
    let gameBoardElement = document.getElementById('game-board');
    gameBoardElement.classList.remove('rotate-center');
    resetStartScreen();
    resetToStartBackground();
    // Exit fullscreen mode
   // closeFullscreen();

}
function resetToStartBackground() {
    const backgroundLayer = document.getElementById("background-layer");
    const transitionLayer = document.getElementById("transition-layer");

    // Postavi početnu sliku na transitionLayer za fade-in efekat
    let startBackground = `backgrounds/poz${tema}.jpg`; // Prilagodite naziv početne slike
    console.log("Resetovanje na početnu sliku:", startBackground);

    transitionLayer.style.backgroundImage = `url(${startBackground})`;
    transitionLayer.style.opacity = 1; // Fade-in efekat za početnu sliku

    // Nakon što fade-in završi, ažuriraj backgroundLayer i sakrij transitionLayer
    setTimeout(() => {
        backgroundLayer.style.backgroundImage = `url(${startBackground})`;
        transitionLayer.style.opacity = 0; // Sakrij transitionLayer nakon tranzicije
    }, 500); // Vrijeme fade-in efekta
}




function pauseGame() {
    if (isPaused || da_li_je_game_over || robotPlaying) return;
    
    isPaused = true;
    clearInterval(timerInterval);
    pauseOverlay.style.display = 'block';
}
function resumeGame() {
    isPaused = false;
    pauseOverlay.style.display = 'none';
    da_li_je_game_over = false;
   if (isClassicMode){
    clearInterval(timerInterval);
    timerInterval = null;
        return;
    }
    timerInterval = setInterval(() => {
        if (isTimeAttackMode) {
            timeAttackRemainingTime--;
            remainingTime = timeAttackRemainingTime;
            timerDisplay.textContent = remainingTime;
            if (remainingTime <= 5 && remainingTime >= 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }
        } else if (isHybridMode) {
            remainingTime--;
            timerHybrid.textContent = remainingTime;
            if (remainingTime <= 5 && remainingTime >= 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }
        } else {
            remainingTime--;
            timerDisplay.textContent = remainingTime;
            if (remainingTime <= 5 && remainingTime >= 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }
        }
        if (remainingTime === 0 && !levelCompleted) {      
        timeUp();
        }
    }, 1000);
}

// Funkcije za fullscreen mod
function openFullscreen() {
    removePassiveOverlay();
    let elem = document.documentElement;
    if (elem.requestFullscreen) {
        elem.requestFullscreen();
    } else if (elem.webkitRequestFullscreen) { /* Safari */
        elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { /* IE11 */
        elem.msRequestFullscreen();
    }
}
function closeFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) { /* Safari */
        document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) { /* IE11 */
        document.msExitFullscreen();
    }
}
// Funkcije za Time Attack mod
function startTimeAttackMode() {
    isClassicMode = false;
    sessionId = generateSessionId();
    fadeOutSound(winterSound, 1421);
    fadeOutSound(bounceSound, 1200);
    stopBouncing();
    const backgroundLayer = document.getElementById("background-layer");
const transitionLayer = document.getElementById("transition-layer");

backgroundLayer.style.display = "none";
transitionLayer.style.display = "none";
    resetInfoPanelStyles();
    isTimeAttackMode = true;
    //openFullscreen();
    if (!levels) {
        levels = timeAttackLevels;
    }
    
    // Postavljanje pocetnih vrijednosti i staart timeatttack (dokle vise)
    currentTimeAttackLevelIndex = 0;
    timeAttackRemainingTime = INITIAL_TIME_ATTACK_TIME;
    remainingTime = timeAttackRemainingTime;
    clearInterval(timerInterval);
    timerInterval = null;
    // Sakrijte ili uklonite elemente iz glavnog moda igre
    document.getElementById('main-buttons').style.display = 'none';
    playerInfoDiv.classList.add("hidden");
    headerContainer.style.display = 'flex';
    logo.style.display = 'none'; // Sakrijemo veliki logo
    //logoSmall.style.display = 'block';
    // Postavimo boju teksta na bijelo
    const infoPanel = document.querySelector('.info');
    infoPanel.style.color = '#ffffff';
    // Ažuriramo timer i naziv nivoa
    scoreDisplayTimer.textContent = score;
    timerDisplay.textContent = timeAttackRemainingTime;
    //levelNameDisplay.textContent = 'Time Attack';
    levelDisplay.textContent = '↑'; // Prazno polje za broj nivoa
    // Zabilježimo vrijeme početka
    startTime = Date.now();
    // Pokrećemo prvi nivo Time Attack moda
    document.body.classList.add('fade-out');
setTimeout(() => {
    document.body.classList.remove('fade-out');
    startTimeAttackLevel();
}, 500);
  
}
let scorep = 0;
function startTimeAttackLevel() {
    
    medaljap = score-scorep;
    scorep = score;
updatePlayerName();
updateGoldOnly();
    level = JSON.parse(JSON.stringify(timeAttackLevels[currentTimeAttackLevelIndex]));
    if (!level) {
        console.error("Nivo nije pravilno inicijalizovan. Provjerite timeAttackLevels.");
        return;
    }
    if (bgMusic) {
        bgMusic.pause();
        bgMusic.currentTime = 0;
    }
    cardsToMatchTimer.textContent = level.matchCards;
    level.solveTime = timeAttackRemainingTime; 
    level.name = 'Time Attack';
    updateUIForCurrentMode();
    // Zaključavanje ploče prije iscrtavanja nivoa
    isBoardLocked = true;
    // Provjera da li je trenutni nivo prvi nivo u Time Attack modu
    const isFirstLevel = currentTimeAttackLevelIndex === 0;
    if (isFirstLevel) {
        // Ako je prvi nivo, direktno iscrtavanje ploče bez pauze
        createBoard();
        if (level.previewTime > 0) {
            setTimeout(() => {
                isBoardLocked = false;
            }, level.previewTime);
        } else {
            isBoardLocked = false; // Otključaj ploču odmah ako nema pregleda
        }
    } else {
        // Dodavanje pauze prije iscrtavanja nivoa za sve ostale nivoe
        setTimeout(() => {
            createBoard(); // Kreiramo tablu za igru
            // Ako je postavljen preview, otključaj ploču nakon pregleda kartica
            if (level.previewTime > 0) {
                setTimeout(() => {
                    isBoardLocked = false;
                }, level.previewTime);
            } else {
                isBoardLocked = false; // Otključaj ploču odmah nakon iscrtavanja ako nema pregleda
            }
        }, 700); // Pauza od 500ms prije prelaska na novi nivo
    }

}
function startTimeAttackTimer() {
    clearInterval(timerInterval); // Očistimo prethodni timer
    timerDisplay.textContent = timeAttackRemainingTime;
    // Postavljanje intervala za odbrojavanje vremena
    timerInterval = setInterval(() => {
        timeAttackRemainingTime--;
        remainingTime = timeAttackRemainingTime;
        timerDisplay.textContent = remainingTime;
        // Ako vrijeme istekne, pozivamo timeUp funkciju
        if (remainingTime <= 0) {
            clearInterval(timerInterval);
            timerInterval = null; // Reset the interval ID
            if (!levelCompleted) {      
        timeUp();
        }        }
    }, 1000);
}
function nextTimeAttackLevel() {
    currentTimeAttackLevelIndex++;
    if (currentTimeAttackLevelIndex >= timeAttackLevels.length) {
        // Kada se završe svi nivoi, počinjemo ispočetka
        currentTimeAttackLevelIndex = 0;
    }
    level = timeAttackLevels[currentTimeAttackLevelIndex];
    startTimeAttackLevel();
}
function clearAllIntervals() {
    if (assistIntervalId) {
        clearInterval(assistIntervalId);
        assistIntervalId = null;
    }
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    // Clear other intervals if you have any
}
function resetStartScreen() {
    logo.style.display = 'block';
    startGameBtn.style.display = 'block';
    timeAttackBtn.style.display = 'block';
    practiceBtn.style.display = 'block';
    instructionsBtn.style.display = 'block';
    //logoSmall.style.display = 'none'; // Sakrij mali logo, ako je prikazan.
    headerContainer.style.display = 'none'; // Sakrij header.
    infoPanel.style.display = 'none'; // Sakrij info panel.
    gameBoard.style.display = 'none'; // Sakrij ploču za igru.
    difficultySelection.style.display = 'none'; // Sakrij selektor težine.
    mainButtons.style.display = 'flex'; // Prikaži dugmad na glavnom ekranu.
    document.getElementById('background-overlay').style.display = 'none'; // Sakrij overlay.
}
function startTimer() {
    // Clear any existing timer to prevent multiple intervals
    if (timerInterval) {
        clearInterval(timerInterval);
    }

    if (isHybridMode) {
        timerInterval = setInterval(() => {
            remainingTime--;
            timerHybrid.textContent = remainingTime;

            // Play beep sound during the last 5 seconds
            if (remainingTime <= 5 && remainingTime > 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }

            if (remainingTime === 0) {
                clearInterval(timerInterval); // Stop the timer
                gameOverHybrid('time');
            }
        }, 1000);
    } else if (isTimeAttackMode) {
        timerInterval = setInterval(() => {
            timeAttackRemainingTime--;
            remainingTime = timeAttackRemainingTime;
            timerDisplay.textContent = remainingTime;

            // Play beep sound during the last 5 seconds
            if (remainingTime <= 5 && remainingTime > 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }

            if (remainingTime === 0) {
                clearInterval(timerInterval); // Stop the timer
                    if (!levelCompleted) {
        timeUp();
    }            }
        }, 1000);
    } else if (!isClassicMode) {
        timerInterval = setInterval(() => {
            remainingTime--;
            timerDisplay.textContent = remainingTime;

            // Play beep sound during the last 5 seconds
            if (remainingTime <= 5 && remainingTime > 0) {
                beepSound.currentTime = 0;
                beepSound.play();
            }

            if (remainingTime === 0) {
                clearInterval(timerInterval); // Stop the timer
                    if (!levelCompleted) {
        timeUp();
    }            }
        }, 1000);
    }
}
const levelDisappearSound = document.getElementById('card-hide-sound');
let score2;
window.levelType = '';
const robotCostsDiamonds = [4500, 6500]; // Fiksne cijene dijamanata za (1) i (2) kupovinu robota
const robotCostGold = 1;                // Fiksna cijena u gold-u (krunama)

/******************************************************
 * KRAJ NOVIH KONFIGURACIJA
 ******************************************************/
let igralitajrobot = "";

 function showLevelNotification(levelData, callback) {
  updatePlayerName();
  score2 = score;
  openFullscreen();

  brojacstreak = 0;
  playerInfoDiv.classList.add("hidden");
  saveGameState();
  enableContinueButton();
  if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
  }
  da_li_je_game_over = false;
  if (isTimeAttackMode) {
      if (callback) callback();
      return;
  }
  if (loadvarijabla === true) {
      fadeOutSound(winterSound, 1200); 
      stopSnowfall(); 
      fadeOutSound(bounceSound, 800); 
      stopBouncing(); 
      switchTheme();
      loadvarijabla = false;
  }
  if (tema === "w") {
      fadeOutSound(winterSound, 1200);
      stopSnowfall();
  } else {
      fadeOutSound(bounceSound, 800);
      stopBouncing();
  }

  const gameContainer = document.getElementById('game-container');
  const levelNotification = document.getElementById('level-notification');
  const levelNotificationContent = document.querySelector('.level-notification-content');
  const levelNumberElem = document.getElementById('level-number');
  const levelMatchCardsElem = document.getElementById('level-match-cards');
  const levelTypeElem = document.getElementById('level-type');
  const levelMovesElem = document.getElementById('level-moves');
  const levelTimeElem = document.getElementById('level-time');
  const countdownTimerElem = document.getElementById('countdown-timer');
  const startLevelButton = document.getElementById('start-level-button');
  const infoHeader = document.getElementById('header-container');
  const infoHeaderHybrid = document.getElementById('header-container-hybrid');
  
  gameContainer.style.display = 'none';
  if (infoHeader) infoHeader.style.display = 'none';
  if (infoHeaderHybrid) infoHeaderHybrid.style.display = 'none';

  const backgroundLayer = document.getElementById("background-layer");
  const transitionLayer = document.getElementById("transition-layer");

  if (levelData.backgroundImage) {
      let baseImage = levelData.backgroundImage.endsWith('.jpg') 
          ? levelData.backgroundImage.slice(0, -4) 
          : levelData.backgroundImage;

      let themedBackground = `${baseImage}${tema}.jpg`;
      console.log("Pokušava učitati sliku za nivo:", themedBackground);

      transitionLayer.style.backgroundImage = `url(${themedBackground})`;
      transitionLayer.style.opacity = 1; // Fade-in efekat

      setTimeout(() => {
          backgroundLayer.style.backgroundImage = `url(${themedBackground})`;
          transitionLayer.style.opacity = 0; 
      }, 500); 
  } else {
      backgroundLayer.style.backgroundImage = '';
      transitionLayer.style.opacity = 0;
  }

  // Funkcija za kreiranje stilizovanog dela teksta
  function createStyledSpan(text, styles, additionalClass = '') {
      const span = document.createElement('span');
      span.textContent = text;
      Object.assign(span.style, styles);
      
      if (additionalClass) {
          span.classList.add(additionalClass);
      }
      return span;
  }

  // Prilagodba za `levelNumberElem`
  levelNumberElem.innerHTML = '';
  levelNumberElem.appendChild(createStyledSpan('NIVO: ', { 
      color: '#fae5d3', 
      fontSize: 'clamp(1.9rem, 2vw + 1rem, 3rem)', 
      fontWeight: 'normal',
      fontFamily: 'Kiddiline' 
  }));
  levelNumberElem.appendChild(createStyledSpan(isPracticeMode ? '-' : currentLevelIndex + 1, { 
      color: '#fae5d3', 
      fontSize: 'clamp(1.9rem, 2vw + 1rem, 3rem)', 
      fontWeight: 'bold',
      fontFamily: 'Kiddiline' 
  }));
  const imenivoaElem = createStyledSpan(imenivoa, { 
      color: '#fae5d3', 
      fontSize: 'clamp(1.2rem, 1.5vw + 1rem, 2.6rem)',
      fontWeight: 'normal',
      fontFamily: 'Kiddiline',
      display: 'block',
      marginTop: '5px',
      marginBottom: "12px"
  });
  levelNumberElem.appendChild(imenivoaElem);

  // Prilagodba za `levelMatchCardsElem`
  levelMatchCardsElem.innerHTML = ''; 
  levelMatchCardsElem.appendChild(createStyledSpan('Broj kartica za slaganje: ', { 
      color: '#f9e79f', 
      fontSize: 'clamp(1.5rem, 1.7vw + 1rem, 2.8rem)', 
      fontWeight: 'bold',
      fontFamily: 'Kiddiline' 
  }));
  levelMatchCardsElem.appendChild(createStyledSpan(levelData.matchCards, { 
      color: '#f9e79f', 
      fontSize: 'clamp(1.5rem, 2vw + 1rem, 3rem)', 
      fontWeight: 'bold',
      fontFamily: 'Kiddiline' 
  }));

  // Prilagodba za `levelTypeElem`
  
  if (levelData.solveTime > 0 && levelData.moves > 0) {
      levelType = 'Tip nivoa: Hibrid';
  } else if (levelData.moves > 0) {
      levelType = 'Tip nivoa: Potezi';
  } else {
      levelType = 'Tip nivoa: Vrijeme';
  }
  levelTypeElem.innerHTML = ''; 
  levelTypeElem.appendChild(createStyledSpan(levelType, {
      color: '#ADD8E6', 
      fontSize: 'clamp(1.5rem, 2vw + 1rem, 3rem)', 
      fontWeight: 'bold', 
      fontFamily: 'Kiddiline'
  }));

  // Prilagodba za `levelMovesElem`
  levelMovesElem.innerHTML = ''; 
  levelMovesElem.appendChild(createStyledSpan('Ukupno poteza: ', { 
      color: '#00FF00', 
      fontSize: 'clamp(1.5rem, 2vw + 1rem, 3rem)', 
      fontFamily: 'Kiddiline' 
  }));
  
  levelMovesElem.appendChild(createStyledSpan(levelData.moves > 0 ? levelData.moves : '∞', { 
      color: ' #04fca6 ', 
      fontSize: 'clamp(1.5rem, 2vw + 1rem, 3rem)', 
      fontWeight: 'bold',
      fontFamily: 'Kiddiline' 
  }));

  // Prilagodba za `levelTimeElem`
  levelTimeElem.innerHTML = ''; 
  levelTimeElem.appendChild(createStyledSpan('Ukupno vrijeme: ', { 
      color: '#FFFF00', 
      fontSize: 'clamp(1.3rem, 1.9vw + 1rem, 3.2rem)', 
      fontFamily: 'Kiddiline' 
  }));
  levelTimeElem.appendChild(createStyledSpan(levelData.solveTime > 0 ? `${levelData.solveTime} sek.` : '∞ sek.', { 
      color: 'orange', 
      fontSize: 'clamp(1.3rem, 1.9vw + 1rem, 3.2rem)', 
      fontWeight: 'bold',
      fontFamily: 'Kiddiline' 
  }));

  shopRefreshShowLevelNotification();
  // Stil za countdown
  countdownTimerElem.style.color = '#FFFFFF';
  countdownTimerElem.style.fontSize = 'clamp(2.5rem, 3.1vw + 1.1rem, 4.1rem)';
  countdownTimerElem.style.fontWeight = 'bold';
  countdownTimerElem.style.fontFamily = 'digital';

  // Vrati font Kiddiline za startLevelButton:
  startLevelButton.style.fontFamily = 'Kiddiline';
  startLevelButton.style.color = '#000080';
  startLevelButton.style.backgroundColor = '#007BFF';
  startLevelButton.style.fontSize = 'clamp(1.5rem, 2vw + 1rem, 3rem)';
  startLevelButton.style.fontWeight = 'bold';
  startLevelButton.style.padding = '10px 20px';
  startLevelButton.style.borderRadius = '100px';
  startLevelButton.style.marginBottom = '12px'; // poništimo eventualne stare margine

  // Sakrijemo startLevelButton iz prethodnih poziva (ako je ostao u DOM-u vidljiv)
  startLevelButton.classList.add('hidden');

  // Provjera postoji li već shop-button. Ako postoji, uklanjamo ga iz DOM-a 
  const existingShopButton = document.getElementById('shop-button');
  if (existingShopButton) {
      existingShopButton.remove();
  }

  // Sada ponovo kreiramo shop dugme (od nule):
  const shopButton = document.createElement('button');
  shopButton.id = 'shop-button';
  shopButton.textContent = 'Trgovina';
  shopButton.classList.add('hidden'); 
  // Stilizacija shop dugmeta — slično start-level-button, ali druga boja:
  shopButton.style.color = '#000080';
  shopButton.style.backgroundColor = '#FF6800';
  shopButton.style.fontSize = 'clamp(1.5rem, 2vw + 1rem, 3rem)';
  shopButton.style.fontWeight = 'bold';
  shopButton.style.fontFamily = 'Kiddiline';
  shopButton.style.padding = '10px 20px';
  shopButton.style.borderRadius = '100px';
  shopButton.style.marginBottom = '0px';

  // Definišemo sporiji efekt flashanja za shop dugme
  const styleElem = document.createElement('style');
  styleElem.textContent = `
      @keyframes flashButtonSlower {
          0%, 100% { background-color: #FF6800; }
          33% { background-color: #ffb94e; }
          66% { background-color: #ff9a1f; }
      }
      #shop-button.flash-slower {
          opacity: 1;
          animation: flashButtonSlower 2s infinite, bounce-in 0.6s ease-in-out; 
      }
  `;
  document.head.appendChild(styleElem);

  // Klik na shop dugme pokreće prikaz shop prozora
  shopButton.onclick = () => {
      prikaziShopProzor(); 
  };

  // === SPECIJALNI KONTEJNER za countdown, dugmad, ...
  buttonContainer = document.getElementById('button-container');
  if (!buttonContainer) {
      buttonContainer = document.createElement('div');
      buttonContainer.id = 'button-container';
      levelNotificationContent.appendChild(buttonContainer);
  }

  // Očistimo buttonContainer (možda su ostaci iz prethodnog prikaza)
  buttonContainer.innerHTML = '';

  // Fiksna visina za 2 dugmeta, countdown... 
  buttonContainer.style.width = '100%';
  buttonContainer.style.height = 'clamp(100px, 12vw, 160px)';
  buttonContainer.style.display = 'flex';
  buttonContainer.style.flexDirection = 'column';
  buttonContainer.style.alignItems = 'center';
  buttonContainer.style.justifyContent = 'center';
  
  // Ubacimo countdownTimerElem (inicijalno vidljiv)
  buttonContainer.appendChild(countdownTimerElem);

  // Dodajemo "startLevelButton" (inicijalno hidden)
  buttonContainer.appendChild(startLevelButton);

  // NOVO: Kreiramo "Uposli robota" dugme i ubacimo ga između start i shop:
  uposliRobotButton = document.createElement('button');
  uposliRobotButton.id = 'use-robot-button';
  uposliRobotButton.classList.add('hidden'); 
  // Kopiramo stil od startLevelButton
  uposliRobotButton.style.fontFamily = 'Kiddiline';
  uposliRobotButton.style.color = '#000080';
  uposliRobotButton.style.backgroundColor = '#007BFF';
  uposliRobotButton.style.fontSize = 'clamp(1.5rem, 2vw + 1rem, 3rem)';
  uposliRobotButton.style.fontWeight = 'bold';
  uposliRobotButton.style.padding = '10px 20px';
  uposliRobotButton.style.borderRadius = '100px';
  uposliRobotButton.style.marginBottom = '12px'; 
  uposliRobotButton.onclick = () => {
    startLevelButton.classList.remove('flash');
      shopButton.classList.remove('flash-slower');
      uposliRobotButton.classList.remove('flash');

      // Uklonimo shop dugme iz DOM-a
      const btn = document.getElementById('shop-button');
      if (btn) btn.remove();

      // Uklanjamo i robot dugme
      const rob = document.getElementById('use-robot-button');
      if (rob) rob.remove();

      levelNotificationContent.style.animation = `${randomDeparture} 0.5s ease forwards`;
      levelDisappearSound.play();

      levelNotificationContent.addEventListener('animationend', () => {
          levelNotification.classList.add('hidden');
          levelNotificationContent.style.display = 'none';
          gameContainer.style.display = '';
          if (infoHeader) infoHeader.style.display = '';
          if (infoHeaderHybrid) infoHeaderHybrid.style.display = '';
          levelNotificationContent.style.animation = '';
          if (callback) callback();
      }, { once: true }); 
      igralitajrobot = "jasta_nego_igra";
      
  };
  buttonContainer.appendChild(uposliRobotButton);

  // Na kraju dodajemo shopButton (inicijalno hidden)
  buttonContainer.appendChild(shopButton);

  // Zvuk pojave
  const randomAudioFile = audioFiles[Math.floor(Math.random() * audioFiles.length)];
  const levelAppearSound = new Audio(randomAudioFile);
  levelAppearSound.play();

  // Reset countdown
  countdownTimerElem.textContent = '5';
  startLevelButton.classList.add('hidden');
  shopButton.classList.add('hidden');
  uposliRobotButton.classList.add('hidden');

  levelNotification.classList.remove('hidden');
  levelNotificationContent.style.display = 'block';

  const arrivalAnimations = [
      'slideInFromLeft', 
      'slideInFromRight', 
      'slideInFromTop', 
      'slideInFromBottom', 
      'zoomInRotate'
  ];
  const departureAnimations = [
      'slideOutToLeft', 
      'slideOutToRight', 
      'slideOutToTop', 
      'slideOutToBottom', 
      'zoomOutRotateFade'
  ];
  const randomArrival = arrivalAnimations[Math.floor(Math.random() * arrivalAnimations.length)];
  const randomDeparture = departureAnimations[Math.floor(Math.random() * departureAnimations.length)];

  levelNotificationContent.style.animation = `${randomArrival} 0.5s ease forwards`;
  countdownTimerElem.classList.remove('hidden');

  let countdown = 5;
  const countdownInterval = setInterval(() => {
      countdown--;
      countdownTimerElem.textContent = countdown;
      if (countdown <= 0) {
          clearInterval(countdownInterval);
          countdownTimerElem.textContent = '';
          countdownTimerElem.classList.add('hidden');
          
          startLevelButton.classList.remove('hidden');
          shopButton.classList.remove('hidden');

          // Pozovemo checkRobotButton da prikaže Robot dugme ako robot>0
          checkRobotButton();

          // Dodaj brži flash na startLevelButton, sporiji na shopButton
          startLevelButton.classList.add('flash');
          shopButton.classList.add('flash-slower');
      }
  }, 1000);

  // Klik na "Pokreni nivo"
  startLevelButton.onclick = () => {
      startLevelButton.classList.remove('flash');
      shopButton.classList.remove('flash-slower');
      uposliRobotButton.classList.remove('flash');

      // Uklonimo shop dugme iz DOM-a
      const btn = document.getElementById('shop-button');
      if (btn) btn.remove();

      // Uklanjamo i robot dugme
      const rob = document.getElementById('use-robot-button');
      if (rob) rob.remove();

      levelNotificationContent.style.animation = `${randomDeparture} 0.5s ease forwards`;
      levelDisappearSound.play();

      levelNotificationContent.addEventListener('animationend', () => {
          levelNotification.classList.add('hidden');
          levelNotificationContent.style.display = 'none';
          gameContainer.style.display = '';
          if (infoHeader) infoHeader.style.display = '';
          if (infoHeaderHybrid) infoHeaderHybrid.style.display = '';
          levelNotificationContent.style.animation = '';
          if (callback) callback();
      }, { once: true });
  };
}
let uposliRobotButton = null;
let buttonContainer = null;

function checkRobotButton() {
        if (robot > 0) {
            // Možemo povećati visinu da stane i to dugme
            buttonContainer.style.height = 'clamp(184px, 14vw, 240px)';
            uposliRobotButton.textContent = `🤖 Uposli robota (${robot})`;
            uposliRobotButton.classList.remove('hidden');
            // Dodamo i flash animaciju, kao na startLevelButton
            uposliRobotButton.classList.add('flash');
        } else {
            // Vraćamo visinu na originalnu, ako želite
            buttonContainer.style.height = 'clamp(100px, 12vw, 160px)';
            uposliRobotButton.classList.add('hidden');
            uposliRobotButton.classList.remove('flash');
        }
    }

function shopRefreshShowLevelNotification() {
    // Elementi
    const levelMovesElem = document.getElementById('level-moves');
    const levelTimeElem  = document.getElementById('level-time');
    if (!levelMovesElem || !levelTimeElem) return;

    // Font "Kiddiline" - po želji setujemo:
    levelMovesElem.style.fontFamily = 'Kiddiline';
    levelTimeElem.style.fontFamily = 'Kiddiline';

    // Obračun kupovine
    const dodatniPotezi = kupljenipotezi + kupljenipoteziskroz; 
    const dodatnoVrijeme = kupljenovrijeme + kupljenovrijemeskroz;

    // Mijenjamo textContent levelMovesElem:
    // Pretpostavimo da je original bio "Ukupno poteza: X" ili "Ukupno poteza: ∞"
    // 1) Ako je "∞", onda ne dodajemo ništa
    const movesTxt = levelMovesElem.textContent; 
    if (!movesTxt.includes('∞') && dodatniPotezi > 0) {
        // Izbrišemo eventualne stare "(+...)" ako postoje
        let baseText = movesTxt.replace(/\(\+\d+\)/, "").trim();
        levelMovesElem.textContent = baseText; 
        // Sada dodamo novim span-om
        const spanBonus = document.createElement('span');
        spanBonus.style.color = 'red';
        spanBonus.style.fontWeight = 'bold';
        spanBonus.textContent = ` (+${dodatniPotezi})`;
        levelMovesElem.appendChild(spanBonus);
    } else if (movesTxt.includes('∞')) {
        // Ako je ∞, ne radimo ništa
    }

    // Isto za vrijeme
    const timeTxt = levelTimeElem.textContent;
    if (!timeTxt.includes('∞') && dodatnoVrijeme > 0) {
        let baseText = timeTxt.replace(/\(\+\d+\)/, "").trim();
        levelTimeElem.textContent = baseText;
        const spanBonus = document.createElement('span');
        spanBonus.style.color = 'red';
        spanBonus.style.fontWeight = 'bold';
        spanBonus.textContent = ` (+${dodatnoVrijeme})`;
        levelTimeElem.appendChild(spanBonus);
    } else if (timeTxt.includes('∞')) {
        // Ako je ∞, ne radimo ništa
    }
}





function proceedToNextLevel() {
    
    isPaused = false;
    isBoardLocked = true;
    isHybridMode = false;
    // Update mode flags based on the new level's properties
    isHybridMode = level.solveTime > 0 && level.moves > 0;
    isClassicMode = level.moves > 0 && level.solveTime === 0;
    isTimeMode = level.solveTime > 0 && level.moves === 0;

    // Update the UI based on the new mode flags
    updateUIForCurrentMode();

    // Proceed to create the new level's grid
    const gameContainer = document.getElementById('game-container');
    gameContainer.style.display = 'flex';
    if (isBombMode) {
        createBombGrid();
    } else {
        createBoard();
    }

    // Update the info panel text color
    updateInfoTextColor();

    // Update the score display
    if (isHybridMode) {
        document.getElementById('score-hybrid').textContent = score;
    } else if (isClassicMode) {
        scoreDisplayMoves.textContent = score;
    } else {
        scoreDisplayTimer.textContent = score;
    }

}
const themeImages = {
    "": images,          // osnovna tema
    "w": imagesw,        // zimska tema
   // "s": imagess,   // ljetna tema
   // "a": imagesa,   // jesenja tema
    // Dodaj ostale teme po potrebi
};

const themes = ["", "w"];
    const themeNames = {
        "": "Jami Stikeri",
        "w": "Zima",
        //"s": "Ljeto",
       // "a": "Jesen"
    };
    let currentThemeIndex = 0;
    let tema = themes[currentThemeIndex]; // Početna tema
    
    function switchTheme() {
        x = 24.21;
    // Ako je stanje igre učitano
    if (loadvarijabla === true) {
        console.log("Stanje igre je učitano.");

       /* // Provjeri da li je učitana tema već aktivna
        if (themes[currentThemeIndex] === tema) {
            console.log("Tema već aktivna, nema potrebe za promjenom.");
            return; // Preskoči sve ako je tema već aktivna
        }*/

        // Postavi učitanu temu
        currentThemeIndex = themes.indexOf(tema);
        if (currentThemeIndex === -1) {
            console.error("Tema nije pronađena u dostupnim temama!");
            return;
        }
        console.log(`Primjenjuje se učitana tema: ${tema}`);
    } else {
        // Standardna funkcionalnost: Kružno prebacivanje tema
        currentThemeIndex = (currentThemeIndex + 1) % themes.length;
        tema = themes[currentThemeIndex];
    }

    // Primjena nove teme
    const temaButton = document.getElementById("tema-mode-btn");
    temaButton.textContent = `✨ Tema: ${themeNames[tema]}`;
    temaButton.className = `menu-btn ${themeClasses[tema]}`;

    const backgroundLayer = document.getElementById("background-layer");
    const transitionLayer = document.getElementById("transition-layer");

    // Postavi novu sliku na transitionLayer
    transitionLayer.style.backgroundImage = `url(${themeBackgrounds[tema]})`;
    transitionLayer.style.opacity = 1; // Fade-in nova slika
    currentImages = themeImages[tema] || images;

    // Provjera prije animacija i zvukova
    if (loadvarijabla === true) {
        console.log("Efekti i animacije preskočeni zbog nastavka igre.");
    } else {
        if (tema === "w") {
            console.log("Pokretanje animacije pahuljica");
            winterSound.play();
            fadeOutSound(bounceSound, 600);
            startSnowfall();
        } else {
            console.log("Zaustavljanje animacije pahuljica");
            fadeOutSound(winterSound, 1200);
            stopSnowfall();
            startBouncingImages();
        }
    }

    // Nakon što fade-in završi, prebaci novu sliku na backgroundLayer i sakrij transitionLayer
    setTimeout(() => {
        backgroundLayer.style.backgroundImage = `url(${themeBackgrounds[tema]})`;
        transitionLayer.style.opacity = 0; // Sakrij transitionLayer
    }, 500); // Vrijeme fade-in efekta
}



const snowCanvas = document.createElement('canvas');
snowCanvas.style.position = 'fixed';
snowCanvas.style.pointerEvents = 'none';
snowCanvas.style.top = '0';
snowCanvas.style.left = '0';
snowCanvas.width = window.innerWidth;
snowCanvas.height = window.innerHeight;
document.body.appendChild(snowCanvas);
const snowCtx = snowCanvas.getContext('2d');

// Konstantne postavke za animaciju pahuljicalet width = window.innerWidth;
let NUMBER_OF_SNOWFLAKES = 1;
let MAX_SNOWFLAKE_SPEED = 0;
if (width > height) {
    NUMBER_OF_SNOWFLAKES = 324;
    MAX_SNOWFLAKE_SPEED = 1.7;
    }else {
    NUMBER_OF_SNOWFLAKES = 150;
    MAX_SNOWFLAKE_SPEED = 0.6;
    }
const MAX_SNOWFLAKE_SIZE = 5;

const SNOWFLAKE_COLOUR = '#ddd';
const snowflakes = [];
let snowfallAnimation;
let isSnowfallActive = false;

// Funkcije za kreiranje i animaciju pahuljica
const createSnowflake = () => ({
    x: Math.random() * snowCanvas.width,
    y: Math.random() * snowCanvas.height,
    radius: Math.floor(Math.random() * MAX_SNOWFLAKE_SIZE) + 1,
    color: SNOWFLAKE_COLOUR,
    speed: Math.random() * MAX_SNOWFLAKE_SPEED + 1,
});

const drawSnowflake = snowflake => {
    snowCtx.beginPath();
    snowCtx.arc(snowflake.x, snowflake.y, snowflake.radius, 0, Math.PI * 2);
    snowCtx.fillStyle = snowflake.color;
    snowCtx.fill();
    snowCtx.closePath();
}

const updateSnowflake = snowflake => {
    snowflake.y += snowflake.speed;
    if (snowflake.y > snowCanvas.height) {
        snowflake.y = 0;
        snowflake.x = Math.random() * snowCanvas.width;
    }
}

const animateSnowflakes = () => {
    snowCtx.clearRect(0, 0, snowCanvas.width, snowCanvas.height);
    snowflakes.forEach(snowflake => {
        updateSnowflake(snowflake);
        drawSnowflake(snowflake);
    });
    if (isSnowfallActive) {
        snowfallAnimation = requestAnimationFrame(animateSnowflakes);
    }
}
const winterSound = new Audio('sounds/winter.mp3');
winterSound.loop = true;
function startSnowfall() {
    stopBouncing();
    if (isSnowfallActive) return;
    isSnowfallActive = true;

    snowflakes.length = 0;
    for (let i = 0; i < NUMBER_OF_SNOWFLAKES; i++) {
        snowflakes.push(createSnowflake());
    }
    
    animateSnowflakes();
}

function stopSnowfall() {
    isSnowfallActive = false;
    cancelAnimationFrame(snowfallAnimation);
    snowCtx.clearRect(0, 0, snowCanvas.width, snowCanvas.height);

}

// Dodaj funkcionalnost za prilagođavanje veličine oba canvasa
window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    snowCanvas.width = window.innerWidth;
    snowCanvas.height = window.innerHeight;
});

// Upotreba
// startSnowfall(); // za pokretanje animacije pahuljica
// stopSnowfall();  // za zaustavljanje animacije pahuljica




    const themeBackgrounds = {
        "": "backgrounds/poz.jpg",
        "w": "backgrounds/pozw.jpg",
       // "s": "backgrounds/poz_s.jpg",
       // "a": "backgrounds/poz_a.jpg"
    };
    const themeClasses = {
        "": "theme-osnovna",
        "w": "theme-zima",
       // "s": "theme-ljeto",
      //  "a": "theme-jesen"
    };

    let currentImages = themeImages[tema] || images;
    // Dodaj event listener za dugme "Tema"
    document.getElementById("tema-mode-btn").addEventListener("click", switchTheme);

    function provjerateme()  {
        if (tema === "w") {
        winterSound.volume = 1.0;
        fadeOutSound(bounceSound, 1200);
        winterSound.play(); 
        startSnowfall();
    
        }else startBouncingImages();
    }

/*let cornerSequence = []; // Služi za praćenje redoslijeda dodira
const correctSequence = ["top-left", "top-right", "bottom-right", "bottom-left"]; // Ispravna sekvenca

document.addEventListener("click", (event) => {
    const x = event.clientX;
    const y = event.clientY;

    // Prepoznaj ugao na osnovu pozicije
    const corner = getCorner(x, y);
    if (corner) {
        cornerSequence.push(corner);
        if (cornerSequence.length > correctSequence.length) {
            cornerSequence.shift(); // Zadrži posljednje unosene elemente
        }

        // Provjera da li sekvenca odgovara
        if (JSON.stringify(cornerSequence) === JSON.stringify(correctSequence)) {
            activateTestMode(); // Aktiviraj test mode
        }
    }
});

// Funkcija za prepoznavanje ugla
function getCorner(x, y) {
    const width = window.innerWidth;
    const height = window.innerHeight;

    if (x < width * 0.2 && y < height * 0.2) return "top-left";
    if (x > width * 0.8 && y < height * 0.2) return "top-right";
    if (x > width * 0.8 && y > height * 0.8) return "bottom-right";
    if (x < width * 0.2 && y > height * 0.8) return "bottom-left";

    return null;
}

function activateTestMode() {
    testMode = (testMode === 1000) ? 0 : 1000; 
    console.log("activateTestMode called! testMode =", testMode);
    lifesound.play(); 
}
*/
 //location.reload(); za refresh stranice

// Funkcija za spremanje trenutnog stanja igre
const maxContinues = 3;
let continueCount = 0;
function updateGoldOnly() {
    const formatted = getCurrentFormattedDateTime();
    // Dohvati trenutno stanje igre iz `localStorage`
    const savedGameState = JSON.parse(localStorage.getItem('savedGameState')) || {};

    // Ažuriraj samo vrijednost `gold` iz globalne varijable
    savedGameState.medalja = medalja;
    savedGameState.gold = gold;
    savedGameState.medalja_ukupno = medalja_ukupno;
    savedGameState.nadimak = nadimak;
    savedGameState.nadimak_level = nadimak_level;
    savedGameState.savedDate = formatted;

    // Sačuvaj izmijenjeno stanje nazad u `localStorage`
    localStorage.setItem('savedGameState', JSON.stringify(savedGameState));

    // Log za praćenje
    console.log(`Gold je ažuriran: ${gold}`);
    syncLocalStorageWithServer();
}
function getCurrentFormattedDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
function saveGameState() {
    const formatted = getCurrentFormattedDateTime();
    const gameState = {
        nadimak_level: nadimak_level,
        nadimak: nadimak,
        medalja: medalja,
        medalja_ukupno: medalja_ukupno,
        gold: gold,
        robot: robot,
        duplipoeni: duplipoeni,
        duplibonus: duplibonus,
        duplipoeniskroz: duplipoeniskroz,
        duplibonusskroz: duplibonusskroz,
        kupljenoprikazivanje: kupljenoprikazivanje,
        kupljenoprikazivanjeskroz: kupljenoprikazivanjeskroz,
        kupljenovrijeme: kupljenovrijeme,
        kupljenovrijemeskroz: kupljenovrijemeskroz,
        kupljenipotezi: kupljenipotezi,
        kupljenipoteziskroz: kupljenipoteziskroz,
        sessionId: sessionId,
        artikliShop: artikliShop,
        currentLevelIndex: currentLevelIndex,
        selectedDifficulty: selectedDifficulty,
        tema: tema,
        score: score,
        lives: lives,
        isBombMode: isBombMode,
        isClassicMode: isClassicMode,
        milestone: milestone,
        continueCount: continueCount,
        savedDate: formatted
    };
    localStorage.setItem('savedGameState', JSON.stringify(gameState));
    enableContinueButton();
    console.log('Stanje igre je sačuvano:', gameState);

    // Nakon lokalnog sejva, pokušaj sync sa serverom
    syncLocalStorageWithServer();
}

let loadvarijabla = false;
let x = 0;
function loadGameState() {
    
    const savedGameState = localStorage.getItem('savedGameState');
    if (savedGameState) {
        const gameState = JSON.parse(savedGameState);
        console.log('Učitano sačuvano stanje:', gameState);

        // Preuzmite i povećajte continueCount
        continueCount = gameState.continueCount || 0;

        // Provjerite je li dostignut maksimalan broj nastavaka
        if (continueCount >= maxContinues) {
            
            disableContinueButton();
            return false;
        } else {
            // Ažurirajte continueCount u gameState i spremite ga nazad u localStorage
            gameState.continueCount = continueCount;
            localStorage.setItem('savedGameState', JSON.stringify(gameState));
            // Ažuriranje dugmeta za nastavak
            enableContinueButton();
        }

        // postavljanje varijabli
        robot = gameState.robot;
        nadimak_level = gameState.nadimak_level;
        nadimak = gameState.nadimak;
        medalja_ukupno = gameState.medalja_ukupno;
        medalja = gameState.medalja;
        gold = gameState.gold;
        duplipoeni = gameState.duplipoeni;
        duplibonus = gameState.duplibonus;
        duplipoeniskroz = gameState.duplipoeniskroz;
        duplibonusskroz = gameState.duplibonusskroz;
        kupljenoprikazivanje = gameState.kupljenoprikazivanje;
        kupljenoprikazivanjeskroz = gameState.kupljenoprikazivanjeskroz;
        kupljenovrijeme = gameState.kupljenovrijeme;
        kupljenovrijemeskroz = gameState.kupljenovrijemeskroz;
        kupljenipotezi = gameState.kupljenipotezi;
        kupljenipoteziskroz = gameState.kupljenipoteziskroz;
        artikliShop = gameState.artikliShop; inicijalizirajShopHandler();
        sessionId = gameState.sessionId || generateSessionId();
        currentLevelIndex = gameState.currentLevelIndex;
        selectedDifficulty = gameState.selectedDifficulty;
        tema = gameState.tema; loadvarijabla = true;
        score = gameState.score;
        lives = gameState.lives;
        isBombMode = gameState.isBombMode;
        isClassicMode = gameState.isClassicMode;
        milestone = gameState.milestone;
updatePlayerName();
        x = 1; 
        return true;
    } else {
        console.log('Nema sačuvanog stanja u localStorage.');
        disableContinueButton();
        return false;
    }
     
}
function formatContinueButtonText(remainingContinues) {
    let text = 'Nastavi igru';
    if (remainingContinues > 0) {
        text += ` (${remainingContinues})`;
    } else {
        text += ' (0)';
    }
    return text;
}
function enableContinueButton() {
        const continueButton = document.getElementById('continue-game-btn');
        const remainingContinues = maxContinues - continueCount;
        continueButton.disabled = false;
        continueButton.classList.remove('disabled');
        continueButton.textContent = formatContinueButtonText(remainingContinues);
        console.log('Dugme "Nastavi" je omogućeno. Preostali nastavi:', remainingContinues);
    }
    
    function disableContinueButton() {
        const continueButton = document.getElementById('continue-game-btn');
        continueButton.disabled = true;
        continueButton.classList.add('disabled');
        continueButton.textContent = formatContinueButtonText(0);
        console.log('Dugme "Nastavi" je onemogućeno.');
    }
function prepareLocalStorageForServer() {
    const allKeys = Object.keys(localStorage);
    const data = {};
    for (let i = 0; i < allKeys.length; i++) {
        const key = allKeys[i];
        if (key === 'unsentResults') continue;
        data[key] = localStorage.getItem(key);
    }
    // Ako se kasnije bude radila enkripcija, ovdje se moze dodati
    return data;
}

// NOVA FUNKCIJA loadLocalStorageFromServer
function loadLocalStorageFromServer(playerName) {
    return fetch('https://jami.ba/jgngame/getLocalStorageData.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ nickname: playerName })
    })
    .then(response => response.json())
    .catch(error => {
        console.error('Greška pri učitavanju stanja sa servera:', error);
        return null;
    });
}

// NOVA FUNKCIJA restoreLocalStorageFromServer
function restoreLocalStorageFromServer(serverData) {
    localStorage.clear();
    try {
        const fullData = JSON.parse(serverData.fullData);
        for (const key in fullData) {
            localStorage.setItem(key, fullData[key]);
        }
    } catch (err) {
        console.error("Neuspješno parsiranje fullData:", err);
    }

    const savedGameState = JSON.parse(localStorage.getItem('savedGameState') || '{}');
    savedGameState.nadimak_level = serverData.nadimak_level;
    savedGameState.nadimak = serverData.nadimak;
    savedGameState.medalja = serverData.medalja;
    savedGameState.medalja_ukupno = serverData.medalja_ukupno;
    savedGameState.savedDate = serverData.savedDate;
    savedGameState.gold = serverData.gold;
    localStorage.setItem('savedGameState', JSON.stringify(savedGameState));

    console.log("Lokalni storage obnovljen sa servera.");
    loadGameState();
    loadInitialGold();
    initializeThreshold();
    updatePlayerName();
}

// NOVA FUNKCIJA syncLocalStorageWithServer
function syncLocalStorageWithServer() {
    const storedData = JSON.parse(localStorage.getItem("playerData")) || {};
    const playerName = storedData.playerName || '';
    if (!playerName) {
        console.warn("Nema imena igrača, preskačem sync sa serverom.");
        return;
    }

    const localGame = localStorage.getItem('savedGameState');
    if (!localGame) {
        console.log("Nema local savedGameState, nema slanja na server.");
        return;
    }

    const gameState = JSON.parse(localGame);
    const preparedData = prepareLocalStorageForServer();
    const postData = new URLSearchParams({
        nickname: playerName,
        fullData: JSON.stringify(preparedData),
        nadimak_level: gameState.nadimak_level || '',
        nadimak: gameState.nadimak || '',
        medalja: gameState.medalja || 0,
        medalja_ukupno: gameState.medalja_ukupno || 0,
        gold: gameState.gold || 0,
        savedDate: gameState.savedDate || ''
    });

    fetch('https://jami.ba/jgngame/updateLocalStorageData.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: postData
    })
    .then(response => response.json())
    .then(data => {
        if(data.status === 'success') {
            console.log('LocalStorage uspješno sinhronizovan na serveru.');
        } else {
            console.error('Greška pri sinhronizaciji localStorage na server:', data.message);
        }
    })
    .catch(error => {
        console.error('Greška pri sinhronizaciji localStorage sa serverom:', error);
    });
}



window.addEventListener('load', () => {
    const continueButton = document.getElementById('continue-game-btn');
    const savedGameState = localStorage.getItem('savedGameState');
    if (savedGameState) {
        const gameState = JSON.parse(savedGameState);
        continueCount = gameState.continueCount || 0;
 
        if (continueCount >= maxContinues) {
            disableContinueButton();
        } else {
            enableContinueButton();
        }
    } else {
        disableContinueButton();
    }
});

function startGameFromLoadedState() {
    mainButtons.style.display = "none";
    continueCount++;
    console.log("Pokrećem igru iz sačuvanog stanja sa težinom:", selectedDifficulty);
    console.log("Is Bomb Mode:", isBombMode);
    console.log("Is Classic Mode:", isClassicMode);

    // Ne resetujemo score jer ga učitavamo iz sačuvanog stanja
    // Inicijalizacija drugih varijabli
    matchedCards = 0;
    levelCompleted = false;
    isBoardLocked = false;
    bns = true;

    // Resetuj ostale modove
    isPracticeMode = false;
    isTimeAttackMode = false;
    isHybridMode = false;

    // Ne resetujemo lives jer ga učitavamo iz sačuvanog stanja

    // Show the appropriate header
    document.getElementById('header-container').style.display = 'none';
    document.getElementById('header-container-hybrid').style.display = 'none';

    // Postavi nivoe i trenutni nivo na osnovu moda i težine
    if (isBombMode) {
        if (selectedDifficulty === 'easy') {
            levels = eblevels;
            imenivoa = "Specijal - Laganica";
        
        } else if (selectedDifficulty === 'normal') {
            levels = blevels;
            imenivoa = "Specijal - Normala";
            console.log("Selected Bomb Mode Levels: blevels");
        } else if (selectedDifficulty === 'hard') {
            levels = hblevels;
            imenivoa = "Specijal - Ludilo!";
            console.log("Selected Bomb Mode Levels: hblevels");
        }
    } else if (isClassicMode) {
        if (selectedDifficulty === 'easy') {
            levels = celevels;
            imenivoa = "Klasika - Laganica";
            console.log("Selected Classic Mode Levels: celevels");
        } else if (selectedDifficulty === 'normal') {
            levels = cnlevels;
            imenivoa = "Klasika - Normala";
            console.log("Selected Classic Mode Levels: cnlevels");
        } else if (selectedDifficulty === 'hard') {
            levels = chlevels;
            imenivoa = "Klasika - Ludilo!";
            console.log("Selected Classic Mode Levels: chlevels");
        }
    } else {
        if (selectedDifficulty === 'easy') {
            levels = elevels;
            imenivoa = "Standardica - Laganica";
            console.log("Selected Standard Mode Levels: elevels");
        } else if (selectedDifficulty === 'normal') {
            levels = nlevels;
            imenivoa = "Standardica - Normala";
            console.log("Selected Standard Mode Levels: nlevels");
        } else if (selectedDifficulty === 'hard') {
            levels = hlevels;
            imenivoa = "Klasika - Ludilo!";
            console.log("Selected Standard Mode Levels: hlevels");
        }
    }
    if (isBombMode) {
        currentGameMode = 'Specijal';
    } else if (isClassicMode) {
        currentGameMode = 'Klasika';
    } else if (isTimeAttackMode) {
        currentGameMode = 'Dokle vise';
    } else {
        currentGameMode = 'Standardica';
    }
    // Provjeri da li su levels ispravno postavljeni
    if (!levels || levels.length === 0) {
        console.error("Levels nisu pravilno inicijalizirani. Provjerite definiciju level-eva.");
        return;
    }

    // Ne resetujemo currentLevelIndex jer ga učitavamo iz sačuvanog stanja
    level = levels[currentLevelIndex];

    // Set mode flags based on the new level's properties
    isHybridMode = level.solveTime > 0 && level.moves > 0;
    isClassicMode = level.moves > 0 && level.solveTime === 0;

    // Update lives display
    if (isHybridMode) {
        document.getElementById('lives-hybrid').textContent = lives;
    } else {
        document.getElementById('lives').textContent = lives;
    }

    // Show the appropriate header based on mode
    console.log("Current Level:", level);

    // Set remaining moves or time based on the mode
    if (isHybridMode) {
        remainingMoves = level.moves + testMode + kupljenipoteziskroz + kupljenipotezi;
        remainingTime = level.solveTime + testMode + kupljenovrijeme + kupljenovrijemeskroz;
        document.getElementById('moves-hybrid').textContent = remainingMoves;
        document.getElementById('timer-hybrid').textContent = remainingTime;
    } else if (isClassicMode) {
        remainingMoves = level.moves + testMode + kupljenipoteziskroz + kupljenipotezi;
        document.getElementById('moves').textContent = remainingMoves;
        console.log("Classic Mode Enabled with moves:", remainingMoves);
    } else {
        remainingTime = level.solveTime + testMode + kupljenovrijeme + kupljenovrijemeskroz;
        document.getElementById('timer').textContent = remainingTime;
        console.log("Time Mode Enabled with remainingTime:", remainingTime);
    }

    // Reset pause and board lock
    isPaused = false;
    isBoardLocked = false;

    // Start fullscreen mode ako je potrebno
    // openFullscreen();

    // Add fade-out class for animation
    document.body.classList.add('fade-out');
    setTimeout(() => {
        document.body.classList.remove('fade-out');
        // Hide and show relevant elements
        logo.style.display = 'none';
        if (isHybridMode) {
            headerContainerHybrid.style.display = 'flex';
        } else {
            headerContainer.style.display = 'flex';
        }
        startGameBtn.style.display = 'none';
        BombBtn.style.display = 'none';
        practiceBtn.style.display = 'none';
        timeAttackBtn.style.display = 'none';
        classicModeBtn.style.display = 'none'; // Hide "Classic" button
        instructionsBtn.style.display = 'none';
        gameBoard.style.display = 'grid';
        infoPanel.style.display = 'flex';
        document.body.style.backgroundColor = level.backgroundColor || '#ffffff';

        // Pause background music if exists
        if (bgMusic) {
            bgMusic.pause();
            bgMusic.currentTime = 0;
        }

        // Start new background music if defined for the current level
        if (level.music) {
            bgMusic = new Audio(level.music);
            bgMusic.loop = true;
            bgMusic.volume = 1; // Adjust the volume as needed
            bgMusic.play();
            console.log("Playing background music:", level.music);
        }
        headerContainer.style.display = 'none';
        headerContainerHybrid.style.display = 'none';
        // Show the level notification before starting the level
        showLevelNotification(level, () => {
            updateUIForCurrentMode();

            // This callback runs after the notification is handled
            if (isBombMode) {
                createBombGrid();
                console.log("Created Bomb Grid");
            } else {
                createBoard();
                console.log("Created Standard/Classic Grid");
            }
            // Update the info panel text color
            updateInfoTextColor();
            // Update the score display
            if (isHybridMode) {
                document.getElementById('score-hybrid').textContent = score;
                console.log("Score Display (Hybrid):", score);
            } else if (isClassicMode) {
                scoreDisplayMoves.textContent = score;
                console.log("Score Display (Moves):", score);
            } else {
                scoreDisplayTimer.textContent = score;
                console.log("Score Display (Timer):", score);
            }
        });
    }, 500); // Animation duration
}

document.getElementById('continue-game-btn').addEventListener('click', () => {
    if (loadGameState()) {
        
        startGameFromLoadedState();
    } else {
    }
});


function saveBestResult(mode, difficulty, score, levelReached) {
    const key = `bestResult_${mode}_${difficulty}`;
    const previousBest = localStorage.getItem(key);
    const previousLevel = localStorage.getItem(`${key}_level`);
    
    if (!previousBest || score > parseInt(previousBest)) {
        localStorage.setItem(key, score);
        localStorage.setItem(`${key}_date`, new Date().toLocaleDateString());
        localStorage.setItem(`${key}_level`, levelReached);
        console.log(`Spremio najbolji rezultat za ${mode} na težini ${difficulty}: Poeni=${score}, Nivo=${levelReached}`);
    }
}

function saveBestDokleViseResult(score, duration, levelReached) {
    const key = 'bestResult_DokleVise';
    const previousBest = localStorage.getItem(key);
    const previousLevel = localStorage.getItem(`${key}_level`);
    
    if (!previousBest || score > parseInt(previousBest)) {
        localStorage.setItem(key, score);
        localStorage.setItem(`${key}_duration`, duration);
        localStorage.setItem(`${key}_date`, new Date().toLocaleDateString());
        localStorage.setItem(`${key}_level`, levelReached);
        console.log(`Spremio najbolji rezultat za Dokle više: Poeni=${score}, Nivo=${levelReached}, Trajanje=${duration}`);
    }
}

// Funkcija za stilizaciju dugmadi
// Definišemo CSS stilove
const style = document.createElement('style');
style.textContent = `
/* Globalni stilovi za rezultate */
.rezultati-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    z-index: 10000;
    padding: 10px;
    overflow-y: auto;
    box-sizing: border-box;
}

.rezultati-background-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(92, 0, 0, 0.77);
    z-index: 9999;
}

.rezultati-heading {
    color: #fff;
    text-align: center;
    margin-bottom: 10px;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.7);
    font-size: calc(20px + 1vw);
    margin-top: 0px;
}

.rezultati-content {
    padding: 10px;
    border-radius: 12px;
    text-align: center;
    width: 100%;
    max-width: 620px;
    background-color: rgb(255, 249, 220);
    margin: 0 auto 10px auto;
    
    overflow-y: auto;
    box-sizing: border-box;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.rezultati-button-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
}

.rezultati-button {
font-weight: bold;
    padding: 10px 30px;
    margin: 0 5px;
    font-size: calc(15px + 0.7vw);
    border-radius: 8px;
    cursor: pointer;
    background-color: #444;
    color: #fff;
    border: none;
    transition: background-color 0.3s, transform 0.2s;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.7);
}

.rezultati-button:hover {
    background-color: #666;
    transform: translateY(-2px);
}

.rezultati-button.active {
    background-color: darkred;
    font-weight: bold;
}

.rezultati-close-button {
font-weight: bold;
    padding: 10px 33px;
    font-size: calc(16px + 0.8vw);
    border-radius: 8px;
    cursor: pointer;
    background-color: mintcream;
    color: #000;
    border: none;
    transition: transform 0.2s;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.7);
}

.rezultati-close-button:hover {
    transform: translateY(-2px);
}

.rezultati-table-container {
    width: 100%;
    max-width: 621px;
    margin: 0 auto 5px auto;
    overflow-x: auto;
}

.rezultati-table {
    width: 100%;
    border-collapse: collapse;
    background-color: #444;
    color: #ffffff;
    border-radius: 8px;
    text-align: center;
    font-size: calc(10px + 0.6vw);
    margin-bottom: 5px;
}

.rezultati-table th, .rezultati-table td {
    padding: 2px 4px;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.rezultati-table th {
    font-weight: bold;
}

.rezultati-table .rang-column {
    width: 40px;
}
`;
document.head.appendChild(style);

// Funkcija za stilizaciju dugmadi
function styleSwitchButton(button) {
    button.classList.add('rezultati-button');
}

// Funkcija za prikaz lokalnih rezultata
function displayLocalResults(container) {
    container.innerHTML = ''; // Očisti prethodni sadržaj

    const modes = [
        { name: '🎮 Standardica', key: 'Standardica', color: 'green' },
        { name: '🤠 Klasika', key: 'Klasika', color: 'gray' },
        { name: '🔥 Specijal', key: 'Specijal', color: 'black' },
        { name: '🕒 Dokle više', key: 'DokleVise', color: 'blue' }
    ];

    const difficultyMap = {
        easy: 'Laganica',
        normal: 'Normala',
        hard: 'Ludilo!'
    };

    modes.forEach((mode) => {
        const tableContainer = document.createElement('div');
        tableContainer.classList.add('rezultati-table-container');

        const table = document.createElement('table');
        table.classList.add('rezultati-table');
        table.style.backgroundColor = mode.color;

        const headerRow = document.createElement('tr');
        const modeHeader = document.createElement('th');
        modeHeader.textContent = mode.name.toUpperCase();
        modeHeader.colSpan = mode.key === 'DokleVise' ? 5 : 5;
        modeHeader.style.padding = '5px';
        headerRow.appendChild(modeHeader);
        table.appendChild(headerRow);

        if (mode.key === 'DokleVise') {
            // Specijalna tabela za "Dokle više"
            const subHeaderRow = document.createElement('tr');
            ['Poeni', 'Nivo', 'Trajanje', 'Datum'].forEach((text) => {
                const th = document.createElement('th');
                th.textContent = text;
                subHeaderRow.appendChild(th);
            });
            table.appendChild(subHeaderRow);

            const row = document.createElement('tr');
            const scoreKey = `bestResult_${mode.key}`;
            const dateKey = `${scoreKey}_date`;
            const levelKey = `${scoreKey}_level`;
            const durationKey = `${scoreKey}_duration`;

            const score = localStorage.getItem(scoreKey) || '-';
            const rawDate = localStorage.getItem(dateKey) || '-';
            const levelReached = localStorage.getItem(levelKey) || '-';
            const duration = localStorage.getItem(durationKey) || '-';
            const date = rawDate !== '-' ? parseAndFormatDate(rawDate) : '-';

            [`<b>${score}</b>`, `<b>${levelReached}</b>`, duration, date].forEach((text, index) => {
                const td = document.createElement('td');
                if (index === 0 || index === 1) td.innerHTML = text;
                else td.textContent = text;
                row.appendChild(td);
            });

            table.appendChild(row);
        } else {
            const subHeaderRow = document.createElement('tr');
            ['Težina', 'Poeni', 'Nivo', 'Datum'].forEach((text) => {
                const th = document.createElement('th');
                th.textContent = text;
                subHeaderRow.appendChild(th);
            });
            table.appendChild(subHeaderRow);

            Object.keys(difficultyMap).forEach((difficultyKey) => {
                const row = document.createElement('tr');
                const difficulty = difficultyMap[difficultyKey];
                const scoreKey = `bestResult_${mode.key}_${difficultyKey}`;
                const dateKey = `${scoreKey}_date`;
                const levelKey = `${scoreKey}_level`;
                const score = localStorage.getItem(scoreKey) || '-';
                const rawDate = localStorage.getItem(dateKey) || '-';
                const levelReached = localStorage.getItem(levelKey) || '-';
                const date = rawDate !== '-' ? parseAndFormatDate(rawDate) : '-';

                [difficulty, `<b>${score}</b>`, `<b>${levelReached}</b>`, date].forEach((text, index) => {
                    const td = document.createElement('td');
                    if (index === 1 || index === 2) td.innerHTML = text;
                    else td.textContent = text;
                    row.appendChild(td);
                });

                table.appendChild(row);
            });
        }

        tableContainer.appendChild(table);
        container.appendChild(tableContainer);
    });
}

// Funkcija za prikaz globalnih rezultata
function displayGlobalResults(container) {
    container.innerHTML = ''; // Očisti prethodni sadržaj
    const loadingMessage = document.createElement('p');
    loadingMessage.textContent = 'Učitavanje globalnih rezultata...';
    loadingMessage.style.color = '#044215';
    container.appendChild(loadingMessage);

    fetch(`https://jami.ba/jgngame/get_leaderboard.php?timestamp=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            container.innerHTML = ''; // Očisti loader
            if (data.status === 'success') {
                const modes = [
                    { name: '🎮 Standardica', key: 'Standardica', color: 'green' },
                    { name: '🤠 Klasika', key: 'Klasika', color: 'gray' },
                    { name: '🔥 Specijal', key: 'Specijal', color: 'black' },
                    { name: '🕒 Dokle više', key: 'DokleVise', color: 'blue' }
                ];

                const difficultyMap = {
                    easy: 'Laganica',
                    normal: 'Normala',
                    hard: 'Ludilo!'
                };

                const groupedResults = groupResultsByModeAndDifficulty(data.leaderboard, modes);

                // Prikaz tabela u definisanom redosledu
                modes.forEach(mode => {
                    const modeKey = mode.key;
                    const modeResults = groupedResults[modeKey];

                    if (modeResults) {
                        if (modeKey === 'DokleVise') {
                            // Za "Dokle više", samo jedna tabela
                            if (modeResults['N/A']) {
                                container.appendChild(createGlobalResultsTable(mode, 'N/A', modeResults['N/A'], difficultyMap));
                            }
                        } else {
                            Object.keys(difficultyMap).forEach(difficultyKey => {
                                const results = modeResults[difficultyKey];
                                if (results && results.length > 0) {
                                    container.appendChild(createGlobalResultsTable(mode, difficultyKey, results, difficultyMap));
                                }
                            });
                        }
                    }
                });
            } else {
                container.textContent = 'Greška pri učitavanju globalnih rezultata.';
            }
        })
        .catch(error => {
            container.textContent = 'Greška pri povezivanju sa serverom.';
            console.error('Greška pri dobavljanju rang liste:', error);
        });
}

// Funkcija za grupisanje rezultata
function groupResultsByModeAndDifficulty(results, modes) {
    const grouped = {};
    const modeNameToKeyMap = {
        'standardica': 'Standardica',
        'klasika': 'Klasika',
        'specijal': 'Specijal',
        'dokle vise': 'DokleVise', // Map 'dokle vise' to 'DokleVise' key
        'dokle više': 'DokleVise'
    };

    results.forEach(result => {
        const modeName = result.game_mode.trim().toLowerCase();
        const difficulty = result.difficulty || 'N/A';

        const modeKey = modeNameToKeyMap[modeName];

        if (!modeKey) {
            console.warn(`Nepoznat mod igre: ${modeName}`);
            return;
        }

        if (!grouped[modeKey]) grouped[modeKey] = {};

        if (modeKey === 'DokleVise') {
            // Za "Dokle više", koristimo 'N/A' kao težinu
            if (!grouped[modeKey]['N/A']) grouped[modeKey]['N/A'] = [];
            grouped[modeKey]['N/A'].push(result);
        } else {
            if (!grouped[modeKey][difficulty]) grouped[modeKey][difficulty] = [];
            grouped[modeKey][difficulty].push(result);
        }
    });

    return grouped;
}

// Funkcija za kreiranje tabele za globalne rezultate
function createGlobalResultsTable(modeObj, difficultyKey, results, difficultyMap) {
    const tableContainer = document.createElement('div');
    tableContainer.classList.add('rezultati-table-container');

    const table = document.createElement('table');
    table.classList.add('rezultati-table');
    table.style.backgroundColor = modeObj.color;

    const headerRow = document.createElement('tr');
    const modeHeader = document.createElement('th');

    let modeName = modeObj.name;
    let difficultyLabel = difficultyKey !== 'N/A' ? difficultyMap[difficultyKey] : '';

    if (modeObj.key === 'DokleVise') {
        modeHeader.textContent = `${modeName}`;
        modeHeader.colSpan = 6;
    } else {
        modeHeader.textContent = `${modeName.toUpperCase()} - ${difficultyLabel}`;
        modeHeader.colSpan = 5;
    }
    modeHeader.style.padding = '5px';
    headerRow.appendChild(modeHeader);
    table.appendChild(headerRow);

    const subHeaderRow = document.createElement('tr');

    if (modeObj.key === 'DokleVise') {
        ['Rang', 'Nadimak', 'Poeni', 'Nivo', 'Trajanje', 'Datum'].forEach((text, index) => {
            const th = document.createElement('th');
            th.textContent = text;
            if (index === 0) th.classList.add('rang-column');
            subHeaderRow.appendChild(th);
        });
    } else {
        ['Rang', 'Nadimak', 'Poeni', 'Nivo', 'Datum'].forEach((text, index) => {
            const th = document.createElement('th');
            th.textContent = text;
            if (index === 0) th.classList.add('rang-column');
            subHeaderRow.appendChild(th);
        });
    }
    table.appendChild(subHeaderRow);

    results.sort((a, b) => b.score - a.score);
    results.slice(0, 10).forEach((result, index) => {
        const row = document.createElement('tr');

        const date = parseAndFormatDate(result.date);

        if (modeObj.key === 'DokleVise') {
            const levelReached = result.level_reached || '-';
            const duration = result.duration || '-';
            const formattedDuration = formatDuration(duration);

            [
                index + 1,
                result.nickname,
                result.score,
                levelReached,
                formattedDuration,
                date
            ].forEach((text, idx) => {
                const td = document.createElement('td');
                td.textContent = text;
                if (idx === 0) td.classList.add('rang-column');
                row.appendChild(td);
            });
        } else {
            const levelReached = result.level_reached || '-';

            [
                index + 1,
                result.nickname,
                result.score,
                levelReached,
                date
            ].forEach((text, idx) => {
                const td = document.createElement('td');
                td.textContent = text;
                if (idx === 0) td.classList.add('rang-column');
                row.appendChild(td);
            });
        }

        table.appendChild(row);
    });

    tableContainer.appendChild(table);
    return tableContainer;
}

function formatDuration(durationStr) {
    if (!durationStr || durationStr === '-') return '-';

    const match = durationStr.match(/(\d+)\s*min\s*(\d+)\s*sek/);
    if (match) {
        const minutes = match[1];
        const seconds = match[2];
        return `${minutes}m:${seconds}s`;
    }
    return durationStr;
}

// Funkcija za formatiranje datuma
function parseAndFormatDate(storedDate) {
    if (!storedDate) return '';
    const date = new Date(storedDate);
    if (isNaN(date.getTime())) return storedDate;
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
    const year = String(date.getFullYear()).slice(-2); // Get last two digits of the year
    return `${day}.${month}.${year}`;
}

// Glavna funkcija za prikaz overlay-a
function showResultsOverlay(){

    rezultatiSound.play();

    const backgroundOverlay = document.createElement('div');
    backgroundOverlay.classList.add('rezultati-background-overlay');
    document.body.appendChild(backgroundOverlay);

    const resultsOverlay = document.createElement('div');
    backgroundOverlay.classList.add('background-fade-in');
    resultsOverlay.classList.add('rezultati-overlay');
    resultsOverlay.classList.add('overlay-enter');

    const heading = document.createElement('h1');
    heading.innerHTML = 'N&nbsp;A&nbsp;J&nbsp;B&nbsp;O&nbsp;L&nbsp;J&nbsp;I&nbsp;&nbsp;&nbsp;R&nbsp;E&nbsp;Z&nbsp;U&nbsp;L&nbsp;T&nbsp;A&nbsp;T&nbsp;I';
    heading.classList.add('rezultati-heading');
    resultsOverlay.appendChild(heading);

    // Dugmad za prebacivanje prikaza
    const buttonContainer = document.createElement('div');
    buttonContainer.classList.add('rezultati-button-container');

    const localResultsButton = document.createElement('button');
    localResultsButton.textContent = '🥇 Moji';
    styleSwitchButton(localResultsButton);

    const globalResultsButton = document.createElement('button');
    globalResultsButton.textContent = '🌍 Globalni';
    styleSwitchButton(globalResultsButton);

    buttonContainer.appendChild(localResultsButton);
    buttonContainer.appendChild(globalResultsButton);

    resultsOverlay.appendChild(buttonContainer);

    const resultsContent = document.createElement('div');
    resultsContent.classList.add('rezultati-content');

    const resultsDisplay = document.createElement('div');
    resultsContent.appendChild(resultsDisplay);

    localResultsButton.addEventListener('click', () => {
        displayLocalResults(resultsDisplay);
        localResultsButton.classList.add('active');
        globalResultsButton.classList.remove('active');
    });

    globalResultsButton.addEventListener('click', () => {
        displayGlobalResults(resultsDisplay);
        globalResultsButton.classList.add('active');
        localResultsButton.classList.remove('active');
    });

    // Inicijalno prikazujemo lokalne rezultate
    displayLocalResults(resultsDisplay);
    localResultsButton.classList.add('active');

    resultsOverlay.appendChild(resultsContent);

    // Dugme za zatvaranje
    const closeButton = document.createElement('button');
    closeButton.textContent = '❌ Zatvori';
    closeButton.classList.add('rezultati-close-button');

    closeButton.addEventListener('click', () => {
        levelDisappearSound.play();
        resultsOverlay.classList.remove('overlay-enter');
        resultsOverlay.classList.add('overlay-exit');
        backgroundOverlay.classList.remove('background-fade-in');
        backgroundOverlay.classList.add('background-fade-out');
        resultsOverlay.addEventListener('animationend', () => {
            document.body.removeChild(resultsOverlay);
        }, { once: true });
        backgroundOverlay.addEventListener('animationend', () => {
            document.body.removeChild(backgroundOverlay);
        }, { once: true });

    });

    // Dodajemo dugme za zatvaranje ispod tabela, izvan pozadine
    resultsOverlay.appendChild(closeButton);

    document.body.appendChild(resultsOverlay);
}

function calculateGameDuration() {
    const endTime = Date.now();
    const totalSeconds = Math.floor((endTime - startTime) / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    return `${minutes} min ${seconds} sek`;
}

function parseAndFormatDate(storedDate) {
    if (!storedDate) return '';
    
    // Check if storedDate is already in the format dd.mm.yy or dd.mm.yyyy
    if (/^\d{2}\.\d{2}\.\d{2,4}$/.test(storedDate)) {
        let parts = storedDate.split('.');
        let day = parts[0];
        let month = parts[1];
        let year = parts[2].slice(-2); // Get last two digits of the year
        return `${day}.${month}.${year}`;
    }
    
    // Try to parse the date string
    const date = new Date(storedDate);
    if (isNaN(date.getTime())) return storedDate;
    
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
    const year = String(date.getFullYear()).slice(-2); // Get last two digits of the year
    return `${day}.${month}.${year}`;
}
function saveCurrentResult() {
    console.log("saveCurrentResult funkcija pozvana");

    let levelReached;
    if (isTimeAttackMode) {
        console.log("Time Attack mod je aktivan. Trenutni indeks nivoa: ", currentTimeAttackLevelIndex);
        levelReached = currentTimeAttackLevelIndex + 1;
        console.log("Dostignuti nivo (Time Attack): ", levelReached);
    } else {
        console.log("Standardni mod igre je aktivan. Trenutni indeks nivoa: ", currentLevelIndex);
        levelReached = currentLevelIndex + 1;
        console.log("Dostignuti nivo (Standardni mod): ", levelReached);
    }

    console.log("Trenutni mod igre: ", currentGameMode);
    let resultData = {};

    const playerData = JSON.parse(localStorage.getItem('playerData'));
    if (!playerData || !playerData.playerName) {
        console.error('Nema podataka o igraču. Rezultat neće biti sačuvan.');
        alert('Greška: Podaci o igraču nisu dostupni. Rezultat nije sačuvan.');
        return;
    }

    const deviceInfo = navigator.userAgent;

    if (currentGameMode === 'Dokle vise') {
        const duration = calculateGameDuration();
        console.log("Trajanje igre izračunato: ", duration);
        console.log("Rezultat će biti sačuvan za 'Dokle vise' mod.");
        
        resultData = {
            sessionId: sessionId,
            playerName: playerData.playerName,
            gameMode: currentGameMode,
            difficulty: "N/A",
            score: score,
            levelReached: levelReached,
            duration: duration,
            date: new Date().toISOString().split('T')[0],
            deviceInfo: deviceInfo
        };

        // Poziv originalne funkcije saveBestDokleViseResult (NE MIJENJA SE)
        saveBestDokleViseResult(score, duration, levelReached);
        console.log("Rezultat za 'Dokle vise' kreiran.");
    } else {
        console.log("Rezultat će biti kreiran za mod: ", currentGameMode, " na težini: ", selectedDifficulty);
        
        resultData = {
            sessionId: sessionId,
            playerName: playerData.playerName,
            gameMode: currentGameMode,
            difficulty: selectedDifficulty,
            score: score,
            levelReached: levelReached,
            duration: currentGameMode === 'Dokle vise' ? calculateGameDuration() : '',
            date: new Date().toISOString().split('T')[0],
            deviceInfo: deviceInfo
        };

        // Poziv originalne funkcije saveBestResult (NE MIJENJA SE)
        saveBestResult(currentGameMode, selectedDifficulty, score, levelReached);
        console.log("Rezultat za drugi mod kreiran.");
    }

    console.log("Provjera internet konekcije...");
    checkOnlineStatus().then(isOnline => {
        if (isOnline) {
            console.log("Internet konekcija postoji. Pokušavam poslati rezultat na server.");
            sendResultToServer(resultData).then(success => {
                if (!success) {
                    console.log("Slanje na server nije uspjelo. Snimam rezultat lokalno.");
                    storeUnsentResult(resultData);
                }
            });
        } else {
            console.log("Nema internet konekcije. Rezultat će biti sačuvan za kasnije slanje.");
            storeUnsentResult(resultData);
        }
    }).catch(error => {
        console.error("Greška pri provjeri internet konekcije:", error);
        console.log("Pretpostavljam da nema internet konekcije. Rezultat će biti sačuvan za kasnije slanje.");
        storeUnsentResult(resultData);
    });

    console.log("Funkcija saveCurrentResult završena.");
}

function checkOnlineStatus() {
    return fetch('https://jami.ba/online-check.txt', { method: 'GET', cache: 'no-store' })
        .then(response => response.ok ? true : false)
        .catch(() => false);
}

function sendResultToServer(resultData) {
    console.log("Podaci za slanje na server:", resultData);

    return fetch('https://jami.ba/jgngame/save_game_result.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(resultData)
    })
    .then(response => {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return response.json();
        } else {
            throw new Error("Server nije vratio JSON odgovor.");
        }
    })
    .then(data => {
        if (data.status === 'success') {
            console.log('Rezultat igre snimljen na serveru.');
            // Ako je slučajno ovaj rezultat bio offline snimljen, obriši ga
            removeSentResult(resultData);
            return true;
        } else {
            console.error('Greška pri snimanju rezultata na serveru:', data.message);
            return false;
        }
    })
    .catch(error => {
        console.error('Greška pri slanju rezultata na server:', error);
        return false;
    });
}

function storeUnsentResult(resultData) {
    if (!resultData || typeof resultData !== 'object') {
        console.error('Pokušaj pohrane nevažećih podataka u unsentResults:', resultData);
        return;
    }

    let unsentResults = JSON.parse(localStorage.getItem('unsentResults')) || [];
    unsentResults.push(resultData);
    localStorage.setItem('unsentResults', JSON.stringify(unsentResults));
    console.log("Rezultat sačuvan lokalno za kasnije slanje:", resultData);
    console.log("Trenutno pohranjeni neslani rezultati:", unsentResults);
}

function cleanOldUnsentData() {
    if (localStorage.getItem('unsentdata')) {
        localStorage.removeItem('unsentdata');
        console.log("'unsentdata' ključ je obrisan iz localStorage.");
    }
}
cleanOldUnsentData();

let connectionCheckTimerId = setInterval(() => {
    checkOnlineStatus().then(isOnline => {
        if (isOnline) {
            console.log('Korisnik je online. Sinhronizujem offline rezultate.');
            syncOfflineScores();
        } else {
            console.log('Korisnik je offline.');
        }
    });
}, 21000); // provjera svakih 12 sekundi

function syncOfflineScores() {
    let unsentResults = JSON.parse(localStorage.getItem('unsentResults')) || [];
    if (unsentResults.length === 0) {
        console.log('Nema neslanih rezultata za sinhronizaciju.');
        return;
    }

    console.log(`Imam ${unsentResults.length} neslanih rezultata za sinhronizaciju.`);
    
    // Pokušaj slanja svakog rezultata, paralelno ili serijski
    const resultsToSync = [...unsentResults]; 
    let promises = resultsToSync.map(r => sendResultToServer(r));

    Promise.all(promises).then(results => {
        // results je niz booleana (true/false) ovisno o uspješnosti slanja
        console.log("Završena sinhronizacija offline rezultata.");
    }).catch(err => {
        console.error("Greška prilikom sinhronizacije offline rezultata:", err);
    });
}

function removeSentResult(sentResult) {
    let unsentResults = JSON.parse(localStorage.getItem('unsentResults')) || [];
    const originalLength = unsentResults.length;
    
    unsentResults = unsentResults.filter(result => {
        return !(
            result.gameMode === sentResult.gameMode &&
            result.difficulty === sentResult.difficulty &&
            result.score === sentResult.score &&
            result.levelReached === sentResult.levelReached &&
            result.date === sentResult.date &&
            result.playerName === sentResult.playerName
        );
    });

    if (unsentResults.length !== originalLength) {
        localStorage.setItem('unsentResults', JSON.stringify(unsentResults));
        console.log("Poslani rezultat uklonjen iz offline spiska. Preostali:", unsentResults);
    }
}

function generateSessionId() {
    return 'session-' + Date.now() + '-' + Math.floor(Math.random() * 1000000);
}

function destroyAllTimers() {
    let id = setTimeout(() => {}, 0); // Dohvati najveći ID tajmera
    while (id >= 0) {
        if (id !== connectionCheckTimerId && id !== crownTimerId && id !== goldTimerId) { // Preskoči specifične tajmere
            clearTimeout(id);
            clearInterval(id);
        }
        id--;
    }
    console.log("Svi tajmeri su očišćeni, osim connectionCheckTimerId i crownTimerId.");
}               

/****************************************
 * Globalne varijable (primjer)
 ****************************************/
let multicijena = 1.5;       // Multiplikator cijene

// Pomoćne globalne varijable ako ti trebaju (broj duplih poena, bonus, itd.):
let duplipoeniskroz = 1, duplipoeni = 1; let robot = 0;
let duplibonusskroz = 1, duplibonus = 1;
let kupljenoprikazivanjeskroz = 0, kupljenovrijemeskroz = 0, kupljenipoteziskroz = 0; // trajno
let kupljenoprikazivanje = 0, kupljenovrijeme = 0, kupljenipotezi = 0; // sljedeci nivo
/****************************************
 * Niz artikala
 ****************************************/
 let artikliShop = [
  /* =========== SLJEDEĆI NIVO =========== */
  {
    naziv: "Produži prikazivanje kartica na sljedećem nivou za +0.8s",
    displayName: "Produži prikazivanje kartica +0.8s",
    kategorija: "sljedeci",
    cijenaDijamant: 200,
    cijenaGold: null,
    kupiHandler: function() {
      kupljenoprikazivanje += 0.8;
    },
    kupljen: 0,
    kupovineNivo: 0,
    maxKupovinaNivo: 2,
    maxKupovinaGlobal: 9999,
    resetOnLevelStart: true
  },
  {
    naziv: "Produži trajanje sljedećeg nivoa +2s",
    displayName: "Produži trajanje nivoa +2s",
    kategorija: "sljedeci",
    cijenaDijamant: 200,
    cijenaGold: null,
    kupiHandler: function() {
      kupljenovrijeme += 2;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 2,
    maxKupovinaGlobal: 9999,
    resetOnLevelStart: true
  },
  {
    naziv: "Dodaj 2 poteza sljedeći nivo",
    displayName: "Dodaj 2 poteza",
    kategorija: "sljedeci",
    cijenaDijamant: 200,
    cijenaGold: null,
    kupiHandler: function() {
      kupljenipotezi += 2;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 2,
    maxKupovinaGlobal: 9999,
    resetOnLevelStart: true
  },
  {
    naziv: "Dupli poeni sljedeći nivo",
    displayName: "Dupli poeni",
    kategorija: "sljedeci",
    cijenaDijamant: 300,
    cijenaGold: null,
    kupiHandler: function() {
      duplipoeni *= 2;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 1,
    maxKupovinaGlobal: 9999,
    resetOnLevelStart: true
  },
  {
    naziv: "Dupli bonus sljedeći nivo",
    displayName: "Dupli bonus",
    kategorija: "sljedeci",
    cijenaDijamant: 300,
    cijenaGold: null,
    kupiHandler: function() {
      duplibonus *= 2;
      console.log("Vrijednost duplibonus nakon kupovine:", duplibonus);
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 1,
    maxKupovinaGlobal: 9999,
    resetOnLevelStart: true
  },

  /* =========== TRAJNO =========== */
  {
    naziv: "Kupi dodatni život",
    displayName: "Kupi dodatni život",
    kategorija: "cijela",
    cijenaDijamant: 4800,
    cijenaGold: 1,
    kupiHandler: function() {
        lives +=1;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 0,
    maxKupovinaGlobal: 1,
    resetOnLevelStart: false
  },
  {
    naziv: "Produži prikazivanje kartica +0.8s (dok traje igra)",
    displayName: "Produži prikazivanje kartica +0.8s",
    kategorija: "cijela",
    cijenaDijamant: 2500,
    cijenaGold: 1,
    kupiHandler: function() {
      kupljenoprikazivanjeskroz += 0.8;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 0,
    maxKupovinaGlobal: 3,
    resetOnLevelStart: false
  },
  {
    naziv: "Trajanje nivoa +2s (dok traje igra)",
    displayName: "Trajanje nivoa +2s",
    kategorija: "cijela",
    cijenaDijamant: 2500,
    cijenaGold: 1,
    kupiHandler: function() {
      kupljenovrijemeskroz += 2;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 0,
    maxKupovinaGlobal: 3,
    resetOnLevelStart: false
  },
  {
    naziv: "Dodati 2 poteza (dok traje igra)",
    displayName: "Dodati 2 poteza",
    kategorija: "cijela",
    cijenaDijamant: 2500,
    cijenaGold: 1,
    kupiHandler: function() {
      kupljenipoteziskroz += 2;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 0,
    maxKupovinaGlobal: 3,
    resetOnLevelStart: false
  },
  {
    naziv: "Dupli poeni (dok traje igra)",
    displayName: "Dupli poeni",
    kategorija: "cijela",
    cijenaDijamant: 6000,
    cijenaGold: 1,
    kupiHandler: function() {
      duplipoeniskroz *= 2;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 0,
    maxKupovinaGlobal: 1,
    resetOnLevelStart: false
  },
  {
    naziv: "Dupli bonus (dok traje igra)",
    displayName: "Dupli bonus",
    kategorija: "cijela",
    cijenaDijamant: 6000,
    cijenaGold: 1,
    kupiHandler: function() {
      duplibonusskroz *= 2;
    },
    kupovineNivo: 0,
    kupljen: 0,
    maxKupovinaNivo: 0,
    maxKupovinaGlobal: 1,
    resetOnLevelStart: false
  },

  /********** NOVO: Robot prebačen u 'cijela' **********/
  {
  naziv: "Unajmi robota",
  displayName: "🤖 Unajmi robota",
  kategorija: "cijela",

  // Za robota postavimo početno na null,
  // jer ćemo cene posebno obraditi u kreirajRedArtikla
  cijenaDijamant: null,
  cijenaGold: null,

  kupiHandler: function() {
    // Povećavamo broj raspoloživih robota
    robot++; checkRobotButton(); 
    // Zvuk pri kupovini robota
    const robotSound = new Audio('sounds/robot.mp3');
    robotSound.play();
  },

  kupovineNivo: 0,
  kupljen: 0,
  maxKupovinaNivo: 0,
  maxKupovinaGlobal: 2,     // Dozvoljene su najviše 2 kupovine po jednoj igri
  resetOnLevelStart: false
},
];

function resetKupovineNivo() {
  artikliShop.forEach(artikal => {
    if (artikal.resetOnLevelStart) {
      artikal.kupovineNivo = 0;
    }
  });
}

function resetShop() {
  artikliShop.forEach(artikal => {
    // Resetuj kupovine po nivou za artikle koji se resetuju
    if (artikal.resetOnLevelStart) {
      artikal.kupovineNivo = 0;
      artikal.kupljen = 0;
    }
    
    // Resetuj trajne kupovine samo ako baš želiš kompletan reset
    if (artikal.kategorija === 'cijela') {
      artikal.kupljen = 0;
      artikal.kupovineNivo = 0;
    }
  });
  
  // Resetuj i globalne varijable
  duplipoeni = 1;
  duplibonus = 1;
  duplipoeniskroz = 1;
  duplibonusskroz = 1;
  kupljenoprikazivanje = 0;
  kupljenoprikazivanjeskroz = 0;
  kupljenovrijeme = 0;
  kupljenovrijemeskroz = 0;
  kupljenipotezi = 0;
  kupljenipoteziskroz = 0;
  robot = 0;
}

// Funkcija sljedeciNivoEnabled - ne menjamo
function sljedeciNivoEnabled(artikal) {
  if (artikal.kategorija !== "sljedeci") return true;
  const n = artikal.naziv.toLowerCase();
  if (n.includes("dupli") || n.includes("poeni") || n.includes("bonus")) {
    return true;
  }
  if (n.includes("poteza")) {
    if (window.levelType === 'Tip nivoa: Hibrid' || window.levelType === 'Tip nivoa: Potezi') {
      return true;
    }
    return false;
  }
  if (n.includes("vrijeme") || n.includes("trajanje") || n.includes("+2s")) {
    if (window.levelType === 'Tip nivoa: Hibrid' || window.levelType === 'Tip nivoa: Vrijeme') {
      return true;
    }
    return false;
  }
  return true;
}

// Funkcija trajnaKupovinaEnabled - ne menjamo logiku
function trajnaKupovinaEnabled(artikal) {
  console.log("Početak provjere za artikal:", artikal);
  console.log("Vrijednost imenivoa:", imenivoa);

  if (artikal.kategorija !== 'cijela') {
    console.log(`Artikal '${artikal.naziv}' ima kategoriju '${artikal.kategorija}', dozvoljeno.`);
    return true;
  }

  const n = artikal.naziv.toLowerCase();
  console.log(`Provjera naziva artikla (lowercase): '${n}'`);

  // standardica -> onemogućeno +2 poteza
  if (imenivoa.toLowerCase().includes("standardica")) {
    console.log("Nivo: Standardica");
    if (n.includes("+2 poteza") || n.includes("2 poteza")) {
      console.log("Artikal sadrži '+2 poteza' - onemogućeno.");
      return false;
    }
  }

  // klasika -> onemogućeno +2s, "vrijeme", "trajanje"
  if (imenivoa.toLowerCase().includes("klasika")) {
    console.log("Nivo: Klasika");
    if (n.includes("+2s") || n.includes("vrijeme") || n.includes("trajanje")) {
      console.log("Artikal sadrži zabranjene riječi ('+2s', 'vrijeme' ili 'trajanje') - onemogućeno.");
      return false;
    }
  }

  // specijal -> sve dozvoljeno
  if (imenivoa.toLowerCase().includes("specijal")) {
    console.log("Nivo: Specijal - sve dozvoljeno.");
  }

  console.log(`Artikal '${artikal.naziv}' je dozvoljen.`);
  return true;
}

// Glavna funkcija za prikaz shop-a
function prikaziShopProzor() {
  // Zvuk ulaska u shop
  const ulazshop = new Audio('sounds/ulazshop.mp3');
  ulazshop.play();

  // Proveravamo da li je shop već otvoren
  if (document.getElementById('shop-overlay')) {
    return;
  }

  // Kreiramo overlay (pozadinski sloj)
  const overlay = document.createElement('div');
  overlay.id = 'shop-overlay';
  overlay.classList.add('shop-overlay');

  // Glavni kontejner za shop
  const shopContainer = document.createElement('div');
  shopContainer.classList.add('shop-container');

  // TOP ROW: prikaz stanja (lives, dijamanti, gold)
  const topRow = document.createElement('div');
  topRow.classList.add('shop-top-row');

  const scoreContainer = document.createElement('div');
  scoreContainer.classList.add('shop-score-container');

  const lblStanje = document.createElement('div');
  lblStanje.innerText = `${lives} ❤️`;
  lblStanje.style.fontWeight = 'bold';
  lblStanje.style.fontSize = '1.3rem';

  const lblDijamanti = document.createElement('div');
  lblDijamanti.innerText = `${score} 💎`;
  lblDijamanti.id = 'shop-diamonds-label';
  lblDijamanti.style.fontWeight = 'bold';
  lblDijamanti.style.fontSize = '1.3rem';

  const lblZlatnici = document.createElement('div');
  lblZlatnici.innerText = `${gold} 👑`;
  lblZlatnici.id = 'shop-gold-label';
  lblZlatnici.style.fontWeight = 'bold';
  lblZlatnici.style.fontSize = '1.3rem';

  scoreContainer.appendChild(lblStanje);
  scoreContainer.appendChild(lblDijamanti);
  scoreContainer.appendChild(lblZlatnici);

  // Slika „Shop“
  const shopImage = document.createElement('img');
  shopImage.src = 'images/shop.webp';
  shopImage.alt = 'Shop';
  shopImage.classList.add('shop-image');

  topRow.appendChild(scoreContainer);
  topRow.appendChild(shopImage);
  shopContainer.appendChild(topRow);

  // Kreiramo kontejner za tabelu (scrollable)
  const tableContainer = document.createElement('div');
  tableContainer.classList.add('shop-table-container');
  tableContainer.style.maxHeight = '400px';
  tableContainer.style.overflowY = 'auto';
  tableContainer.style.marginBottom = '20px';

  // Jedna jedinstvena <table>
  const table = document.createElement('table');
  table.classList.add('shop-table');

  // THEAD
  const thead = document.createElement('thead');
  thead.classList.add('shop-sticky-header');

  const headerRow = document.createElement('tr');
  headerRow.style.backgroundColor = '#444444';
  headerRow.style.color = '#ffffff';
  headerRow.style.fontWeight = 'bold';
  headerRow.style.fontFamily = 'Arial Narrow';
  headerRow.style.textShadow = '1px 1px 2px black';

  const thArtikal = document.createElement('th');
  thArtikal.innerText = 'Artikal';
  headerRow.appendChild(thArtikal);

  const thCijena = document.createElement('th');
  thCijena.innerText = 'Cijena';
  headerRow.appendChild(thCijena);

  const thKupovina = document.createElement('th');
  thKupovina.innerText = 'Kupovina';
  headerRow.appendChild(thKupovina);

  thead.appendChild(headerRow);
  table.appendChild(thead);

  // TBODY
  const tbody = document.createElement('tbody');
  table.appendChild(tbody);

  // 1) Naslov za SLJEDECI NIVO
  const trSljedeciTitle = document.createElement('tr');
  trSljedeciTitle.style.backgroundColor = '#000000';
  trSljedeciTitle.style.color = '#fff';
  trSljedeciTitle.style.fontWeight = 'bold';
  trSljedeciTitle.style.fontFamily = 'Arial Narrow';
  trSljedeciTitle.style.textShadow = '1px 1px 2px black';

  const tdSljedeciTitle = document.createElement('td');
  tdSljedeciTitle.colSpan = 3;
  tdSljedeciTitle.innerText = 'Kupovina za naredni nivo';
  tdSljedeciTitle.style.textAlign = 'center';
  trSljedeciTitle.appendChild(tdSljedeciTitle);
  tbody.appendChild(trSljedeciTitle);

  // Filtriramo artikle kategorije "sljedeci"
  const sljedeciItems = artikliShop.filter(a => a.kategorija === 'sljedeci');

  // 2) Naslov za CIJELA (do kraja igre)
  // Filtriramo artikle kategorije "cijela"
  const cijelaItems = artikliShop.filter(a => a.kategorija === 'cijela');

  // Funkcija koja kreira jedan <tr> za dati artikal
  function kreirajRedArtikla(artikal, bojaPozadine) {
    const tr = document.createElement('tr');
    tr.style.backgroundColor = bojaPozadine;
    tr.style.fontFamily = 'Arial Narrow';
    tr.style.fontWeight = 'bold';
    tr.style.color = '#000000';

    // --- Kolona 1: Naziv artikla ---
    const tdNaziv = document.createElement('td');
    tdNaziv.innerText = artikal.displayName || artikal.naziv;
    tr.appendChild(tdNaziv);

    // --- Kolona 2: Cijena (dva dugmeta: dijamanti / gold) ---
    const tdCijena = document.createElement('td');
    tdCijena.style.whiteSpace = 'nowrap';

    // DIJAMANTSKE CENE
    const btnDiamonds = document.createElement('button');
    btnDiamonds.classList.add('shop-button');
    btnDiamonds.style.backgroundColor = '#003366';
    
    let disabledDiamonds = false;
    let prikazanaCijenaDij = 0;

    // Ako je "Unajmi robota", fiksiramo cene iz niza [4500, 6500]
    if (artikal.naziv === "Unajmi robota") {
      if (artikal.kupljen >= 2) {
        // Već je 2x kupljeno, onemogućavamo
        disabledDiamonds = true;
        prikazanaCijenaDij = 6500; // prikazaće 6500 💎, ali disabled
      } else {
        prikazanaCijenaDij = robotCostsDiamonds[artikal.kupljen]; 
      }
    } else {
      // Inace koristimo stari sistem za artikle koji imaju cijenaDijamant
      if (artikal.cijenaDijamant !== null) {
        let basePrice = artikal.cijenaDijamant * Math.pow(multicijena, artikal.kupljen);
        basePrice = basePrice * (1 - (currentLevelIndex / 142));
        prikazanaCijenaDij = Math.floor(basePrice);
      }
    }

    if (prikazanaCijenaDij > 0) {
      btnDiamonds.innerText = `${prikazanaCijenaDij} 💎`;
    } else {
      // Ako nema cijenu u dijamantima, sakrij dugme
      if (artikal.naziv !== "Unajmi robota") {
        btnDiamonds.style.display = 'none';
      }
    }

    // Provera ograničenja
    if (artikal.kategorija === 'sljedeci') {
      if (artikal.kupovineNivo >= artikal.maxKupovinaNivo) {
        disabledDiamonds = true;
      }
      if (!sljedeciNivoEnabled(artikal)) {
        disabledDiamonds = true;
      }
    } else {
      // kategorija 'cijela'
      if (artikal.kupljen >= artikal.maxKupovinaGlobal) {
        disabledDiamonds = true;
      }
      if (!trajnaKupovinaEnabled(artikal)) {
        disabledDiamonds = true;
      }
    }
    if (score < prikazanaCijenaDij) {
      // Nemamo dovoljno dijamanata
      disabledDiamonds = true;
    }

    if (disabledDiamonds) {
      btnDiamonds.disabled = true;
      btnDiamonds.style.opacity = 0.4;
    }

    // Event listener za kupovinu dijamantima
    btnDiamonds.addEventListener('click', () => {
      if (!btnDiamonds.disabled) {
        score -= prikazanaCijenaDij;
        score2 = score;
        lblDijamanti.innerText = `${score} 💎`;

        // Animacija dijamanata
        lblDijamanti.classList.remove('shop-change-anim');
        void lblDijamanti.offsetWidth;
        lblDijamanti.classList.add('shop-change-anim');

        // Handler kupovine
        artikal.kupiHandler();
        artikal.kupljen++;
        if (artikal.kategorija === 'sljedeci') {
          artikal.kupovineNivo++;
        }

        // Zvuk plaćanja
        const platiSound = new Audio('sounds/plati.mp3');
        platiSound.play();

        // Osvježimo tabelu
        osvjeziTabelu();
      }
    });

    // Dodaj dijamantsko dugme u kolonu
    tdCijena.appendChild(btnDiamonds);

    // GOLD
    const btnGold = document.createElement('button');
    btnGold.classList.add('shop-button');
    btnGold.style.backgroundColor = '#000000';
    btnGold.style.marginLeft = '10px';

    let prikazanaGold = artikal.cijenaGold;

    // Ako je robot, gold fiksno = 1
    if (artikal.naziv === "Unajmi robota") {
      prikazanaGold = robotCostGold; // = 1
    }

    if (prikazanaGold === null) {
      // Ako artikal nema gold cenu => sakrij dugme
      btnGold.style.display = 'none';
    } else {
      btnGold.innerText = `${prikazanaGold} 👑`;
    }

    let disabledGold = false;
    if (artikal.kategorija === 'sljedeci') {
      if (artikal.kupovineNivo >= artikal.maxKupovinaNivo) {
        disabledGold = true;
      }
      if (!sljedeciNivoEnabled(artikal)) {
        disabledGold = true;
      }
    } else {
      // 'cijela'
      if (artikal.kupljen >= artikal.maxKupovinaGlobal) {
        disabledGold = true;
      }
      if (!trajnaKupovinaEnabled(artikal)) {
        disabledGold = true;
      }
    }
    // Nemamo dovoljno golda
    if (gold < prikazanaGold) {
      disabledGold = true;
    }
    // Ako je robot već 2x kupljen => disable
    if (artikal.naziv === "Unajmi robota" && artikal.kupljen >= 2) {
      disabledGold = true;
    }

    if (disabledGold) {
      btnGold.disabled = true;
      btnGold.style.opacity = 0.4;
    }

    // Event listener za kupovinu goldom
    btnGold.addEventListener('click', () => {
      if (!btnGold.disabled) {
        gold -= prikazanaGold;
        updateGoldOnly();
        lblZlatnici.innerText = `${gold} 👑`;
        lblZlatnici.classList.remove('shop-change-anim');
        void lblZlatnici.offsetWidth;
        lblZlatnici.classList.add('shop-change-anim');

        artikal.kupiHandler();
        artikal.kupljen++;
        if (artikal.kategorija === 'sljedeci') {
          artikal.kupovineNivo++;
        }

        // Ako je "Kupi dodatni život"
        if (artikal.naziv === "Kupi dodatni život") {
          lifesound.play();
          showHeartAnimation();
          lblStanje.classList.remove('shop-change-anim-lives');
          void lblStanje.offsetWidth;
          lblStanje.innerText = `${lives} ❤️`;
          lblStanje.classList.add('shop-change-anim-lives');
        }

        // Robot zvuk se već pušta u artikal.kupiHandler

        const platiSound = new Audio('sounds/plati.mp3');
        platiSound.play();

        osvjeziTabelu();
      }
    });

    // Dodaj gold dugme u kolonu
    tdCijena.appendChild(btnGold);

    tr.appendChild(tdCijena);

    // --- Kolona 3: Kupovina (X/Y) ---
    const tdKup = document.createElement('td');
    if (artikal.kategorija === 'sljedeci') {
      tdKup.innerText = `${artikal.kupovineNivo}/${artikal.maxKupovinaNivo}`;
    } else {
      tdKup.innerText = `${artikal.kupljen}/${artikal.maxKupovinaGlobal}`;
    }
    tr.appendChild(tdKup);

    return tr;
  }

  // Funkcija za osvežavanje tabele
  function osvjeziTabelu() {
    tbody.innerHTML = '';

    // 1) Red "Kupovina za naredni nivo"
    const trSljTitle = document.createElement('tr');
    trSljTitle.style.backgroundColor = '#880000';
    trSljTitle.style.color = '#fff';
    trSljTitle.style.fontWeight = 'bold';
    trSljTitle.style.fontFamily = 'Arial Narrow';
    trSljTitle.style.textShadow = '1px 1px 2px black';

    const tdSljTitle = document.createElement('td');
    tdSljTitle.colSpan = 3;
    tdSljTitle.innerText = 'Kupovina za naredni nivo';
    tdSljTitle.style.textAlign = 'center';
    trSljTitle.appendChild(tdSljTitle);
    tbody.appendChild(trSljTitle);

    // Ispišemo sve "sljedeci" artikle
    sljedeciItems.forEach(art => {
      const row = kreirajRedArtikla(art, '#fcd9c5');
      tbody.appendChild(row);
    });

    // 2) Red "Kupovina do kraja trenutne igre"
    const trCijTitle = document.createElement('tr');
    trCijTitle.style.backgroundColor = '#006600';
    trCijTitle.style.color = '#fff';
    trCijTitle.style.fontWeight = 'bold';
    trCijTitle.style.fontFamily = 'Arial Narrow';
    trCijTitle.style.textShadow = '1px 1px 2px black';

    const tdCijTitle = document.createElement('td');
    tdCijTitle.colSpan = 3;
    tdCijTitle.innerText = 'Kupovina do kraja trenutne igre';
    tdCijTitle.style.textAlign = 'center';
    trCijTitle.appendChild(tdCijTitle);
    tbody.appendChild(trCijTitle);

    // Ispišemo sve "cijela" artikle
    cijelaItems.forEach(art => {
      const row = kreirajRedArtikla(art, '#e7facd');
      tbody.appendChild(row);
    });
  }

  // Inicijalno pozivamo osvjeziTabelu
  osvjeziTabelu();

  // Ubacujemo tabelu u tableContainer
  tableContainer.appendChild(table);
  shopContainer.appendChild(tableContainer);

  // Dugme "Završi kupovinu"
  const finishButton = document.createElement('button');
  finishButton.innerText = "Završi kupovinu";
  finishButton.classList.add('shop-main-button');
  finishButton.addEventListener('click', () => {
    zatvoriShop();
  });
  shopContainer.appendChild(finishButton);

  overlay.appendChild(shopContainer);
  document.body.appendChild(overlay);

  // Animacija skrolovanja (opciono)
  setTimeout(() => {
    const scrollHeight = tableContainer.scrollHeight;
    tableContainer.scrollTo({ top: scrollHeight, behavior: 'smooth' });
    setTimeout(() => {
      tableContainer.scrollTo({ top: 0, behavior: 'smooth' });
    }, 800);
  }, 300);

  // Zvuk shop-a
  const shopSound = new Audio('sounds/shop.mp3');
  shopSound.play();
  shopSound.loop = true;

  // Funkcija za zatvaranje shopa
  function zatvoriShop() {
    
    const izlazShopSound = new Audio('sounds/izlazshop.mp3');
    izlazShopSound.play();

    if (typeof fadeOutSound === 'function') {
      fadeOutSound(shopSound, 1200);
    } else {
      shopSound.pause();
    }

    overlay.style.animation = 'shopFadeOut 0.4s ease forwards';
    shopContainer.style.animation = 'shopBounceOut 0.6s cubic-bezier(.34,1.56,.64,1) forwards';

    // Refresh level notifikacije (npr. da se ažuriraju potezi, vrijeme, robot dugme...)
    shopRefreshShowLevelNotification();
    checkRobotButton();
    setTimeout(() => {
      if (overlay.parentNode) {
        overlay.parentNode.removeChild(overlay);
      }
    }, 600);
  }
}




function inicijalizirajShopHandler() {
  let uspjesnoPostavljenih = 0;

  artikliShop.forEach(artikal => {
    switch (artikal.naziv) {
      case "Produži prikazivanje kartica na sljedećem nivou za +0.8s":
        artikal.kupiHandler = function() { kupljenoprikazivanje += 0.8; };
        uspjesnoPostavljenih++;
        break;
      case "Produži trajanje sljedećeg nivoa +2s":
        artikal.kupiHandler = function() { kupljenovrijeme += 2; };
        uspjesnoPostavljenih++;
        break;
      case "Dodaj 2 poteza sljedeći nivo":
        artikal.kupiHandler = function() { kupljenipotezi += 2; };
        uspjesnoPostavljenih++;
        break;
      case "Dupli poeni sljedeći nivo":
        artikal.kupiHandler = function() { duplipoeni *= 2; };
        uspjesnoPostavljenih++;
        break;
      case "Dupli bonus sljedeći nivo":
        artikal.kupiHandler = function() { duplibonus *= 2; };
        uspjesnoPostavljenih++;
        break;
      case "Kupi dodatni život":
        artikal.kupiHandler = function() { lives++; };
        uspjesnoPostavljenih++;
        break;
      case "Produži prikazivanje kartica +0.8s (dok traje igra)":
        artikal.kupiHandler = function() { kupljenoprikazivanjeskroz += 0.8; };
        uspjesnoPostavljenih++;
        break;
      case "Trajanje nivoa +2s (dok traje igra)":
        artikal.kupiHandler = function() { kupljenovrijemeskroz += 2; };
        uspjesnoPostavljenih++;
        break;
      case "Dodati 2 poteza (dok traje igra)":
        artikal.kupiHandler = function() { kupljenipoteziskroz += 2; };
        uspjesnoPostavljenih++;
        break;
      case "Dupli poeni (dok traje igra)":
        artikal.kupiHandler = function() { duplipoeniskroz *= 2; };
        uspjesnoPostavljenih++;
        break;
      case "Dupli bonus (dok traje igra)":
        artikal.kupiHandler = function() { duplibonusskroz *= 2; };
        uspjesnoPostavljenih++;
        break;
        case "Unajmi robota":
        artikal.kupiHandler = function() { robot ++; checkRobotButton();};
        uspjesnoPostavljenih++;
        break;
      default:
        console.warn(`Artikal '${artikal.naziv}' nije pronađen u inicijalizaciji.`);
    }
  });

  // Logovanje potvrde da je sve prošlo kako treba
  console.log(`Inicijalizacija shop handlera završena. Ukupno uspješno postavljenih handlera: ${uspjesnoPostavljenih}/${artikliShop.length}`);

  if (uspjesnoPostavljenih === artikliShop.length) {
    console.log("Svi handleri su uspješno postavljeni! ✔️");
  } else {
    console.warn("Neki handleri nisu postavljeni. Provjeri artikle! ⚠️");
  }
}
function pauseAllAudio() {
    console.log("Pausing all currently playing audio...");
    window.playingAudio.forEach(audio => {
        console.log(`Pausing audio: ${audio.src}`);
        audio.pause();

        // Dodaj u pausedAudio ako već nije tamo
        if (!window.pausedAudio.includes(audio)) {
            window.pausedAudio.push(audio);
        }
    });
}

function resumeAllAudio() {
    console.log("Resuming all paused audio objects...");
    window.pausedAudio.forEach(audio => {
        console.log(`Restarting audio: ${audio.src}`);
        audio.currentTime = 0; // Resetuj na početak
        audio.play().catch(err => console.error(`Failed to play audio: ${err.message}`));
    });

    // Očisti listu pauziranih zvukova nakon što ih pustiš
    window.pausedAudio = [];
}


</script>
</body>
</html>


