const gamePrefix = "WordScramble_";


runOnStartup(runtimeInstance => {
    runtime = runtimeInstance;
    if (runtime && runtime.assets) {
        console.log("Runtime hazır.");
    } else {
        console.warn("Runtime henüz hazır değil.");
        const interval = setInterval(() => {
            if (runtime && runtime.assets) {
                clearInterval(interval);
                console.log("Runtime hazır.");
            }
        }, 1000);
    }
});

let runtime;
let currentLevel = 0;

//GAMEMECHANICS//
let globalLevel = null;
let selectedWords = [];
let totalLetters = 0;
const LETTER_SIZE = 100;
const VERTICAL_SPACING = 85; 
function applyGravity(level) {
    const R = level.length;
    const C = level[0].length;
    for (let x = 0; x < C; x++) {
        let stack = [];
        for (let y = R - 1; y >= 0; y--) {
            if (level[y][x] !== null) {
                stack.push(level[y][x]);
            }
        }
        for (let y = R - 1; y >= 0; y--) {
            if (stack.length > 0) {
                level[y][x] = stack.shift();
            } else {
                level[y][x] = null;
            }
        }
    }
}
function isGridEmpty(level) {
    for (let r = 0; r < level.length; r++) {
        for (let c = 0; c < level[0].length; c++) {
            if (level[r][c] !== null) {
                console.log(`isGridEmpty: Hücre (${r}, ${c}) dolu.`);
                return false;
            }
        }
    }
    console.log("isGridEmpty: Grid tamamen boş.");
    return true;
}
function countPlayableWords(level) {
    let count = 0;
    if (!selectedWords || selectedWords.length === 0) {
        console.log("countPlayableWords: No words to search for (selectedWords is empty or null)");
        return 0;
    }
    
    console.log(`countPlayableWords: Starting to search for ${selectedWords.length} words in grid`);
    
    // First make a deep copy of the level to avoid modifying the original grid
    const levelCopy = JSON.parse(JSON.stringify(level));
    
    for (const wObj of selectedWords) {
        if (!wObj.found) {
            const W = wObj.word.toUpperCase();
            console.log(`countPlayableWords: Checking if word "${W}" exists in grid...`);
            
            const wordLocation = isWordInGrid(levelCopy, W);
            if (wordLocation) {
                console.log(`countPlayableWords: FOUND "${W}" at position (${wordLocation.startRow}, ${wordLocation.startCol}) in direction ${wordLocation.direction}`);
                count++;
            } else {
                console.log(`countPlayableWords: NOT FOUND "${W}" - this word is not in the grid`);
            }
        } else {
            console.log(`countPlayableWords: Skipping "${wObj.word}" as it's already found (found = true)`);
        }
    }
    
    console.log(`countPlayableWords: Found a total of ${count} playable words in the grid`);
    return count;
}
function anyPlayableWords(level) {
    const count = countPlayableWords(level);
    console.log(`anyPlayableWords: ${count > 0}`);
    return count > 0;
}
function isWordInGrid(level, W) {
    const rows = level.length;
    const cols = level[0].length;
    const directions = [
        { dx: 1, dy: 0, name: "yatay-sağ" },
        { dx: -1, dy: 0, name: "yatay-sol" },
        { dx: 0, dy: 1, name: "dikey-aşağı" },
        { dx: 0, dy: -1, name: "dikey-yukarı" }
    ];

    function checkDirection(x, y, dx, dy) {
        const foundLetters = [];
        for (let i = 0; i < W.length; i++) {
            const nx = x + i * dx;
            const ny = y + i * dy;
            
            // Boundary check
            if (nx < 0 || nx >= cols || ny < 0 || ny >= rows) {
                return false;
            }
            
            // Cell and value existence check
            if (!level[ny][nx] || level[ny][nx].value !== W[i]) {
                return false;
            }
            
            foundLetters.push({
                x: nx,
                y: ny,
                letter: level[ny][nx].value
            });
        }
        
        // Log every letter found in this direction for debugging
        const lettersStr = foundLetters.map(l => `(${l.x},${l.y}):${l.letter}`).join(', ');
        console.log(`isWordInGrid: Found "${W}" at (${x},${y}) direction (${dx},${dy}): ${lettersStr}`);
        
        return true;
    }

    for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
            if (level[y][x] && level[y][x].value === W[0]) {
                for (const dir of directions) {
                    if (checkDirection(x, y, dir.dx, dir.dy)) {
                        console.log(`isWordInGrid: Successfully found word "${W}" starting at (${x},${y}) in direction "${dir.name}"`);
                        return {
                            startRow: y,
                            startCol: x,
                            direction: dir.name
                        };
                    }
                }
            }
        }
    }
    
    console.log(`isWordInGrid: Word "${W}" not found in grid after complete search`);
    return false;
}
function rearrangeGrid(level) {
    console.log("rearrangeGrid: Grid yeniden düzenleniyor...");
    
    // Grid boyutlarını al
    const rows = 10; // Her zaman 10 satır
    const cols = 9;  // Her zaman 9 sütun

    // 1. Mevcut tüm harfleri toplama
    let allLetters = [];
    for (let y = 0; y < level.length; y++) {
        for (let x = 0; x < level[0].length; x++) {
            if (level[y][x] !== null) {
                allLetters.push(level[y][x].value);
            }
        }
    }

    // 2. Seçilen kelimelerin harflerini ayırma
    let selectedWordLetters = [];
    selectedWords.forEach(wObj => {
        selectedWordLetters = selectedWordLetters.concat(wObj.word.toUpperCase().split(''));
    });

    // 3. Kalan harfleri belirleme
    let remainingLetters = allLetters.slice(); // Kopya al
    selectedWordLetters.forEach(letter => {
        const index = remainingLetters.indexOf(letter);
        if (index !== -1) {
            remainingLetters.splice(index, 1);
        }
    });

    // 4. Grid'i temizleme
    for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
            level[y][x] = null;
        }
    }

    // 5. Seçilen kelimeleri grid'e yerleştirme
    selectedWords.forEach(wordObj => {
        if (!wordObj.found) {
            const W = wordObj.word.toUpperCase();
            let placed = false;
            const directions = [
                "horizontal",
                "vertical",
                "reverse-horizontal",
                "reverse-vertical"
            ];
            let attempts = 0;
            while (!placed && attempts < 100) {
                const direction = directions[Math.floor(Math.random() * directions.length)];
                const startX = Math.floor(Math.random() * cols);
                const startY = Math.floor(Math.random() * rows);
                if (canPlaceWord(level, rows, cols, W, direction, startX, startY)) {
                    placeWord(level, W, direction, startX, startY);
                    if (verifyPlacedWord(level, W, direction, startX, startY)) {
                        placed = true;
                        console.log(`rearrangeGrid: "${W}" kelimesi yerleştirildi.`);
                    } else {
                        undoPlaceWord(level, W, direction, startX, startY);
                    }
                }
                attempts++;
            }
            if (!placed) {
                console.error(`rearrangeGrid: "${W}" kelimesi gridde yerleştirilemedi.`);
            }
        }
    });

    // 6. Kalan harfleri rastgele yerleştirme
    // Harfleri karıştırma
    for (let i = remainingLetters.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [remainingLetters[i], remainingLetters[j]] = [remainingLetters[j], remainingLetters[i]];
    }

    // Harfleri rastgele boş hücrelere yerleştirme
    remainingLetters.forEach(letter => {
        let placed = false;
        let attempts = 0;
        while (!placed && attempts < 100) {
            const x = Math.floor(Math.random() * cols);
            const y = Math.floor(Math.random() * rows);
            if (level[y][x] === null) {
                level[y][x] = { value: letter, uuid: generateUUID() };
                placed = true;
            }
            attempts++;
        }
        if (!placed) {
            console.warn(`rearrangeGrid: "${letter}" harfi gridde yerleştirilemedi.`);
        }
    });

    // 7. Kalan boş hücreleri rastgele harflerle doldur
    const englishAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
            if (level[y][x] === null) {
                // Rastgele bir harf seç
                const randomLetter = englishAlphabet[Math.floor(Math.random() * englishAlphabet.length)];
                // Boş hücreye yerleştir
                level[y][x] = { value: randomLetter, uuid: generateUUID() };
            }
        }
    }

    console.log("rearrangeGrid: Grid yeniden düzenlendi.");
}
function afterWordRemoved(level) {
    let maxAttempts = 100;
    let attempts = 0;

    while (!anyPlayableWords(level) && attempts < maxAttempts) {
        const allFound = selectedWords.every(wObj => wObj.found);
        if (allFound) {
            if (runtime) {
                // Level tamamlandığında animasyonlu geçiş ekle
                animateGridDestroy(() => {
                    runtime.callFunction("levelcompleted");
                    next_level();
                });
            }

            return false;
        } else {
            rearrangeGrid(level);
            applyGravity(level);

            if (isGridEmpty(level)) {
                if (runtime) {
                    // Level tamamlandığında animasyonlu geçiş ekle
                    animateGridDestroy(() => {
                        runtime.callFunction("levelcompleted");
                        next_level();
                    });
                }

                return false;
            }

            clearLetters(); 
            renderGrid(level, level[0].length, level.length);
        }
        attempts++;
    }

    if (anyPlayableWords(level)) {
        return true;
    } else {
        if (runtime) {
            // Level tamamlandığında animasyonlu geçiş ekle
            animateGridDestroy(() => {
                runtime.callFunction("levelcompleted");
                next_level();
            });
        }

        return false;
    }
}

// Grid sprite'larını animasyonla yok etme fonksiyonu
function animateGridDestroy(callback) {
    console.log("Grid sprite'ları animasyonla yok ediliyor...");
    
    // Level katmanındaki tüm Letter sprite'larını al
    const allLetters = runtime.objects.Letters.getAllInstances()
        .filter(spr => spr.layer.name === "Level" && !spr.instVars.hiddenWord);
    
    if (allLetters.length === 0) {
        console.log("Animasyon yapılacak sprite bulunamadı.");
        // Hiç sprite yoksa direkt callback'i çağır
        if (typeof callback === "function") callback();
        return;
    }
    
    console.log(`Toplam ${allLetters.length} harf sprite'ı animasyonla yok edilecek`);
    
    // Her sprite için başlangıç gecikmesi
    let maxDelay = 0;
    const animationDuration = 0.3; // saniye
    
    // Satır ve sütun bazında gecikme oluştur (ortadan dışa doğru)
    const gridPositions = {};
    
    // Önce sprite'ların grid pozisyonlarını hesapla
    allLetters.forEach(spr => {
        // Sprite'ın grid koordinatlarını yaklaşık olarak hesapla
        const LETTER_WIDTH = 100;
        const VERTICAL_SPACING = 85;
        const SHIFT_X = 50;
        
        const screenWidth = runtime.layout.width;
        const screenHeight = runtime.layout.height;
        
        const cols = 9;
        const rows = 10;
        
        const totalWidth = cols * LETTER_WIDTH;
        const totalHeight = rows * VERTICAL_SPACING;
        
        const startX = (screenWidth - totalWidth) / 2 + SHIFT_X;
        const startY = (screenHeight - totalHeight) / 2 + 250;
        
        // Yaklaşık grid pozisyonunu hesapla
        const col = Math.round((spr.x - startX) / LETTER_WIDTH);
        const row = Math.round((spr.y - startY) / VERTICAL_SPACING);
        
        // Grid pozisyonunu kaydet
        gridPositions[spr.uid] = { row, col };
    });
    
    // Grid merkezi
    const centerRow = 5;  // 10 satırın yarısı
    const centerCol = 4;  // 9 sütunun yarısı
    
    // Her sprite için animasyon başlat
    allLetters.forEach(spr => {
        // Sprite'ın grid pozisyonu
        const pos = gridPositions[spr.uid] || { row: 0, col: 0 };
        
        // Merkezden uzaklık hesapla (Manhattan mesafesi)
        const distance = Math.abs(pos.row - centerRow) + Math.abs(pos.col - centerCol);
        
        // Merkezden dışa doğru gecikme (merkezdekiler önce, dıştakiler sonra)
        const delay = distance * 0.05; // Her birim mesafe için 50ms gecikme
        
        if (delay > maxDelay) maxDelay = delay;
        
        // Sprite'ı küçült
        setTimeout(() => {
            // Width ve height için tween başlat
            spr.behaviors.Tween.startTween("width", 0, animationDuration, "linear");
            spr.behaviors.Tween.startTween("height", 0, animationDuration, "linear");
            
            // Animasyon bitince sprite'ı yok et
            setTimeout(() => {
                spr.destroy();
            }, animationDuration * 1000);
            
        }, delay * 1000);
    });
    
    // Tüm animasyonlar bittikten sonra callback'i çağır
    const totalAnimationTime = maxDelay + animationDuration + 0.1; // Ufak bir ek süre
    setTimeout(() => {
        console.log("Grid sprite'larının animasyonlu yok edilmesi tamamlandı.");
        if (typeof callback === "function") callback();
    }, totalAnimationTime * 1000);
}
function checkWordInGrid(word) {
    if (!globalLevel || !Array.isArray(globalLevel) || globalLevel.length === 0) {
        console.error("Grid henüz hazır değil veya geçerli değil.");
        return;
    }

    const W = word.toUpperCase();
    console.log(`checkWordInGrid: Checking word "${W}" in the grid`);

    // First check if the word is in our selected words list
    const wordObj = selectedWords.find(wObj => wObj.word.toUpperCase() === W);
    if (!wordObj) {
        console.log(`checkWordInGrid: "${W}" is not in selectedWords list`);
        if (runtime) {
            runtime.callFunction("noword");
        }
        GUESS = [];
        GUESS_DIRECTION = null;
        return;
    }

    if (wordObj.found) {
        console.log(`checkWordInGrid: "${W}" has already been found`);
        return;
    }

    const level = globalLevel;
    const rows = level.length;
    const cols = level[0].length;

    const directions = [
        { name: "horizontal", dx: 1, dy: 0 },
        { name: "vertical", dx: 0, dy: 1 },
        { name: "reverse-horizontal", dx: -1, dy: 0 },
        { name: "reverse-vertical", dx: 0, dy: -1 }
    ];

    // First verify the word is actually in the grid using isWordInGrid
    const wordLocation = isWordInGrid(level, W);
    if (!wordLocation) {
        console.log(`checkWordInGrid: "${W}" exists in selectedWords but NOT FOUND in grid`);
        if (runtime) {
            runtime.callFunction("noword");
        }
        GUESS = [];
        GUESS_DIRECTION = null;
        return;
    }
    
    console.log(`checkWordInGrid: "${W}" CONFIRMED in grid at (${wordLocation.startRow}, ${wordLocation.startCol}) in ${wordLocation.direction}`);

    function buildUniqueIdMap(grid) {
        const map = {};
        grid.forEach((row, y) => {
            row.forEach((cell, x) => {
                if (cell !== null && cell.uuid) {
                    map[cell.uuid] = { x, y };
                }
            });
        });
        return map;
    }

    const previousGrid = JSON.parse(JSON.stringify(level));
    const previousMap = buildUniqueIdMap(previousGrid);

    function checkDirectionAndRemove(startX, startY, dx, dy) {
        for (let i = 0; i < W.length; i++) {
            const x = startX + i * dx;
            const y = startY + i * dy;
            if (x < 0 || x >= cols || y < 0 || y >= rows) return false;
            if (!level[y][x] || level[y][x].value !== W[i]) return false;
        }
        return true;
    }

    function removeWord(startX, startY, dx, dy) {
        const uuids = [];
        for (let i = 0; i < W.length; i++) {
            const x = startX + i * dx;
            const y = startY + i * dy;
            if (level[y][x] && level[y][x].uuid) {
                uuids.push(level[y][x].uuid);
            }
            level[y][x] = null;
        }
        return uuids;
    }

    let pendingLogs = [];

    // Use the wordLocation to remove the word directly
    const startX = wordLocation.startCol;
    const startY = wordLocation.startRow;
    const dirObj = directions.find(d => {
        if (wordLocation.direction === "yatay-sağ") return d.name === "horizontal";
        if (wordLocation.direction === "yatay-sol") return d.name === "reverse-horizontal";
        if (wordLocation.direction === "dikey-aşağı") return d.name === "vertical";
        if (wordLocation.direction === "dikey-yukarı") return d.name === "reverse-vertical";
        return false;
    });
    
    if (!dirObj) {
        console.error(`checkWordInGrid: Could not map direction ${wordLocation.direction} to a valid direction object`);
        // Fall back to the original search method
        for (let y = 0; y < rows; y++) {
            for (let x = 0; x < cols; x++) {
                if (level[y][x] && level[y][x].value === W[0]) {
                    for (const dir of directions) {
                        if (checkDirectionAndRemove(x, y, dir.dx, dir.dy)) {
                            pendingLogs.push(`"${word}" kelimesi gridde bulundu. OYNANABİLİR.`);

                            const removedUUIDs = removeWord(x, y, dir.dx, dir.dy);
                            applyGravity(level);

                            for (const logLine of pendingLogs) {
                                console.log(logLine);
                            }
                            console.log(`"${word}" kelimesi gridde çıkarıldı. UUID'ler:`, removedUUIDs);

                            wordObj.found = true;
                            openHiddenWordSprites(word);

                            removedUUIDs.forEach((uuid, index) => {
                                setTimeout(() => {
                                    runtime.callFunction("removeletters", uuid);
                                }, index * 100);
                            });

                            const currentMap = buildUniqueIdMap(level);
                            const movedLetters = [];

                            for (const uuid in currentMap) {
                                if (previousMap[uuid]) {
                                    const prevPos = previousMap[uuid];
                                    const currPos = currentMap[uuid];
                                    if (prevPos.x !== currPos.x || prevPos.y !== currPos.y) {
                                        const xPixel = currPos.x * LETTER_SIZE + (runtime.layout.width - (cols * LETTER_SIZE)) / 2 + 50;
                                        const yPixel = currPos.y * VERTICAL_SPACING + (runtime.layout.height - (rows * VERTICAL_SPACING)) / 2 + 250;
                                        movedLetters.push({ uniqueId: uuid, x: xPixel, y: yPixel });
                                    }
                                }
                            }

                            const totalLettersRemoved = removedUUIDs.length;
                            const totalDelay = totalLettersRemoved * 100;

                            setTimeout(() => {
                                movedLetters.forEach(letter => {
                                    runtime.callFunction("dropletters", letter.uniqueId, letter.x, letter.y);
                                });

                                const gameStatus = afterWordRemoved(level);
                                if (!gameStatus) {
                                    console.log("OYUN BİTTİ KAZANDIN");
                                } else {
                                    console.log("Oyun devam ediyor.");
                                }
                            }, totalDelay);

                        if (currentTask && word.toUpperCase().includes(currentTask.letter)) {
                            addTask();
                            runtime.callFunction("taskfound");
                            }

                            return;
                        }
                    }
                }
            }
        }
    } else {
        // Use the exact found location and direction
        pendingLogs.push(`"${word}" kelimesi gridde bulundu at (${startY}, ${startX}) OYNANABİLİR.`);
        
        const removedUUIDs = removeWord(startX, startY, dirObj.dx, dirObj.dy);
        applyGravity(level);

        for (const logLine of pendingLogs) {
            console.log(logLine);
        }
        console.log(`"${word}" kelimesi gridde çıkarıldı. UUID'ler:`, removedUUIDs);

        wordObj.found = true;
        openHiddenWordSprites(word);

        removedUUIDs.forEach((uuid, index) => {
            setTimeout(() => {
                runtime.callFunction("removeletters", uuid);
            }, index * 100);
        });

        const currentMap = buildUniqueIdMap(level);
        const movedLetters = [];

        for (const uuid in currentMap) {
            if (previousMap[uuid]) {
                const prevPos = previousMap[uuid];
                const currPos = currentMap[uuid];
                if (prevPos.x !== currPos.x || prevPos.y !== currPos.y) {
                    const xPixel = currPos.x * LETTER_SIZE + (runtime.layout.width - (cols * LETTER_SIZE)) / 2 + 50;
                    const yPixel = currPos.y * VERTICAL_SPACING + (runtime.layout.height - (rows * VERTICAL_SPACING)) / 2 + 250;
                    movedLetters.push({ uniqueId: uuid, x: xPixel, y: yPixel });
                }
            }
        }

        const totalLettersRemoved = removedUUIDs.length;
        const totalDelay = totalLettersRemoved * 100;

        setTimeout(() => {
            movedLetters.forEach(letter => {
                runtime.callFunction("dropletters", letter.uniqueId, letter.x, letter.y);
            });

            const gameStatus = afterWordRemoved(level);
            if (!gameStatus) {
                console.log("OYUN BİTTİ KAZANDIN");
            } else {
                console.log("Oyun devam ediyor.");
            }
        }, totalDelay);

        if (currentTask && word.toUpperCase().includes(currentTask.letter)) {
            addTask();
            runtime.callFunction("taskfound");
        }

        return;
    }

    console.log(`checkWordInGrid: Word "${W}" was not found in the grid in any direction`);
    if (runtime) {
        runtime.callFunction("noword");
    }
    GUESS = [];
    GUESS_DIRECTION = null;
}
function isGridValid(level) {
    // 9x10 grid için hiçbir sütunda 10'dan fazla harf olmamalı
    const rows = level.length;
    const cols = level[0].length;
    
    for (let x = 0; x < cols; x++) {
        const count = countLettersColumn(level, x);
        if (count > rows) {
            return false;
        }
    }

    return true;
}
function countLettersColumn(level, col) {
    let c = 0;
    for (let y = 0; y < level.length; y++) {
        if (level[y][col] !== null) c++;
    }
    return c;
}
function canPlaceWord(level, rows, cols, word, direction, startX, startY) {
    const W = word;
    if (direction === "horizontal") {
        if (startX + W.length > cols) return false;
        for (let i = 0; i < W.length; i++) {
            if (level[startY][startX + i] !== null) return false;
        }
        return true;
    } else if (direction === "vertical") {
        if (startY + W.length > rows) return false;
        for (let i = 0; i < W.length; i++) {
            if (level[startY + i][startX] !== null) return false;
        }
        return true;
    } else if (direction === "reverse-horizontal") {
        if (startX - (W.length - 1) < 0) return false;
        for (let i = 0; i < W.length; i++) {
            if (level[startY][startX - i] !== null) return false;
        }
        return true;
    } else if (direction === "reverse-vertical") {
        if (startY - (W.length - 1) < 0) return false;
        for (let i = 0; i < W.length; i++) {
            if (level[startY - i][startX] !== null) return false;
        }
        return true;
    }
    return false;
}
function placeWord(level, word, direction, startX, startY) {
    const W = word;
    if (direction === "horizontal") {
        for (let i = 0; i < W.length; i++) {
            level[startY][startX + i] = { value: W[i], uuid: generateUUID() };
        }
    } else if (direction === "vertical") {
        for (let i = 0; i < W.length; i++) {
            level[startY + i][startX] = { value: W[i], uuid: generateUUID() };
        }
    } else if (direction === "reverse-horizontal") {
        for (let i = 0; i < W.length; i++) {
            level[startY][startX - i] = { value: W[i], uuid: generateUUID() };
        }
    } else if (direction === "reverse-vertical") {
        for (let i = 0; i < W.length; i++) {
            level[startY - i][startX] = { value: W[i], uuid: generateUUID() };
        }
    }
}
function verifyPlacedWord(level, word, direction, startX, startY) {
    const W = word;
    let letters = [];
    if (direction === "horizontal") {
        for (let i = 0; i < W.length; i++) {
            letters.push(level[startY][startX + i].value);
        }
    } else if (direction === "vertical") {
        for (let i = 0; i < W.length; i++) {
            letters.push(level[startY + i][startX].value);
        }
    } else if (direction === "reverse-horizontal") {
        for (let i = 0; i < W.length; i++) {
            letters.push(level[startY][startX - i].value);
        }
    } else if (direction === "reverse-vertical") {
        for (let i = 0; i < W.length; i++) {
            letters.push(level[startY - i][startX].value);
        }
    }

    const placedWord = letters.join("");
    return placedWord === W;
}
function undoPlaceWord(level, word, direction, startX, startY) {
    const W = word;
    if (direction === "horizontal") {
        for (let i = 0; i < W.length; i++) {
            level[startY][startX + i] = null;
        }
    } else if (direction === "vertical") {
        for (let i = 0; i < W.length; i++) {
            level[startY + i][startX] = null;
        }
    } else if (direction === "reverse-horizontal") {
        for (let i = 0; i < W.length; i++) {
            level[startY][startX - i] = null;
        }
    } else if (direction === "reverse-vertical") {
        for (let i = 0; i < W.length; i++) {
            level[startY - i][startX] = null;
        }
    }
}
function clearLetters() {
    // Iterate through all Letters instances
    runtime.objects.Letters.getAllInstances().forEach(instance => {
        // Check if hiddenWord is empty or undefined
        if (!instance.instVars.hiddenWord) {
            instance.destroy();
        }
    });
}
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
let currentCategory = "animals";
let currentDifficulty = "veryeasy";
async function createLevelWords(category = currentCategory) {
    if (!runtime || !runtime.assets) {
        console.error("Runtime veya assets tanımlı değil.");
        return { wordsForGrid: [], remainingLetters: [] };
    }

    try {
        // levels.json dosyasını yükle
        const levelsData = await runtime.assets.fetchJson("levels.json");
        console.log("levels.json başarıyla yüklendi.");

        // Mevcut seviye verisini al
        const levelData = levelsData.find(level => level.level === currentLevel);
        if (!levelData) {
            console.error(`Level ${currentLevel} levels.json içinde bulunamadı.`);
            return { wordsForGrid: [], remainingLetters: [] };
        }

        console.log(`Level ${currentLevel} verisi bulundu:`, levelData);

        // Kategoriyi kontrol edin (isteğe bağlı)
        if (levelData.category !== category) {
            console.warn(`Seçilen kategori "${category}", level ${currentLevel} için "${levelData.category}" olarak ayarlandı.`);
            category = levelData.category; // Kategoriyi level verisine göre güncelle
        }

        // Direkt İngilizce kelime listesini kullan
        const wordsKey = "words_en"; // Sabit olarak İngilizce kelime listesi
        if (!Array.isArray(levelData[wordsKey]) || levelData[wordsKey].length === 0) {
            console.error(`Level ${currentLevel} için ${wordsKey} alanı boş veya geçersiz.`);
            return { wordsForGrid: [], remainingLetters: [] };
        }

        console.log(`Level ${currentLevel} için kelimeler (İngilizce):`, levelData[wordsKey]);

        // Her kelime için { word: "KELIME", found: false } nesnesi oluştur
        const wordsForGrid = levelData[wordsKey].map(word => ({ word: word.toUpperCase(), found: false }));

        // Level 0 için özel düzenleme - BIRD kelimesini ekle
        if (currentLevel === 0) {
            // BIRD kelimesinin listede olup olmadığını kontrol et
            const hasBird = wordsForGrid.some(w => w.word.toUpperCase() === "BIRD");
            
            if (!hasBird) {
                console.log("Level 0 için BIRD kelimesi ekleniyor...");
                wordsForGrid.push({ word: "BIRD", found: false });
            } else {
                console.log("Level 0 için BIRD kelimesi zaten listede mevcut.");
            }
        }

        // IMPORTANT: selectedWords dizisini güncelle
        selectedWords = wordsForGrid;

        console.log(`wordsForGrid oluşturuldu:`, wordsForGrid);

        // Toplam harf sayısını hesapla
        totalLetters = wordsForGrid.reduce((acc, wordObj) => acc + wordObj.word.length, 0);

        // Global kategori güncellemesi
        currentCategory = category;

        // Dönüş değeri
        return { wordsForGrid, remainingLetters: [] };
    } catch (error) {
        console.error("levels.json yüklenirken bir hata oluştu:", error);
        return { wordsForGrid: [], remainingLetters: [] };
    }
}
function clearGridAndLetters() {
    // 1. Tüm Letters nesnelerini temizle
    const allLetters = runtime.objects.Letters.getAllInstances();
    allLetters.forEach(letter => {
        letter.destroy(); // Harfleri sahneden kaldır
    });
   

    // 2. Global grid verisini sıfırla
    if (globalLevel && Array.isArray(globalLevel)) {
        globalLevel.forEach(row => {
            row.fill(null); // Her satırı tamamen null yap
        });
      
    } else {
        
    }

    // 3. Seçilen kelimeleri sıfırla
    selectedWords = [];
    

    // 4. Render edilmiş harf sprite'larını sıfırla
    clearLetters();

    // 5. Harflerin toplam sayısını sıfırla
    totalLetters = 0;
   

    // --- EKLENDİ ---
    // isFirstRender bayrağını sıfırla
    isFirstRender = true;
   

   
}
let isFirstRender = true; // Global değişken
// B harfinin y konumunu tutacak global değişken
let birdBLetterY = 0;

function renderGrid(level, cols, rows) {
    // LETTER SIZE AND VERTICAL SPACING
    const LETTER_WIDTH = 100;   // Letter width
    const LETTER_HEIGHT = 100;  // Letter height
    const VERTICAL_SPACING = 85;
    const SHIFT_X = 50;

    const screenWidth = runtime.layout.width;
    const screenHeight = runtime.layout.height;

    const totalWidth = cols * LETTER_WIDTH;
    const totalHeight = rows * VERTICAL_SPACING;

    const startX = (screenWidth - totalWidth) / 2 + SHIFT_X;
    // Y pozisyonunu ayarla - ekranın ortasından biraz daha aşağıda olsun
    const startY = (screenHeight - totalHeight) / 2 + 250; // 150 piksel daha aşağıya kaydır

    // Level 0 için griddeki B harfinin y pozisyonunu kaydet
    const currentLevelValue = parseInt(localStorage.getItem(`${gamePrefix}level`), 10) || 0;
    if (currentLevelValue === 0) {
        // B harfinin grid koordinatları (biliyoruz ki BIRD ortada)
        const centerRow = Math.floor(rows / 2);
        const centerCol = Math.floor(cols / 2) - 2; // BIRD kelimesi için orta noktadan 2 birim sol
        // B harfinin y pozisyonunu hesapla
        birdBLetterY = startY + (centerRow * VERTICAL_SPACING);
        console.log(`Level 0: B harfinin y pozisyonu: ${birdBLetterY}`);
    }

    for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
            const cell = level[row][col];
            if (!cell) continue;

            const { value: letter, uuid: uniqueId } = cell;

            const x = startX + (col * LETTER_WIDTH);
            const y = startY + (row * VERTICAL_SPACING);

            const letterSprite = runtime.objects.Letters.createInstance("Level", x, y);
            letterSprite.width = LETTER_WIDTH;    // Updated width
            letterSprite.height = LETTER_HEIGHT;  // Updated height
            letterSprite.setAnimation(letter);

            letterSprite.instVars.uuid = uniqueId;
        }
    }

    // Update the category in the "areatext3" object dynamically
    const areatext3 = runtime.objects.areatext3.getFirstInstance();
    if (areatext3) {
        if (typeof currentCategory === "string" && currentCategory.trim().length > 0) {
            areatext3.text = currentCategory; // Write the dynamic category
            console.log(`areatext3 text updated to: ${currentCategory}`);
        } else {
            console.warn("currentCategory is not a valid string:", currentCategory);
        }
    } else {
        console.warn("areatext3 object instance not found.");
    }

    // Call showHiddenWordsForSelectedWords only on the first render
    if (isFirstRender) {
        showHiddenWordsForSelectedWords();
        isFirstRender = false; // Set the flag to false after the first render
    }
}
// B harfinin UUID değerini tutacak global değişken
let birdBLetterUUID = '';

async function initializeGridWithSelectedWords(cols, rows, wordsForGrid, remainingLetters) {
    // Sabit grid boyutu için
    cols = 9;  // Her zaman 9 sütun
    rows = 10; // Her zaman 10 satır

    const directions = [
        "horizontal",
        "vertical",
        "reverse-horizontal",
        "reverse-vertical"
    ];

    let attemptsOverall = 0;
    const difficultWordsCount = 3;
    let difficultWordsPlaced = 0;
    let difficultWords = [];

    while (true) {
        const level = Array.from({ length: rows }, () => Array(cols).fill(null));
        
        // Level 0 için özel düzenleme - BIRD kelimesini grid ortasına yerleştir
        const currentLevelValue = parseInt(localStorage.getItem(`${gamePrefix}level`), 10) || 0;
        if (currentLevelValue === 0) {
            // BIRD kelimesini grid'in ortasına yatay olarak yerleştir
            const birdWord = "BIRD";
            const centerRow = Math.floor(rows / 2); // Merkez satır: 5 (10 satırın yarısı)
            const centerCol = Math.floor(cols / 2) - Math.floor(birdWord.length / 2); // Merkez sütun: 3.5 - 2 = 1.5 -> 1
            
            // Özel bir UUID oluştur ve kaydet
            birdBLetterUUID = generateUUID();
            console.log(`Level 0: B harfinin UUID'si: ${birdBLetterUUID}`);
            
            // BIRD kelimesini yatay (horizontal) olarak yerleştir
            for (let i = 0; i < birdWord.length; i++) {
                // B harfi için özel UUID kullan, diğerleri için yeni UUID oluştur
                const uuid = (i === 0) ? birdBLetterUUID : generateUUID();
                level[centerRow][centerCol + i] = { value: birdWord[i], uuid: uuid };
            }
            
            console.log(`Level 0 için BIRD kelimesi grid ortasına yerleştirildi. Konum: Satır ${centerRow}, Sütun ${centerCol}`);
            
            // BIRD kelimesini wordsForGrid listesinde bul ve found = false olarak ayarla
            const birdWordObj = wordsForGrid.find(wObj => wObj.word.toUpperCase() === "BIRD");
            if (birdWordObj) {
                birdWordObj.found = false;
                console.log("BIRD kelimesi wordsForGrid içinde bulundu ve found = false olarak ayarlandı.");
            } else {
                console.warn("BIRD kelimesi wordsForGrid içinde bulunamadı!");
            }
        }

        let allPlaced = true;
        const failedWords = []; // Yerleştirilemeyen kelimeleri tutmak için

        for (const wordObj of wordsForGrid) {
            if (!wordObj.found) {
                const W = wordObj.word.toUpperCase();
                
                // Level 0'da ve kelime BIRD ise, zaten yerleştirildi kabul et
                if (currentLevelValue === 0 && W === "BIRD") {
                    console.log("BIRD kelimesi zaten yerleştirildi, atlıyorum.");
                    continue;
                }
                
                let placed = false;
                let attempts = 0;
                const isDifficult = difficultWordsPlaced < difficultWordsCount;

                const failedReasons = []; // Bu kelimenin neden yerleştirilemediğini tutmak için

                while (!placed && attempts < (isDifficult ? 500 : 200)) {
                    const directionIndex = Math.floor(Math.random() * directions.length);
                    const direction = directions[directionIndex];
                    const startX = Math.floor(Math.random() * cols);
                    const startY = Math.floor(Math.random() * rows);

                    if (canPlaceWord(level, rows, cols, W, direction, startX, startY)) {
                        placeWord(level, W, direction, startX, startY);
                        if (verifyPlacedWord(level, W, direction, startX, startY)) {
                            placed = true;
                            if (isDifficult) {
                                difficultWordsPlaced++;
                                difficultWords.push(W);
                            }
                        } else {
                            undoPlaceWord(level, W, direction, startX, startY);
                            failedReasons.push(`Kelime yerleştirildikten sonra doğrulama başarısız oldu: ${direction}, (${startX}, ${startY})`);
                        }
                    } else {
                        failedReasons.push(`Kelime ${direction} yönünde (${startX}, ${startY}) başlangıç noktasıyla gridde yerleştirilemedi.`);
                    }
                    attempts++;
                }

                if (!placed) {
                    allPlaced = false;
                    failedWords.push({ word: W, reasons: failedReasons });
                }
            }
        }

        if (allPlaced) {
            // Tüm satırları doldur (artık sadece 10 satır olduğu için kısıtlama kaldırıldı)
            const englishAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            for (let y = 0; y < rows; y++) {
                for (let x = 0; x < cols; x++) {
                    if (level[y][x] === null) {
                        // Rastgele bir harf seç
                        const randomLetter = englishAlphabet[Math.floor(Math.random() * englishAlphabet.length)];
                        // Boş hücreye yerleştir
                        level[y][x] = { value: randomLetter, uuid: generateUUID() };
                    }
                }
            }
            
            applyGravity(level);
            if (isGridValid(level)) {
                const totalLettersInGrid = level.flat().filter(cell => cell !== null).length;
                const playableCount = countPlayableWords(level);
                if (playableCount > 0) { // En az bir kelime oynanabilir olmalı
                    renderGrid(level, cols, rows);
                    globalLevel = level; // Global değişkene atama
                    return level;
                } else {
                    attemptsOverall++;
                    if (attemptsOverall > 5000) {
                        console.error("Çok fazla deneme yapıldı, uygun düzen bulunamadı.");
                        return null;
                    }
                    continue; // Yeni bir grid denemesi yap
                }
            }
        }

        attemptsOverall++;
        if (attemptsOverall > 5000) {
            console.error("Çok fazla deneme yapıldı, uygun düzen bulunamadı.");
            failedWords.forEach(({ word, reasons }) => {
                console.error(`Kelime "${word}" yerleştirilemedi. Sebepler:`);
                reasons.forEach(reason => console.error(`- ${reason}`));
            });
            return null;
        }
    }
}
async function initializeGridAndLog(category = "flowers") {
    const { wordsForGrid, remainingLetters } = await createLevelWords(category);
    
    // Sabit grid boyutu: 9x10
    const cols = 9;
    const rows = 10;
    
    const newGrid = await initializeGridWithSelectedWords(
        cols, 
        rows, 
        wordsForGrid, 
        remainingLetters
    );

    if (newGrid) {
        console.log("Yeni grid oluşturuldu:");
        newGrid.forEach(row => console.log(row.map(cell => (cell ? cell.value : " ")).join(" ")));
        renderGrid(newGrid, cols, rows);
        globalLevel = newGrid;
    } else {
        console.error("Yeni grid oluşturulamadı.");
    }
}
async function initializeGameAndCreateGrid(level, difficulty) {
    // Seviye ve zorluk parametrelerini kaydetmek isterseniz:
    if (level) currentLevel = level;
    if (difficulty) currentDifficulty = difficulty;

    console.log(`Seçilen seviye: ${currentLevel}, zorluk: ${currentDifficulty}`);

    try {
        // Artık levelHard yerine, doğrudan kelimeleri çekiyoruz
        const { wordsForGrid, remainingLetters } = await createLevelWords(currentCategory);

        if (!wordsForGrid || wordsForGrid.length === 0) {
            console.error("wordsForGrid boş geldi.");
            return;
        }

        // Sabit kolon ve satır sayısı kullanıyoruz - 9x10 grid
        const cols = 9; 
        const rows = 10; 

        const newGrid = await initializeGridWithSelectedWords(
            cols, 
            rows, 
            wordsForGrid,
            remainingLetters
        );

        if (newGrid) {
            console.log("Yeni grid oluşturuldu:");
            newGrid.forEach(row => console.log(row.map(cell => (cell ? cell.value : " ")).join(" ")));
            renderGrid(newGrid, cols, rows);
            globalLevel = newGrid; // Global grid
            
            // Level 1 için tutorial parmak gösterimini çağır
            if (currentLevel === 1) {
                setTimeout(() => {
                    showTutorialFingers();
                }, 1000); // 1 saniye bekleyerek tüm sprite'ların render olmasını sağla
            }
        } else {
            console.error("Yeni grid oluşturulamadı.");
        }
    } catch (error) {
        console.error("Oyunu başlatırken veya grid oluştururken bir hata oluştu:", error);
    }
}

// Level 1 için B ve D harflerini bulup parmak gösterimi yapan fonksiyon
// Fingerr fonksiyonu yalnızca bir kez çağrılacak
let tutorialShown = false; // Fingerr fonksiyonunun bir kez çağrılmasını engelle

function showTutorialFingers() {
    console.log("showTutorialFingers fonksiyonu çağrıldı...");
    
    // Fonksiyon zaten çalıştırıldıysa tekrar çalıştırma
    if (tutorialShown) {
        console.log("Tutorial parmak gösterimi zaten yapıldı, tekrar yapılmayacak.");
        return;
    }
    
    // Level 0 kontrolü
    const currentLevelValue = parseInt(localStorage.getItem(`${gamePrefix}level`), 10) || 0;
    if (currentLevelValue !== 0) {
        console.log("Bu level 0 değil, tutorial parmak gösterimi atlanıyor.");
        return;
    }
    
    // B harfinin UUID'sini kontrol et
    console.log(`Tutorial: B harfinin UUID değeri: ${birdBLetterUUID}`);
    
    // Eğer B harfinin UUID'si varsa
    if (birdBLetterUUID) {
        // B harfinin UUID'sini kullanarak sprite'ı bul
        const allLetters = runtime.objects.Letters.getAllInstances();
        const bSprite = allLetters.find(spr => spr.instVars.uuid === birdBLetterUUID);
        
        if (bSprite) {
            // B sprite'ının konumu ve Construct 3 UID'si
            const x = bSprite.x;
            const y = bSprite.y;
            const uid = bSprite.uid; // Construct 3'ün kendi UID'si
            
            console.log(`Tutorial: B sprite'ı bulundu. Konum: (${x}, ${y}), Construct 3 UID: ${uid}`);
            
            // fingerr fonksiyonunu çağır - Construct 3 UID değerini gönder
            if (runtime) {
                console.log(`Tutorial: fingerr fonksiyonuna B harfinin C3 UID'si gönderiliyor: ${uid}`);
                runtime.callFunction("fingerr", uid);
                tutorialShown = true; // Fonksiyonun tekrar çağrılmasını engelle
            }
        } else {
            console.error("B harfinin UUID'si ile eşleşen sprite bulunamadı.");
        }
    } else {
        console.error("B harfinin UUID'si tanımlanmamış.");
    }
}
function removeletters(uuid) {
    // Construct 3'teki ilgili sprite'ı bul ve kaldır
    const sprite = runtime.objects.Letters.instances.find(s => s.instVars.uuid === uuid);
    if (sprite) {
        sprite.destroy();
        console.log(`removeletters: UUID ${uuid} olan harf kaldırıldı.`);
    } else {
        console.warn(`removeletters: UUID ${uuid} bulunamadı.`);
    }
}
function checkPlayableWordsOrRearrange() {
    // 1) Grid geçerli mi?
    if (!globalLevel || !Array.isArray(globalLevel) || globalLevel.length === 0) {
        console.error("Grid (globalLevel) geçersiz veya boş.");
        return;
    }

    // 2) Oynanabilir kelime var mı?
    const playableCount = countPlayableWords(globalLevel);
    // countPlayableWords fonksiyonunuz, gridde seçilen kelimelerin bulunabilirliğini kontrol edip
    // konsola hangi kelimenin bulunduğunu da yazıyor.

    if (playableCount > 0) {
        // Varsa
        console.log("Gridde oynanabilir en az bir kelime var => 'var'");
        // (İsterseniz ilk bulunan kelimeyi de ek bir yöntemle yakalayıp loglayabilirsiniz.)
    } else {
        // Yoksa => grid yenile
        console.log("Oynanabilir kelime yok => grid yeniden düzenleniyor...");

        rearrangeGrid(globalLevel);
        applyGravity(globalLevel);
        clearLetters();

        // En son grid'i yeniden çiziyoruz:
        renderGrid(globalLevel, globalLevel[0].length, globalLevel.length);
        console.log("Yeni grid oluşturuldu.");
    }
}
function dropletters(uniqueId, x, y) {
    // uniqueId'ye sahip sprite'ı bulun
    const sprite = runtime.objects.Letters.instances.find(s => s.instVars.uuid === uniqueId);
    if (sprite) {
        // Sprite'ın yeni konumunu güncelle
        sprite.x = x;
        sprite.y = y + 250; // Add the same offset used in renderGrid
        console.log(`dropletters: UUID ${uniqueId} için x:${x}, y:${y+250} konumu güncellendi.`);
    } else {
        console.warn(`dropletters: UUID ${uniqueId} bulunamadı.`);
    }
}
const maxLevel = 100;
async function startLevel() {
    clearGridAndLetters();
    currentLevel = parseInt(localStorage.getItem(`${gamePrefix}level`), 10) || 0;
    if (currentLevel > maxLevel) {
        console.warn(`Level ${currentLevel}, izin verilen maksimum seviyeden (${maxLevel}) büyük. Oyun sıfırlanıyor...`);
        // nolevel fonksiyonu yok, oyunu sıfırla
        resetAllGameData();
        return; // resetAllGameData içinde zaten startLevel çağrılıyor
    }

    try {
        // levels.json dosyasını yükle
        const levelsData = await runtime.assets.fetchJson("levels.json");

        // Mevcut seviye için veriyi bul
        const levelData = levelsData.find(level => level.level === currentLevel);
        if (!levelData) {
            console.error(`Level ${currentLevel} levels.json içinde bulunamadı. Oyun sıfırlanıyor...`);
            
            // Oyun verilerini sıfırla ve 0. levelden başla
            resetAllGameData();
            return; // resetAllGameData içinde zaten startLevel çağrılıyor
        }

        const { category, difficulty } = levelData;

        console.log(`Level ${currentLevel} başlatılıyor: kategori="${category}", zorluk="${difficulty}"`);

        // Oyunu başlatmak için initializeGameAndCreateGrid fonksiyonunu çağır
        await initializeGameAndCreateGrid(currentLevel, difficulty);

        // Süre sınırını kaldırdık - artık countdown yok, sınırsız süre
        console.log(`Level ${currentLevel} sınırsız süre ile başlatıldı.`);
        
        // Countdown text'i temizle veya "∞" göster
        const countdownText = runtime.objects.spriteText.getAllInstances().find(instance => instance.instVars.w === "countdown");
        if (countdownText) {
            countdownText.text = "∞"; // Sonsuzluk sembolü göster
        }
    } catch (error) {
        console.error("levels.json yüklenirken veya level başlatılırken bir hata oluştu:", error);
        
        // Herhangi bir hata durumunda da oyunu sıfırla
        console.log("Hata nedeniyle oyun sıfırlanıyor...");
        resetAllGameData();
    }
}


async function next_level() {
  updateVariable("add","level",1);
}
let GUESS = [];
let GUESS_DIRECTION = null;
function findLetterByUUID(uuid, level) {
    for (let row = 0; row < level.length; row++) {
        for (let col = 0; col < level[0].length; col++) {
            const cell = level[row][col];
            if (cell && cell.uuid === uuid) {
                // cell.value = "A" gibi
                return { x: col, y: row, letter: cell.value };
            }
        }
    }
    return null;
}
function getDirectionName(dx, dy) {
    if (dx === 1 && dy === 0)  return "right";
    if (dx === -1 && dy === 0) return "left";
    if (dx === 0 && dy === 1)  return "down";
    if (dx === 0 && dy === -1) return "up";
    return null; // Diagonal veya 2 birim fark varsa
}
function guessLetter(uuid) {
    console.log("----- guessLetter called -----");
    console.log("Param 'uuid':", uuid);

    // 1) Bu UUID'li harfi gridde bulalım
    const found = findLetterByUUID(uuid, globalLevel);
    if (!found) {
        console.log("guessLetter: Bu UUID gridde bulunamadı:", uuid);
        return;
    }
    const { x, y, letter } = found;
    console.log("Bulunan harf:", letter, "| Koordinatlar => x:", x, "y:", y);

    // 2) GUESS ve GUESS_DIRECTION'in mevcut durumunu loglayalım
    console.log("GUESS şu anda:", GUESS.map(obj => obj.letter).join(""), 
                "| Length:", GUESS.length);
    console.log("GUESS_DIRECTION:", GUESS_DIRECTION);

    // 3) Eğer GUESS boşsa (ilk harf)
    if (GUESS.length === 0) {
        GUESS.push({ x, y, letter, uuid });
        GUESS_DIRECTION = null;  // Henüz yön belli değil
        console.log("1. harf eklendi => devam");
        const lastguess = GUESS.map(obj => obj.letter).join("");
        if (runtime) {
            runtime.callFunction("wordopacity", uuid, lastguess);
        }

        console.log("GUESS so far:", GUESS.map(obj => obj.letter).join(""));
        return;
    }

    // 4) GUESS'te en az 1 harf varsa, son harf ile farkı al
    const last = GUESS[GUESS.length - 1];
    const dx = x - last.x;
    const dy = y - last.y;

    // 4a) 2. harf (GUESS.length === 1)
    if (GUESS.length === 1) {
        const dirName = getDirectionName(dx, dy);
        if (!dirName) {
            console.log("2. harfte geçersiz yön => oynanamaz");
            return;
        }
        GUESS_DIRECTION = { dx, dy, name: dirName };
        GUESS.push({ x, y, letter, uuid });
        console.log("2. harf => yön belirlendi:", dirName, "=> devam");

            const lastguess = GUESS.map(obj => obj.letter).join("");
        if (runtime) {
            runtime.callFunction("wordopacity", uuid, lastguess);
        }

        console.log("GUESS so far:", GUESS.map(obj => obj.letter).join(""));
        return;
    }

    // 4b) 3+. harf (GUESS.length >= 2)
    if (!GUESS_DIRECTION) {
        console.log("Mantık hatası: 2+ harf var ama yön yok?!");
        return;
    }

    const expectedDx = GUESS_DIRECTION.dx;
    const expectedDy = GUESS_DIRECTION.dy;

    if (dx === expectedDx && dy === expectedDy) {
        // Aynı yön => devam
        GUESS.push({ x, y, letter, uuid });
        console.log(`=> 3+. harf => yön '${GUESS_DIRECTION.name}' devam`);

             const lastguess = GUESS.map(obj => obj.letter).join("");
        if (runtime) {
            runtime.callFunction("wordopacity", uuid, lastguess);
        }

        console.log("GUESS so far:", GUESS.map(obj => obj.letter).join(""));
    } else {
        console.log("=> oynanamaz! Beklenen yön:", GUESS_DIRECTION.name, 
                    ` (dx:${expectedDx}, dy:${expectedDy}) ama gelen fark (dx:${dx}, dy:${dy})`);
        // İsterseniz GUESS = []; yapabilirsiniz
    }
}
function end() {
    const guessedWord = GUESS.map(obj => obj.letter).join("");

    checkWordInGrid(guessedWord);

    GUESS = [];

    // textholdd objesini boş bir metinle set etme
    const textHolderInstance = runtime.objects.textholdd.getFirstInstance();
    if (textHolderInstance) {
        textHolderInstance.text = ""; // Boş metin olarak ayarla
    }
}
function showHiddenWordsForSelectedWords() {
 
    const wordList = selectedWords.map(wObj => wObj.word.toUpperCase());

  
    renderHiddenWords(wordList);
}
function renderHiddenWords(wordList) {
    console.log("renderHiddenWords fonksiyonu çağrıldı.");

    const holder = runtime.objects.LetterHolder.getFirstInstance();
    if (!holder) {
        console.warn("LetterHolder object not found.");
        return;
    }
    console.log("LetterHolder bulundu:", holder);

    const LETTER_WIDTH = 50;
    const LETTER_HEIGHT = 50;
    const LETTER_SPACING = 55;  
    const ROW_SPACING = 60;
    const COLUMN_OFFSET = 230;
    const X_SHIFT = -30;

    const centerX = holder.x + X_SHIFT;
    const centerY = holder.y;

   

    // Kelime listesinin geçerli olup olmadığını kontrol et
    if (!Array.isArray(wordList) || wordList.length === 0) {
        console.error("Word list is empty or invalid:", wordList);
        return;
    }
    

    // Kelime listesini ikiye böl
    const half = Math.ceil(wordList.length / 2);
    const leftWords = wordList.slice(0, half);
    const rightWords = wordList.slice(half);

    

    // Soldaki sütun
    const leftTotalHeight = (leftWords.length - 1) * ROW_SPACING;
    const leftStartY = centerY - (leftTotalHeight / 2);
    const leftCenterX = centerX - COLUMN_OFFSET;

   

    for (let i = 0; i < leftWords.length; i++) {
        const word = leftWords[i];
        const rowY = leftStartY + i * ROW_SPACING;
        const wordLength = word.length;
        const rowWidth = (wordLength - 1) * LETTER_SPACING;
        const startX = leftCenterX - (rowWidth / 2);

       

        for (let j = 0; j < wordLength; j++) {
            const x = startX + j * LETTER_SPACING;
            const y = rowY;

         
            const letterSprite = runtime.objects.Letters.createInstance("Level", x, y);
            if (!letterSprite) {
                console.error(`Letter sprite oluşturulamadı: (${x}, ${y})`);
                continue;
            }

            letterSprite.width = LETTER_WIDTH;
            letterSprite.height = LETTER_HEIGHT;
            letterSprite.setAnimation("back");

            // --- EKLENDİ ---
            letterSprite.instVars.hiddenWord = word;        // Bu harf hangi kelimeye ait?
            letterSprite.instVars.hiddenLetter = word[j];   // Bu harfin kendisi
        }
    }

    // Sağdaki sütun
    const rightTotalHeight = (rightWords.length - 1) * ROW_SPACING;
    const rightStartY = centerY - (rightTotalHeight / 2);
    const rightCenterX = centerX + COLUMN_OFFSET;

  

    for (let i = 0; i < rightWords.length; i++) {
        const word = rightWords[i];
        const rowY = rightStartY + i * ROW_SPACING;
        const wordLength = word.length;
        const rowWidth = (wordLength - 1) * LETTER_SPACING;
        const startX = rightCenterX - (rowWidth / 2);

      

        for (let j = 0; j < wordLength; j++) {
            const x = startX + j * LETTER_SPACING;
            const y = rowY;

          

            const letterSprite = runtime.objects.Letters.createInstance("Level", x, y);
            if (!letterSprite) {
                console.error(`Letter sprite oluşturulamadı: (${x}, ${y})`);
                continue;
            }

            letterSprite.width = LETTER_WIDTH;
            letterSprite.height = LETTER_HEIGHT;
            letterSprite.setAnimation("back");

            // --- EKLENDİ ---
            letterSprite.instVars.hiddenWord = word;       
            letterSprite.instVars.hiddenLetter = word[j];  
        }
    }

    console.log("renderHiddenWords tamamlandı.");
}
function openHiddenWordSprites(foundWord) {
    // Get all Letters sprites
    const allLetters = runtime.objects.Letters.getAllInstances();
    foundWord = foundWord.toUpperCase();

    const matchingSprites = [];

    for (const spr of allLetters) {
        // Check if this sprite is part of the "hidden words" screen
        if (spr.instVars.hiddenWord) {
            // Check if it matches the found word
            if (spr.instVars.hiddenWord.toUpperCase() === foundWord) {
                matchingSprites.push(spr);

                // Set the opened variable to 1
                spr.instVars.opened = 1;

                // Animate the sprite
                setTimeout(() => {
                    const originalWidth = spr.width;
                    const originalHeight = spr.height;

                    // Shrink the sprite
                    const shrinkWidth = spr.behaviors.Tween.startTween("width", 0, 0.3, "out-cubic");
                    const shrinkHeight = spr.behaviors.Tween.startTween("height", 0, 0.3, "out-cubic");

                    // Wait for the shrink animation to complete
                    Promise.all([shrinkWidth.finished, shrinkHeight.finished]).then(() => {
                        // Set the new animation
                        spr.setAnimation(spr.instVars.hiddenLetter);

                        // Restore the sprite to its original size
                        spr.behaviors.Tween.startTween("width", originalWidth, 0.3, "out-cubic");
                        spr.behaviors.Tween.startTween("height", originalHeight, 0.3, "out-cubic");
                    });
                }, 1000);
            }
        }
    }

    // Find the middle sprite for staar and particlestar effects
    if (matchingSprites.length > 0) {
        const middleIndex = Math.floor(matchingSprites.length / 2);
        const middleSprite = matchingSprites[middleIndex];

        // Middle sprite's coordinates
        const x2 = middleSprite.x;
        const y2 = middleSprite.y;

        if (runtime) {
            // Call staar function
            runtime.callFunction("staar", 0, 0, x2, y2);

            // Call particlestar after 0.5 seconds
            setTimeout(() => {
                const height = middleSprite.height * 2; // Double the height
                const width = 300;

                runtime.callFunction("particlestar", x2, y2, height, width, "Level");
            }, 500); // 0.5-second delay
        }
    }
}
function updateText(key) {
    // Fetch the current value of the key from localStorage
    const currentValue = localStorage.getItem(`${gamePrefix}${key}`) || 0;

    // Iterate through all "spriteText" objects
    const allSpriteTexts = runtime.objects.spriteText.getAllInstances();
    allSpriteTexts.forEach(spriteText => {
        // Check if the "w" instance variable matches the key
        if (spriteText.instVars.w === key) {
            // Update the text property of the spriteText object to display the current value
            spriteText.text = currentValue; // Metnin başına bir boşluk ekleyerek güncelle
        }
    });
}
function openAndRevertHiddenWordSprites() {
    // Check for 500 gold
    const currentGold = parseInt(localStorage.getItem(`${gamePrefix}gold`), 10) || 0;

    if (currentGold < 500) {
        console.log("Yetersiz altın! En az 500 altın gerekiyor.");
        return;
    }

    // Subtract 500 gold and update the UI
    updateVariable("sub", "gold", 500);
    console.log("500 altın düşüldü.");

    // Get all Letters sprites
    const allLetters = runtime.objects.Letters.getAllInstances();

    if (allLetters.length === 0) {
        console.warn("No Letters objects found.");
        return;
    }

    // Get LetterHolder object for width and height
    const letterHolder = runtime.objects.LetterHolder.getFirstInstance();
    if (!letterHolder) {
        console.warn("LetterHolder object not found.");
        return;
    }

    const holderWidth = letterHolder.width;
    const holderHeight = letterHolder.height;
    const holderX = letterHolder.x;
    const holderY = letterHolder.y;

    // Animate only letters with opened === 0
    const lettersToAnimate = allLetters.filter(spr => spr.instVars.opened === 0);

    lettersToAnimate.forEach(spr => {
        if (spr.instVars.hiddenWord) {
            setTimeout(() => {
                const originalWidth = spr.width;
                const originalHeight = spr.height;

                // Shrink the sprite
                const shrinkWidth = spr.behaviors.Tween.startTween("width", 0, 0.3, "linear");
                const shrinkHeight = spr.behaviors.Tween.startTween("height", 0, 0.3, "linear");

                // Wait for the shrink animation to complete
                Promise.all([shrinkWidth.finished, shrinkHeight.finished]).then(() => {
                    // Set the new animation (hiddenLetter)
                    spr.setAnimation(spr.instVars.hiddenLetter);

                    // Restore the sprite to its original size
                    spr.behaviors.Tween.startTween("width", originalWidth, 0.3, "linear");
                    spr.behaviors.Tween.startTween("height", originalHeight, 0.3, "linear");

                });
            }, 100); // Small delay for each sprite to animate sequentially
        }
    });

    // Call particlestar once after all animations start
    setTimeout(() => {
        runtime.callFunction("particlestar", holderX, holderY, holderHeight, holderWidth, "Level");
        console.log(`particlestar called once for LetterHolder: x=${holderX}, y=${holderY}, height=${holderHeight}, width=${holderWidth}`);
    }, 500); // Call particlestar after the initial animation starts

    // After 1.7 seconds, revert all letters back to "back" animation
    setTimeout(() => {
        lettersToAnimate.forEach(spr => {
            if (spr.instVars.hiddenWord) {
                const originalWidth = spr.width;
                const originalHeight = spr.height;

                // Shrink the sprite again
                const shrinkWidth = spr.behaviors.Tween.startTween("width", 0, 0.3, "linear");
                const shrinkHeight = spr.behaviors.Tween.startTween("height", 0, 0.3, "linear");

                // Wait for the shrink animation to complete
                Promise.all([shrinkWidth.finished, shrinkHeight.finished]).then(() => {
                    // Set the animation back to "back"
                    spr.setAnimation("back");

                    // Restore the sprite to its original size
                    spr.behaviors.Tween.startTween("width", originalWidth, 0.3, "linear");
                    spr.behaviors.Tween.startTween("height", originalHeight, 0.3, "linear");

                    console.log(`Sprite animation reverted to "back".`);
                });
            }
        });
    }, 2700); // Wait for 1.7 seconds before reverting
}
function openSingleLetter() {
    // Check if the player has at least 50 gold
    const currentGold = parseInt(localStorage.getItem(`${gamePrefix}gold`), 10) || 0;
    if (currentGold < 50) {
        return; // Exit if not enough gold
    }

    // Deduct 50 gold
    updateVariable("sub", "gold", 50);

    // Get all Letters instances
    const allLetters = runtime.objects.Letters.getAllInstances();

    // Filter to find Letters with opened === 0 and hiddenWord is not empty
    const lettersToAnimate = allLetters.filter(
        spr => spr.instVars.opened === 0 && spr.instVars.hiddenWord
    );

    if (lettersToAnimate.length === 0) return;

    // Randomly select one letter from the filtered list
    const letterToOpen = lettersToAnimate[Math.floor(Math.random() * lettersToAnimate.length)];

    // Set its opened variable to 1
    letterToOpen.instVars.opened = 1;

    // Animate the letter to open it
    const originalWidth = letterToOpen.width;
    const originalHeight = letterToOpen.height;

    // Shrink the sprite
    const shrinkWidth = letterToOpen.behaviors.Tween.startTween("width", 0, 0.3, "linear");
    const shrinkHeight = letterToOpen.behaviors.Tween.startTween("height", 0, 0.3, "linear");

    // Wait for the shrink animation to complete
    Promise.all([shrinkWidth.finished, shrinkHeight.finished]).then(() => {
        // Set the new animation (hiddenLetter)
        letterToOpen.setAnimation(letterToOpen.instVars.hiddenLetter);

        // Restore the sprite to its original size
        letterToOpen.behaviors.Tween.startTween("width", originalWidth, 0.3, "linear");
        letterToOpen.behaviors.Tween.startTween("height", originalHeight, 0.3, "linear");

        // Send particlestar with Letter's coordinates and size
        runtime.callFunction("particlestar", letterToOpen.x, letterToOpen.y, originalWidth, originalHeight, "Level");
    });
}
let countdownTimer = null;
let countdownInterval;
function startCountdown(duration, onFinish) {
    let remainingTime = duration;

    // Eğer zaten bir geri sayım çalışıyorsa durdur
    if (countdownInterval) {
        clearInterval(countdownInterval);
    }

    countdownInterval = setInterval(() => {
        // Level layer görünürlüğünü kontrol et
        const levelLayer = runtime.layout.getLayer("Level");
        if (!levelLayer || !levelLayer.isVisible) {
            // Eğer Layer görünür değilse, geri sayımı durdurmadan bekle
            return;
        }

        remainingTime--;

        const minutes = Math.floor(remainingTime / 60);
        const seconds = remainingTime % 60;
        const formattedTime = `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;

        // Zamanlayıcıyı "w" değişkeni "countdown" olan SpriteText'e yaz
        const countdownText = runtime.objects.spriteText.getAllInstances().find(instance => instance.instVars.w === "countdown");
        if (countdownText) {
            countdownText.text = formattedTime;
        } else {
            console.error('No spriteText object with w="countdown" found.');
        }

        // Eğer zaman dolduysa işlemleri yap
        if (remainingTime <= 0) {
            clearInterval(countdownInterval);
            countdownInterval = null;
            if (typeof onFinish === "function") {
                onFinish(); // Süre dolduğunda verilen fonksiyonu çağır
            }
        }
    }, 1000);
}
function resetCountdown() {
    if (countdownInterval) {
        clearInterval(countdownInterval);
        countdownInterval = null;
    }
}
function failGame() {
    console.log("Game over! Time is up.");

    // Geri sayımı sıfırla
    resetCountdown();

    // Construct 3'e oyunun bittiğini bildir
    if (runtime) {
        runtime.callFunction("failgame");
		updateVariable("sub","lives",1);
    }

    // Oyunu sıfırlamak için gerekli işlemleri yap
    clearGridAndLetters();

    // Ek işlemler (örn. oyuncuya mesaj göstermek, tekrar deneme seçeneği sunmak vs.)
}
//GAMEMECHANICS//
function updateVariable(operation, key, value) {
    // Fetch the current value from localStorage
    let currentValue = parseInt(localStorage.getItem(`${gamePrefix}${key}`), 10) || 0;

    // Perform the operation
    if (operation === "add") {
        currentValue += value; // Add the value
    } else if (operation === "sub") {
        currentValue -= value; // Subtract the value
    } else if (operation === "set") {
        currentValue = value; // Set the value directly
    }

    // Ensure the value is not below 0
    if (currentValue < 0) {
        currentValue = 0;
    }

    // Special condition for "lives"
    if (key === "lives" && currentValue > 5) {
        currentValue = 5;
    }
    
    // Special handling for currentLevel
    if (key === "level" && typeof currentLevel !== "undefined") {
        currentLevel = currentValue; // Update the JavaScript global variable
    }

    // Save the updated value back to localStorage
    localStorage.setItem(`${gamePrefix}${key}`, currentValue);

    // Update the global Construct 3 variable
    if (runtime && runtime.globalVars[key] !== undefined) {
        runtime.globalVars[key] = currentValue; // Set the global variable
    }

    // Update the spriteText object with the final value
    if (runtime && runtime.objects.spriteText) {
        const allSpriteTexts = runtime.objects.spriteText.getAllInstances();
        allSpriteTexts.forEach(spriteText => {
            // Check if the "w" instance variable matches the key
            if (spriteText.instVars.w === key) {
                // Update the text property of the spriteText object to display the current value
                spriteText.text = currentValue.toString();
            }
        });
    }
}
function resetAllGameData() {
    console.log("Resetting all game data...");
    
    // Find all localStorage keys that start with gamePrefix
    const keysToRemove = [];
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && key.startsWith(gamePrefix)) {
            keysToRemove.push(key);
            console.log(`Found localStorage item to remove: ${key}`);
        }
    }
    
    // Remove all keys
    keysToRemove.forEach(key => {
        localStorage.removeItem(key);
        console.log(`Removed localStorage item: ${key}`);
    });
    
    // Reset current level to 0
    currentLevel = 0;
    localStorage.setItem(`${gamePrefix}level`, 0);
    console.log(`Reset currentLevel to 0`);
    
    // Reset default game values
    const defaultValues = {
        "lives": 5,
        "gold": 0,
        "level": 0,
        "score": 0
    };
    
    // Set default values
    for (const [key, value] of Object.entries(defaultValues)) {
        localStorage.setItem(`${gamePrefix}${key}`, value);
        console.log(`Reset ${key} to ${value}`);
        
        // Update Construct global variables if they exist
        if (runtime && runtime.globalVars && typeof runtime.globalVars[key] !== 'undefined') {
            runtime.globalVars[key] = value;
            console.log(`Updated runtime.globalVars.${key} to ${value}`);
        }
        
        // Update UI text directly
        const textElements = runtime.objects.spriteText.getAllInstances().filter(instance => 
            instance.instVars.w === key
        );
        
        textElements.forEach(textElement => {
            textElement.text = value.toString();
            console.log(`Updated text element for ${key} to ${value}`);
        });
    }
    
    // Make sure UI is updated
    updateText("lives");
    updateText("gold");
    updateText("level"); 
    updateText("score");
    
    console.log("All game data has been reset to default values");
    
    // Clear the grid and restart level
    if (runtime) {
        clearGridAndLetters();
        
        // Delay starting level to ensure UI is updated first
        setTimeout(() => {
            startLevel();
            console.log("Started fresh level after reset");
        }, 500);
    }
}


//RANDOMQUEST//
let currentTask = null;
function startTask() {
    // Eğer görev yoksa veya mevcut görev tamamlandıysa yeni görev oluştur
    if (!currentTask || currentTask.found >= currentTask.required) {
        if (currentTask && currentTask.found >= currentTask.required) {
            completeTask();
        }

        const savedTask = localStorage.getItem(`${gamePrefix}currentTask`);
        if (savedTask) {
            currentTask = JSON.parse(savedTask);
        } else {
            currentTask = generateTask();
            currentTask.startTime = Date.now();
            localStorage.setItem(`${gamePrefix}currentTask`, JSON.stringify(currentTask));
        }
    }

    // Süre kontrolü yap
    const elapsedTime = (Date.now() - currentTask.startTime) / 1000;
    const remainingTime = Math.max(0, currentTask.duration - elapsedTime);

    // Eğer süre bittiyse görevi tamamla ve yenile
    if (remainingTime <= 0) {
        completeTask();
        resetTask();
        return;
    }

    updateUI(); // UI güncelle
}
function generateTask() {
    // Sadece yaygın İngilizce harfler kullanılacak
    const letters = "ABCDEFGHIJKLMNOP".split("");
    const letter = letters[Math.floor(Math.random() * letters.length)];
    
    // Daha küçük ve kolay ulaşılabilir hedefler belirle
    const requiredOptions = [5, 10, 15, 20, 25, 30];
    const required = requiredOptions[Math.floor(Math.random() * requiredOptions.length)];
    
    // Ödül miktarlarını da yeni hedeflere göre ayarla
    const durationMap = {
        5: { gold: 250, lives: 1, duration: 15 * 60 },
        10: { gold: 500, lives: 1, duration: 30 * 60 },
        15: { gold: 750, lives: 1, duration: 45 * 60 },
        20: { gold: 1000, lives: 1, duration: 60 * 60 },
        25: { gold: 1250, lives: 1, duration: 90 * 60 },
        30: { gold: 1500, lives: 1, duration: 120 * 60 }
    };
    
    const reward = durationMap[required];
    return { letter, required, found: 0, reward, duration: reward.duration };
}
function completeTask() {
    if (currentTask) {
        const { gold, lives } = currentTask.reward;
        updateVariable("add", "gold", gold);
        updateVariable("add", "lives", 1);
        localStorage.removeItem(`${gamePrefix}currentTask`);
        console.log("Görev tamamlandı, ödüller verildi.");
    }
}
function resetTask() {
    currentTask = null;
    localStorage.removeItem(`${gamePrefix}currentTask`);
    currentTask = generateTask();
    currentTask.startTime = Date.now();
    localStorage.setItem(`${gamePrefix}currentTask`, JSON.stringify(currentTask));
    updateUI();
}
function updateUI() {
    const allSpriteTexts = runtime.objects.spriteText.getAllInstances();
    const allProgressBars = runtime.objects.collectiongrandprogress.getAllInstances();
    const randomTaskImg = runtime.objects.randomtaskimg.getFirstInstance();
    const randomquestp4 = runtime.objects.randomquestp4.getFirstInstance();

    const progressText = allSpriteTexts.find(sprite => sprite.instVars.w === "progresstask");
    if (progressText) {
        progressText.text = `${currentTask.found}/${currentTask.required}`;
    }

    const taskPrice = allSpriteTexts.find(spriteText => spriteText.instVars.w === "taskprice");
    const taskPrice2 = allSpriteTexts.find(spriteText => spriteText.instVars.w === "taskprice2");

    if (taskPrice) {
        taskPrice.text = `${currentTask.reward.gold}`;
    }

    const progressBar = allProgressBars.find(bar => bar.instVars.w === "task");
    if (progressBar) {
        const originalWidth = progressBar.instVars.originalWidth || progressBar.width;
        if (!progressBar.instVars.originalWidth) {
            progressBar.instVars.originalWidth = originalWidth;
        }
        const progressPercent = (currentTask.found / currentTask.required) * 100;
        progressBar.width = (originalWidth * progressPercent) / 100;
    }

    // randomtaskimg objesinin animasyonunu ayarla
    if (randomTaskImg) {
        randomTaskImg.setAnimation(currentTask.letter);
    }
    
    // randomquestp4 objesinin animasyonunu da aynı harfe ayarla
    if (randomquestp4) {
        randomquestp4.setAnimation(currentTask.letter);
        console.log(`randomquestp4 animasyonu '${currentTask.letter}' olarak ayarlandı.`);
    }

    const taskTimeText = allSpriteTexts.find(sprite => sprite.instVars.w === "tasktime");
    if (taskTimeText) {
        const elapsedTime = (Date.now() - currentTask.startTime) / 1000;
        const remainingTime = Math.max(0, currentTask.duration - elapsedTime);

        const hours = Math.floor(remainingTime / 3600);
        const minutes = Math.floor((remainingTime % 3600) / 60);
        const seconds = Math.floor(remainingTime % 60);

        if (hours > 0) {
            taskTimeText.text = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}`;
        } else {
            taskTimeText.text = `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
        }
    }
}
function addTask() {
    if (currentTask && currentTask.found < currentTask.required) {
        currentTask.found++;

        if (currentTask.found >= currentTask.required) {
            completeTask();
            resetTask(); // Yeni göreve geç
        } else {
            localStorage.setItem(`${gamePrefix}currentTask`, JSON.stringify(currentTask));
        }
    }

    updateUI();
}
//RANDOMQUEST//

//RANDOMQUEST//

function highlightRandomWord() {
    // Get current level
    const currentLevelVal = parseInt(localStorage.getItem(`${gamePrefix}level`), 10) || 0;
    
    // Check if this is level 0 or 1 and if we have already used the free highlight
    const hasUsedFreeHighlight = localStorage.getItem(`${gamePrefix}usedFreeHighlightLevel${currentLevelVal}`) === "true";
    const isEarlyLevel = currentLevelVal <= 1;
    
    // Determine cost based on level
    let goldCost = 1000; // Default cost
    
    // For levels 0-1, it's free but can only be used once
    if (isEarlyLevel) {
        if (hasUsedFreeHighlight) {
            console.log(`Level ${currentLevelVal} için ücretsiz ipucu kullanıldı. Artık 1000 altın gerekiyor.`);
            goldCost = 1000;
        } else {
            console.log(`Level ${currentLevelVal} için ücretsiz ipucu kullanılıyor.`);
            goldCost = 0;
        }
    }
    
    // Check if the player has enough gold (skip check if cost is 0)
    if (goldCost > 0) {
        const currentGold = parseInt(localStorage.getItem(`${gamePrefix}gold`), 10) || 0;
        if (currentGold < goldCost) {
            console.log(`Yetersiz altın! En az ${goldCost} altın gerekiyor.`);
            return;
        }
        
        // Deduct gold and update the UI
        updateVariable("sub", "gold", goldCost);
        console.log(`${goldCost} altın düşüldü.`);
    } else if (isEarlyLevel && !hasUsedFreeHighlight) {
        // Mark this free usage as used
        localStorage.setItem(`${gamePrefix}usedFreeHighlightLevel${currentLevelVal}`, "true");
        console.log(`Level ${currentLevelVal} için ücretsiz ipucu kullanıldı ve kaydedildi.`);
    }

    // Validate the global level exists
    if (!globalLevel || !Array.isArray(globalLevel) || globalLevel.length === 0) {
        console.error("Grid henüz hazır değil veya geçerli değil.");
        return;
    }

    // Get list of playable words (words that haven't been found yet)
    const playableWords = selectedWords.filter(wObj => !wObj.found);
    
    if (playableWords.length === 0) {
        console.log("Oynanabilir kelime kalmadı.");
        return;
    }

    // Choose a random word from playable words
    const randomWordObj = playableWords[Math.floor(Math.random() * playableWords.length)];
    const randomWord = randomWordObj.word.toUpperCase();
    
    console.log(`Rastgele seçilen kelime: "${randomWord}"`);

    // Find the word in the grid
    const wordLocation = isWordInGrid(globalLevel, randomWord);
    if (!wordLocation) {
        console.log(`"${randomWord}" kelimesi gridde bulunamadı.`);
        return;
    }

    // Extract the word's letter positions and UUIDs
    const { startRow, startCol, direction } = wordLocation;
    
    // Map direction name to dx, dy values
    const dirMap = {
        "yatay-sağ": { dx: 1, dy: 0 },
        "yatay-sol": { dx: -1, dy: 0 },
        "dikey-aşağı": { dx: 0, dy: 1 },
        "dikey-yukarı": { dx: 0, dy: -1 }
    };
    
    const { dx, dy } = dirMap[direction];
    
    // Collect letter UUIDs and highlight them
    const letterUUIDs = [];
    let partialWord = "";
    
    for (let i = 0; i < randomWord.length; i++) {
        const row = startRow + (i * dy);
        const col = startCol + (i * dx);
        
        if (row >= 0 && row < globalLevel.length && col >= 0 && col < globalLevel[0].length) {
            const cell = globalLevel[row][col];
            if (cell && cell.uuid) {
                letterUUIDs.push(cell.uuid);
                partialWord += cell.value;
                
                // Call wordopacity for each letter with accumulated word
                if (runtime) {
                    setTimeout(() => {
                        runtime.callFunction("wordopacity", cell.uuid, partialWord);
                    }, i * 200); // Stagger the animation with a 200ms delay between letters
                }
            }
        }
    }
    
    // Display visual effects
    if (letterUUIDs.length > 0) {
        // Get the middle letter position for effects
        const middleIndex = Math.floor(letterUUIDs.length / 2);
        const middleUUID = letterUUIDs[middleIndex];
        const middleRow = startRow + (middleIndex * dy);
        const middleCol = startCol + (middleIndex * dx);
        
        // Find the letter sprite to get its position
        const letterSprites = runtime.objects.Letters.getAllInstances();
        const middleSprite = letterSprites.find(sprite => sprite.instVars.uuid === middleUUID);
        
        if (middleSprite && runtime) {
            // Add particle effect
            setTimeout(() => {
                runtime.callFunction("particlestar", middleSprite.x, middleSprite.y, 200, 300, "Level");
            }, (randomWord.length * 200) + 100);
        }
    }
    
    console.log(`"${randomWord}" kelimesi gridde vurgulandı.`);
}

//RANDOMQUEST//

const scriptsInEvents = {

	async Start_Event1_Act6(runtime, localVars)
	{
		updateVariable("add","gold",0)
	},

	async Start_Event1_Act7(runtime, localVars)
	{
		updateVariable("add","level",0)
	},

	async Start_Event2_Act1(runtime, localVars)
	{
		localStorage.clear();
	},

	async Start_Event3_Act1(runtime, localVars)
	{
		addTask();
	},

	async Start_Event10_Act10(runtime, localVars)
	{
const storage = runtime.storage;

// Helper function to get a random value from an array
function getRandomFromArray(array) {
    return array[Math.floor(Math.random() * array.length)];
}

// Function to generate a random quest
async function generateRandomQuest() {
    const suits = ["Spades", "Hearts", "Diamonds", "Clubs"]; // Card suits
    const amounts = [20, 50, 100]; // Minimum task count is 20
    const rewards = { 20: 200, 50: 500, 100: 1000 }; // Rewards based on task count

    const randomSuit = getRandomFromArray(suits);
    const randomAmount = getRandomFromArray(amounts);
    const reward = rewards[randomAmount];

    const questName = `${randomAmount}${randomSuit}`;
    const questData = `${questName}-${reward}-0`; // Start with progress 0

    await storage.setItem("randomQuest", questData);

    // Set animation for `randomquestp4`
    const questP4Object = runtime.objects.randomquestp4.getFirstInstance();
    if (questP4Object) {
        questP4Object.setAnimation(randomSuit); // Set the animation to the suit (Spades, Hearts, Diamonds, Clubs)
        console.log(`randomquestp4 animation set to: ${randomSuit}`);
    } else {
        console.error("randomquestp4 object not found.");
    }

    console.log(`Generated quest: ${questData}`); // Log the generated quest
    return questData;
}

// Function to process the current quest (log it, update texts, call reward function)
async function processQuest(questData) {
    const [questName, reward, currentProgress] = questData.split("-");
    const targetAmount = parseInt(questName.match(/\d+/)[0], 10); // Extract target amount from quest name
    const progress = Math.min(parseInt(currentProgress, 10), targetAmount); // Ensure progress doesn't exceed target

    // Update `randomquesttxt` text
    const questTextObject = runtime.objects.randomquesttxt.getFirstInstance();
    if (questTextObject) {
        questTextObject.text = `${progress}/${targetAmount}`;
        console.log(`randomquesttxt updated: ${progress}/${targetAmount}`);
    } else {
        console.error("randomquesttxt object not found.");
    }

    // Update `randomquesttxt2` text
    const rewardTextObject = runtime.objects.randomquesttxt2.getFirstInstance();
    if (rewardTextObject) {
        rewardTextObject.text = `${reward} Gold`;
        console.log(`randomquesttxt2 updated: ${reward} Gold`);
    } else {
        console.error("randomquesttxt2 object not found.");
    }

    // Calculate percentage progress for `randomquestreward`
    const progressPercent = Math.floor((progress / targetAmount) * 100);
    runtime.callFunction("randomquestreward", progressPercent, 100);
    console.log(`Called randomquestreward with value: ${progressPercent}, maxValue: 100`);

    // Check if the quest is completed
    if (progress >= targetAmount) {
        console.log("Quest completed! Removing old quest, rewarding gold, and generating a new one...");

        // Retrieve current gold
        let savedGold = await storage.getItem("gold");
        let goldValue = savedGold ? parseInt(savedGold, 10) : 0;

        // Add the quest reward to the total gold
        const rewardValue = parseInt(reward, 10);
        goldValue += rewardValue;
        await storage.setItem("gold", goldValue.toString());
        console.log(`Gold increased by ${rewardValue}. Total gold is now: ${goldValue}.`);

        // Update `giftTXT2` with the reward value
        const giftText = runtime.objects.giftTXT2.getFirstInstance();
        if (giftText) {
            giftText.text = rewardValue.toString();
            console.log(`giftTXT2 updated with reward value: ${rewardValue}.`);
        } else {
            console.error("giftTXT2 object not found.");
        }

        // Update `goldTXT` with the total gold value
        const goldText = runtime.objects.goldTXT.getFirstInstance();
        if (goldText) {
            goldText.text = goldValue.toString();
            console.log(`goldTXT updated with total gold value: ${goldValue}.`);
        } else {
            console.error("goldTXT object not found.");
        }

        // Remove the completed quest
        await storage.removeItem("randomQuest");

        // Generate a new quest and process it
        const newQuest = await generateRandomQuest();
        await processQuest(newQuest);
    }
}

// Main logic
(async () => {
    let existingQuest = await storage.getItem("randomQuest");

    if (!existingQuest) {
        console.log("No existing quest found. Generating a new one...");
        existingQuest = await generateRandomQuest();
    } else {
        console.log(`Existing quest found: ${existingQuest}`);
    }

    // Ensure progress remains unchanged unless explicitly updated
    const [questName, reward, currentProgress] = existingQuest.split("-");
    const targetAmount = parseInt(questName.match(/\d+/)[0], 10);
    const progress = Math.min(parseInt(currentProgress, 10), targetAmount);

    // Update the quest data with the current progress (ensure no accidental change)
    const validatedQuestData = `${questName}-${reward}-${progress}`;
    await storage.setItem("randomQuest", validatedQuestData);

    // Process the quest to ensure everything is logged and updated
    await processQuest(validatedQuestData);
})();

	},

	async Start_Event13_Act1(runtime, localVars)
	{
		startTask();
	},

	async Start_Event15_Act1(runtime, localVars)
	{
		startTask();
	},

	async Start_Event17_Act9(runtime, localVars)
	{
		updateVariable("add","level",1)
	},

	async Start_Event17_Act10(runtime, localVars)
	{
		updateVariable("add","gold",350)
	},

	async Start_Event17_Act11(runtime, localVars)
	{
		updateVariable("add","starRewards",5)
	},

	async EventSheet1_Event1_Act3(runtime, localVars)
	{
		startLevel();
	},

	async EventSheet1_Event18_Act1(runtime, localVars)
	{
		const picked = runtime.objects.Letters.getPickedInstances()[0];
		if (picked) {
		  guessLetter(picked.instVars.uuid);
		}
		
	},

	async EventSheet1_Event19_Act1(runtime, localVars)
	{
		end();
		
	},

	async EventSheet1_Event19_Act3(runtime, localVars)
	{
		checkPlayableWordsOrRearrange();
	},

	async EventSheet1_Event28_Act2(runtime, localVars)
	{
		openAndRevertHiddenWordSprites();
		
	},

	async EventSheet1_Event29_Act2(runtime, localVars)
	{
		openSingleLetter();
	},

	async EventSheet1_Event30_Act2(runtime, localVars)
	{
		highlightRandomWord();
	},

	async EventSheet1_Event31_Act1(runtime, localVars)
	{
		updateVariable("add","gold",1000)
	},

	async Setup_Event88_Act1(runtime, localVars)
	{
// Define chest reward information
const storage = runtime.storage;
const chestRewards = [
    { name: 'chestReward1', duration: 1800, booleanVar: 'chestRewardq1', chestType: 1, wasVisible: false },
    { name: 'chestReward2', duration: 3600, booleanVar: 'chestRewardq2', chestType: 2, wasVisible: false },
    { name: 'chestReward3', duration: 180, booleanVar: 'chestRewardq3', chestType: 3, wasVisible: false }
];

// Ensure visibility of rewards at startup
async function ensureRewardVisibilityOnStart() {
    for (const chest of chestRewards) {
        const savedTime = await storage.getItem(chest.name);
        const savedTimestamp = await storage.getItem(`${chest.name}_timestamp`);
        const currentTime = Math.floor(Date.now() / 1000);

        if (savedTime && savedTimestamp) {
            const previousTime = parseInt(savedTimestamp, 10);
            const elapsedTime = currentTime - previousTime;
            const remainingTime = Math.max(0, parseInt(savedTime, 10) - elapsedTime);

            console.log(`Chest Type ${chest.chestType}: Remaining time from local = ${remainingTime}`);

            if (remainingTime === 0) {
                chest.isGiven = true;
                storage.setItem(chest.booleanVar, 'true');
                updateChestVisibility(chest);
                console.log(`Chest Type ${chest.chestType}: Time is up. Button made visible.`);
            }
        } else {
            console.log(`Chest Type ${chest.chestType}: No saved time or timestamp found.`);
        }
    }
}

// Load chest data
async function loadChestData() {
    for (const chest of chestRewards) {
        const savedTime = await storage.getItem(chest.name);
        const savedTimestamp = await storage.getItem(`${chest.name}_timestamp`);
        const isRewardGiven = await storage.getItem(chest.booleanVar);
        const currentTime = Math.floor(Date.now() / 1000);

        if (!savedTime) {
            chest.currentDuration = 0;
            chest.isGiven = true;
            await storage.setItem(chest.booleanVar, 'true');
            updateChestVisibility(chest);
            updateChestTimeText(chest.chestType, chest.currentDuration);
        } else {
            chest.currentDuration = parseInt(savedTime, 10);

            if (savedTimestamp) {
                const previousTime = parseInt(savedTimestamp, 10);
                const timeElapsed = currentTime - previousTime;
                chest.currentDuration = Math.max(0, chest.currentDuration - timeElapsed);
            }

            chest.isGiven = isRewardGiven === 'true';
            chest.wasVisible = chest.isGiven;
            updateChestVisibility(chest);
            updateChestTimeText(chest.chestType, chest.currentDuration);
        }
    }

    setupButtonClickHandlers();
}

// Update chest timers
function updateChestTimers() {
    chestRewards.forEach(chest => {
        if (chest.isGiven) {
            updateChestVisibility(chest);
            return;
        }

        if (chest.currentDuration > 0) {
            chest.currentDuration--;
            storage.setItem(chest.name, chest.currentDuration.toString());
            storage.setItem(`${chest.name}_timestamp`, Math.floor(Date.now() / 1000).toString());
        } else {
            chest.isGiven = true;
            storage.setItem(chest.booleanVar, 'true');
            updateChestVisibility(chest);
        }

        updateChestTimeText(chest.chestType, chest.currentDuration);
    });
}

// Update visibility of chest button and time display based on `isGiven`
function updateChestVisibility(chest) {
    const { chestType, isGiven, wasVisible } = chest;

    if (isGiven !== wasVisible) {
        const chestTimeObjects = runtime.objects.chestTime.getAllInstances();
        const chestButtonObjects = runtime.objects.chestRewardButton.getAllInstances();

        chestTimeObjects.forEach(chestTime => {
            if (chestTime.instVars.type === chestType) {
                chestTime.isVisible = !isGiven;
            }
        });

        chestButtonObjects.forEach(button => {
            if (button.instVars.type === chestType) {
                button.isVisible = isGiven;
            }
        });

        console.log(`Visibility updated: Chest Type ${chestType}, isVisible = ${isGiven}`);
        
        chest.wasVisible = isGiven; // Save the visibility state
    }
}

// Update chest time text
function updateChestTimeText(type, remainingTime) {
    const chestTimeObjects = runtime.objects.chestTime.getAllInstances();
    const formattedTime = formatTime(remainingTime);

    chestTimeObjects.forEach(chest => {
        if (chest.instVars.type === type) {
            chest.text = formattedTime;
        }
    });
}

// Reset the chest when button is clicked
globalThis.resetChest = function (chestType) {
    const chest = chestRewards.find(chest => chest.chestType === chestType);
    if (chest && chest.isGiven) {
        chest.isGiven = false;
        chest.currentDuration = chest.duration;
        storage.setItem(chest.name, chest.currentDuration.toString());
        storage.setItem(chest.booleanVar, 'false');
        storage.setItem(`${chest.name}_timestamp`, Math.floor(Date.now() / 1000).toString());
        chest.wasVisible = false;
        console.log(`Chest reset: Chest Type ${chestType}, visibility should now be false.`);
        updateChestVisibility(chest);
    }
};

// Set up button click events
function setupButtonClickHandlers() {
    const chestButtonObjects = runtime.objects.chestRewardButton.getAllInstances();

    chestButtonObjects.forEach(button => {
        button.addEventListener('click', () => {
            const chestType = button.instVars.type;
            console.log(`Button clicked, chestType: ${chestType}`);
            resetChest(chestType);
        });
    });
}

// Format time to MM:SS
function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// Load initial data
ensureRewardVisibilityOnStart(); // Ensure visibility on start
loadChestData();

// Update timers every second
setInterval(updateChestTimers, 1000);

	},

	async Setup_Event89_Act1(runtime, localVars)
	{
		// Burada globalThis ile tanımlanmış fonksiyonu çağırıyoruz
		const chestType = runtime.objects.chestRewardButton.getFirstPickedInstance().instVars.type;
		globalThis.resetChest(chestType);
		
	},

	async Setup_Event95_Act9(runtime, localVars)
	{
		updateVariable("add","gold",250)
	}
};

globalThis.C3.JavaScriptInEvents = scriptsInEvents;
