// ========================
// LETTERQUEST GAME
// ========================

// Level Configuration
const LEVEL_CONFIG = {
    1: { gridSize: 5, wordCount: 3, minWordLen: 3, maxWordLen: 4, timeLimit: 40 },
    2: { gridSize: 6, wordCount: 4, minWordLen: 3, maxWordLen: 5, timeLimit: 45 },
    3: { gridSize: 7, wordCount: 5, minWordLen: 4, maxWordLen: 6, timeLimit: 50 },
    4: { gridSize: 8, wordCount: 6, minWordLen: 4, maxWordLen: 6, timeLimit: 55 },
    5: { gridSize: 9, wordCount: 7, minWordLen: 4, maxWordLen: 7, timeLimit: 60 },
    6: { gridSize: 10, wordCount: 8, minWordLen: 5, maxWordLen: 7, timeLimit: 65 },
    7: { gridSize: 11, wordCount: 9, minWordLen: 5, maxWordLen: 8, timeLimit: 70 },
    8: { gridSize: 12, wordCount: 10, minWordLen: 6, maxWordLen: 8, timeLimit: 75 },
    9: { gridSize: 13, wordCount: 11, minWordLen: 6, maxWordLen: 9, timeLimit: 80 },
    10: { gridSize: 14, wordCount: 12, minWordLen: 7, maxWordLen: 10, timeLimit: 90 },
    11: { gridSize: 15, wordCount: 13, minWordLen: 7, maxWordLen: 10, timeLimit: 95 },
    12: { gridSize: 16, wordCount: 14, minWordLen: 7, maxWordLen: 11, timeLimit: 100 },
    13: { gridSize: 16, wordCount: 15, minWordLen: 8, maxWordLen: 11, timeLimit: 105 },
    14: { gridSize: 17, wordCount: 16, minWordLen: 8, maxWordLen: 12, timeLimit: 110 },
    15: { gridSize: 17, wordCount: 17, minWordLen: 8, maxWordLen: 12, timeLimit: 115 },
    16: { gridSize: 18, wordCount: 18, minWordLen: 9, maxWordLen: 12, timeLimit: 120 },
    17: { gridSize: 18, wordCount: 19, minWordLen: 9, maxWordLen: 13, timeLimit: 125 },
    18: { gridSize: 19, wordCount: 20, minWordLen: 9, maxWordLen: 13, timeLimit: 130 },
    19: { gridSize: 19, wordCount: 21, minWordLen: 10, maxWordLen: 13, timeLimit: 135 },
    20: { gridSize: 20, wordCount: 22, minWordLen: 10, maxWordLen: 14, timeLimit: 140 }
};

// Word Dictionary - Curated common English words
const WORD_DICTIONARY = [
    "cat", "dog", "bat", "hat", "rat", "mat", "sat", "pat", "fat", "car", "bar", "jar", "tar", "far", "gap", "cap", "map",
    "nap", "rap", "sap", "tap", "bad", "dad", "had", "mad", "pad", "sad", "bag", "gag", "tag", "ban", "can", "fan", "man",
    "pan", "ran", "tan", "van", "ham", "jam", "day", "hay", "jay", "lay", "may", "pay", "ray", "say", "way", "bed", "fed",
    "red", "wed", "bee", "den", "hen", "men", "pen", "ten", "bet", "get", "jet", "let", "met", "net", "pet", "set", "vet",
    "wet", "yet", "bid", "did", "hid", "kid", "lid", "big", "dig", "fig", "pig", "wig", "bin", "din", "fin", "pin", "sin",
    "tin", "win", "dip", "hip", "lip", "nip", "rip", "sip", "tip", "zip", "bit", "fit", "hit", "kit", "lit", "pit", "sit",
    "wit", "bob", "cob", "job", "mob", "rob", "bog", "cog", "fog", "hog", "jog", "log", "bop", "cop", "hop", "mop", "pop",
    "top", "bot", "cot", "dot", "got", "hot", "jot", "lot", "not", "pot", "rot", "tot", "bow", "cow", "how", "low", "mow",
    "now", "row", "tow", "vow", "wow", "box", "fox", "boy", "joy", "toy", "bud", "dud", "mud", "bug", "dug", "hug", "jug",
    "mug", "pug", "rug", "tug", "bum", "gum", "hum", "rum", "sum", "bun", "dun", "fun", "gun", "nun", "pun", "run", "sun",
    "bus", "but", "cut", "gut", "hut", "jut", "nut", "put", "buy", "guy", "sky", "spy", "try", "cry", "dry", "fly", "fry",
    "able", "acid", "aged", "also", "area", "army", "away", "baby", "back", "ball", "band", "bank", "base", "bath", "bear",
    "beat", "been", "beer", "bell", "belt", "best", "bill", "bird", "blow", "blue", "boat", "body", "bomb", "bond", "bone",
    "book", "boom", "born", "boss", "both", "bowl", "burn", "bush", "busy", "cafe", "cake", "call", "calm", "came", "camp",
    "card", "care", "case", "cash", "cast", "cave", "cell", "chat", "chip", "city", "clay", "club", "coal", "coat", "code",
    "cold", "come", "cool", "cope", "copy", "core", "corn", "cost", "crab", "crew", "crop", "cube", "cure", "dark", "data",
    "date", "dawn", "days", "dead", "deal", "dean", "dear", "debt", "deck", "deep", "deer", "desk", "diet", "dire", "dirt",
    "disc", "dish", "dive", "dock", "does", "done", "door", "dose", "down", "drag", "draw", "drew", "drop", "drug", "drum",
    "dual", "duck", "duke", "dull", "dumb", "dump", "dune", "dusk", "dust", "duty", "each", "earl", "earn", "ease", "east",
    "easy", "echo", "edge", "edit", "else", "envy", "epic", "even", "ever", "evil", "exam", "exit", "face", "fact", "fade",
    "fail", "fair", "fall", "fame", "farm", "fast", "fate", "fear", "feed", "feel", "feet", "fell", "felt", "file", "fill",
    "film", "find", "fine", "fire", "firm", "fish", "fist", "five", "flag", "flat", "fled", "flee", "flew", "flow", "folk",
    "fond", "food", "fool", "foot", "ford", "fork", "form", "fort", "foul", "four", "free", "from", "fuel", "full", "fund",
    "gain", "game", "gang", "gate", "gave", "gear", "gene", "gift", "girl", "give", "glad", "glow", "glue", "goal", "goat",
    "goes", "gold", "golf", "gone", "good", "grab", "gram", "gray", "grew", "grey", "grid", "grim", "grin", "grip", "grow",
    "gulf", "hair", "half", "hall", "halt", "hand", "hang", "hard", "harm", "hate", "have", "hawk", "head", "heal", "heap",
    "hear", "heat", "heel", "heir", "held", "hell", "help", "herb", "here", "hero", "hide", "high", "hill", "hint", "hire",
    "hold", "hole", "holy", "home", "hood", "hook", "hope", "horn", "host", "hour", "huge", "hung", "hunt", "hurt", "icon",
    "idea", "idle", "inch", "into", "iron", "isle", "item", "jail", "jazz", "jean", "join", "joke", "jump", "june", "jury",
    "just", "keen", "keep", "kept", "kick", "kill", "kind", "king", "kiss", "knee", "knew", "knit", "know", "lack", "lady",
    "laid", "lake", "lamb", "lamp", "land", "lane", "last", "late", "lead", "leaf", "lean", "leap", "left", "lend", "lens",
    "lent", "less", "liar", "life", "lift", "like", "limb", "lime", "line", "link", "lion", "list", "live", "load", "loan",
    "lock", "long", "look", "loop", "lord", "lose", "loss", "lost", "loud", "love", "luck", "lung", "made", "maid", "mail",
    "main", "make", "male", "mall", "mark", "mars", "mask", "mass", "mate", "math", "maze", "meal", "mean", "meat", "meet",
    "melt", "menu", "mere", "mesh", "mess", "mice", "mild", "mile", "milk", "mill", "mind", "mine", "mint", "miss", "mist",
    "mode", "mood", "moon", "more", "moss", "most", "move", "much", "myth", "nail", "name", "navy", "near", "neat", "neck",
    "need", "nest", "news", "next", "nice", "nick", "nine", "node", "none", "noon", "norm", "nose", "note", "noun", "null",
    "numb", "oath", "obey", "odds", "okay", "once", "only", "onto", "open", "oral", "oven", "over", "owns", "pace", "pack",
    "page", "paid", "pain", "pair", "pale", "palm", "park", "part", "pass", "past", "path", "peak", "peer", "pick", "pile",
    "pill", "pine", "pink", "pipe", "pity", "plan", "play", "plot", "plug", "plus", "poem", "poet", "pole", "poll", "pond",
    "pony", "pool", "poor", "pope", "pork", "port", "pose", "post", "pour", "pray", "prep", "prey", "pure", "push", "quit",
    "quiz", "race", "rack", "rage", "raid", "rail", "rain", "rank", "rare", "rate", "read", "real", "rear", "reef", "rely",
    "rent", "rest", "rice", "rich", "ride", "ring", "rise", "risk", "road", "roar", "robe", "rock", "rode", "role", "roll",
    "roof", "room", "root", "rope", "rose", "rude", "rule", "rush", "rust", "safe", "sage", "said", "sail", "sake", "sale",
    "salt", "same", "sand", "sank", "save", "seal", "seat", "seed", "seek", "seem", "seen", "self", "sell", "send", "sent",
    "shed", "ship", "shoe", "shop", "shot", "show", "shut", "sick", "side", "sign", "silk", "sing", "sink", "site", "size",
    "skin", "skip", "slam", "slay", "slew", "slid", "slim", "slip", "slot", "slow", "slug", "snap", "snow", "soak", "soap",
    "soar", "sock", "soft", "soil", "sold", "sole", "some", "song", "soon", "sore", "sort", "soul", "soup", "sour", "span",
    "spar", "spec", "sped", "spin", "spot", "stab", "stag", "star", "stay", "stem", "step", "stew", "stir", "stop", "stud",
    "such", "suit", "sung", "sunk", "sure", "surf", "swap", "swam", "swan", "sway", "swim", "tail", "take", "tale", "talk",
    "tall", "tank", "tape", "task", "taxi", "team", "tear", "tell", "tend", "tent", "term", "test", "text", "than", "that",
    "them", "then", "they", "thin", "this", "thou", "thud", "thus", "tick", "tide", "tidy", "tied", "tier", "tile", "till",
    "tilt", "time", "tiny", "tire", "toad", "told", "toll", "tomb", "tone", "took", "tool", "tops", "tore", "torn", "toss",
    "tour", "town", "tray", "tree", "trim", "trio", "trip", "trot", "true", "tube", "tune", "turn", "twig", "twin", "type",
    "ugly", "undo", "unit", "upon", "urge", "used", "user", "uses", "vain", "vast", "veil", "vein", "verb", "very", "vest",
    "veto", "vice", "view", "vine", "visa", "void", "volt", "vote", "wage", "wait", "wake", "walk", "wall", "want", "ward",
    "warm", "warn", "wary", "wash", "wave", "wavy", "weak", "wear", "weed", "week", "well", "went", "were", "west", "what",
    "when", "whip", "wide", "wife", "wild", "will", "wind", "wine", "wing", "wink", "wipe", "wire", "wise", "wish", "with",
    "wolf", "wood", "wool", "word", "wore", "work", "worm", "worn", "wrap", "yard", "yeah", "year", "yell", "yoga", "your",
    "zero", "zone", "zoom",
    "about", "above", "abuse", "actor", "acute", "admit", "adopt", "adult", "after", "again", "agent", "agree", "ahead",
    "alarm", "album", "alert", "alike", "alive", "allow", "alone", "along", "alter", "among", "anger", "angle", "angry",
    "apart", "apple", "apply", "arena", "argue", "arise", "array", "arrow", "aside", "asset", "avoid", "awake", "award",
    "aware", "badly", "baker", "bases", "basic", "beach", "beard", "beast", "began", "begin", "being", "below", "bench",
    "birth", "black", "blade", "blame", "blank", "blend", "bless", "blind", "block", "blood", "bloom", "board", "boost",
    "booth", "bound", "brain", "brand", "brave", "bread", "break", "breed", "brief", "bring", "broad", "broke", "brown",
    "build", "built", "bunch", "burst", "buyer", "cable", "calif", "carry", "catch", "cause", "chain", "chair", "chaos",
    "charm", "chart", "chase", "cheap", "check", "cheek", "chest", "chief", "child", "china", "chose", "civil", "claim",
    "class", "clean", "clear", "climb", "clock", "close", "cloth", "cloud", "coach", "coast", "count", "court", "cover",
    "crack", "craft", "crash", "crazy", "cream", "crime", "cross", "crowd", "crown", "crude", "cruel", "curve", "cycle",
    "daily", "dance", "death", "debut", "delay", "dense", "depth", "doing", "doubt", "dozen", "draft", "drama", "drank",
    "dream", "dress", "dried", "drill", "drink", "drive", "driven", "drove", "drunk", "eager", "early", "earth", "eight",
    "elite", "empty", "enemy", "enjoy", "enter", "entry", "equal", "error", "event", "every", "exact", "exist", "extra",
    "faith", "false", "fault", "fence", "fiber", "field", "fifty", "fight", "final", "first", "fixed", "flash", "fleet",
    "flesh", "float", "floor", "flour", "focus", "force", "forth", "forty", "forum", "found", "frame", "frank", "fraud",
    "fresh", "front", "frost", "fruit", "fully", "funny", "giant", "given", "glass", "globe", "glory", "glove", "grace",
    "grade", "grain", "grand", "grant", "grape", "graph", "grasp", "grass", "grave", "great", "green", "greet", "gross",
    "group", "grown", "guard", "guess", "guest", "guide", "guilt", "habit", "happy", "harsh", "haste", "heart", "heavy",
    "hence", "henry", "honor", "horse", "hotel", "house", "human", "humor", "ideal", "image", "imply", "index", "inner",
    "input", "issue", "japan", "jones", "judge", "known", "label", "labor", "large", "laser", "later", "laugh", "layer",
    "learn", "lease", "least", "leave", "legal", "lemon", "level", "lewis", "light", "limit", "linux", "local", "logic",
    "loose", "lower", "loyal", "lucky", "lunch", "lying", "magic", "major", "maker", "march", "match", "mayor", "meant",
    "media", "metal", "might", "minor", "minus", "mixed", "model", "money", "month", "moral", "motor", "mount", "mouse",
    "mouth", "movie", "music", "needs", "nerve", "never", "newly", "night", "ninth", "noble", "noise", "north", "noted",
    "novel", "nurse", "occur", "ocean", "offer", "often", "order", "other", "ought", "outer", "owner", "panel", "panic",
    "paper", "paris", "party", "pasta", "patch", "pause", "peace", "peter", "phase", "phone", "photo", "piano", "piece",
    "pilot", "pitch", "place", "plain", "plane", "plant", "plate", "plaza", "point", "poker", "polar", "pound", "power",
    "press", "price", "pride", "prime", "print", "prior", "prison", "proof", "proud", "prove", "queen", "quest", "quick",
    "quiet", "quite", "radio", "raise", "ranch", "range", "rapid", "ratio", "reach", "react", "ready", "realm", "refer",
    "relax", "reply", "rider", "ridge", "rifle", "right", "rigid", "river", "robot", "rocky", "roger", "roman", "rough",
    "round", "route", "royal", "rural", "scale", "scare", "scene", "scope", "score", "scout", "scrap", "sense", "serve",
    "seven", "shall", "shape", "share", "sharp", "sheep", "sheer", "sheet", "shelf", "shell", "shift", "shine", "shirt",
    "shock", "shoot", "shore", "short", "shown", "sight", "silly", "since", "sixth", "sixty", "sized", "skill", "slave",
    "sleep", "slept", "slice", "slide", "slope", "small", "smart", "smell", "smile", "smoke", "snake", "solid", "solve",
    "sorry", "sound", "south", "space", "spare", "speak", "speed", "spend", "spent", "split", "spoke", "sport", "squad",
    "stack", "stage", "stake", "stand", "stark", "start", "state", "steam", "steel", "steep", "steer", "stick", "still",
    "stock", "stone", "stood", "store", "storm", "story", "strip", "stuck", "study", "stuff", "style", "sugar", "suite",
    "super", "surge", "sweet", "swift", "swing", "sword", "table", "taken", "taste", "teach", "tempo", "tense", "tenth",
    "texas", "thank", "theft", "their", "theme", "there", "these", "thick", "thing", "think", "third", "those", "three",
    "threw", "throw", "thumb", "tiger", "tight", "timer", "title", "toast", "today", "token", "topic", "total", "touch",
    "tough", "tower", "toxic", "track", "tract", "trade", "trail", "train", "trait", "trash", "treat", "trend", "trial",
    "tribe", "trick", "tried", "troop", "truck", "truly", "trunk", "trust", "truth", "tulip", "tumor", "twist", "ultra",
    "uncle", "under", "undue", "unfair", "union", "unity", "until", "upper", "upset", "urban", "usage", "usual", "utter",
    "valid", "value", "vapor", "vault", "venue", "verde", "verse", "video", "virus", "visit", "vital", "vivid", "vocal",
    "voice", "voter", "wagon", "waste", "watch", "water", "wheat", "wheel", "where", "which", "while", "white", "whole",
    "whose", "woman", "women", "world", "worry", "worse", "worst", "worth", "would", "wound", "write", "wrong", "wrote",
    "yield", "young", "yours", "youth"
];

// Directions for word placement (8 directions)
const DIRECTIONS = [
    { dr: 0, dc: 1 },   // Right
    { dr: 1, dc: 0 },   // Down
    { dr: 1, dc: 1 },   // Diagonal down-right
    { dr: 1, dc: -1 },  // Diagonal down-left
    { dr: 0, dc: -1 },  // Left
    { dr: -1, dc: 0 },  // Up
    { dr: -1, dc: 1 },  // Diagonal up-right
    { dr: -1, dc: -1 }  // Diagonal up-left
];

// Game State
let gameState = {
    currentLevel: 1,
    totalScore: 0,
    grid: [],
    gridSize: 0,
    hiddenWords: [],
    foundWords: [],
    wordPositions: [],  // Store positions of each word
    timer: null,
    timeRemaining: 0,
    isPlaying: false,
    selecting: false,
    startCell: null,
    selectedCells: [],
    timestamp: 0
};

// Game Progress (Persistent)
let gameProgress = {
    maxLevel: 1,
    highScore: 0,
    unlockedLevels: [1],
    stats: {} // Will hold { level: { completions: 0, failures: 0, bestTime: null, bestScore: 0 } }
};

// Track game start time
let gameStartTime = null;

// DOM Elements
const elements = {
    hud: document.querySelector('.game-stats'),
    mainMenuBtn: document.getElementById('main-menu-btn'),
    startScreen: document.getElementById('start-screen'),
    levelCompleteScreen: document.getElementById('level-complete-screen'),
    levelFailedScreen: document.getElementById('level-failed-screen'),
    gameCompleteScreen: document.getElementById('game-complete-screen'),
    gridContainer: document.getElementById('letter-grid'),
    wordListContainer: document.getElementById('word-list-container'),
    wordList: document.getElementById('word-list'),
    levelDisplay: document.getElementById('level-display'),
    timerDisplay: document.getElementById('timer-display'),
    wordsDisplay: document.getElementById('words-display'),
    scoreDisplay: document.getElementById('score-display'),
    levelGrid: document.getElementById('level-grid'),
    maxLevelDisplay: document.getElementById('max-level-display'),
    highScoreDisplay: document.getElementById('high-score-display'),
    nextLevelBtn: document.getElementById('next-level-btn'),
    retryBtn: document.getElementById('retry-btn'),
    menuBtnWin: document.getElementById('menu-btn-win'),
    menuBtnLose: document.getElementById('menu-btn-lose'),
    menuBtnComplete: document.getElementById('menu-btn-complete'),
    playAgainBtn: document.getElementById('play-again-btn'),
    viewStatsCard: document.getElementById('view-stats-card'),
    closeStatsBtn: document.getElementById('close-stats-btn'),
    statsScreen: document.getElementById('stats-screen')
};

// Event Listeners
if (elements.mainMenuBtn) elements.mainMenuBtn.addEventListener('click', backToMenu);
if (elements.nextLevelBtn) elements.nextLevelBtn.addEventListener('click', nextLevel);
if (elements.retryBtn) elements.retryBtn.addEventListener('click', retryLevel);
if (elements.menuBtnWin) elements.menuBtnWin.addEventListener('click', backToMenu);
if (elements.menuBtnLose) elements.menuBtnLose.addEventListener('click', backToMenu);
if (elements.menuBtnComplete) elements.menuBtnComplete.addEventListener('click', backToMenu);
if (elements.playAgainBtn) elements.playAgainBtn.addEventListener('click', playAgain);

// Stats Event Listeners
if (elements.viewStatsCard) {
    console.log('Stats card found, attaching listener');
    elements.viewStatsCard.addEventListener('click', (e) => {
        console.log('Stats card clicked');
        showStats();
    });
    elements.viewStatsCard.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
            showStats();
        }
    });
} else {
    console.error('Stats card element NOT found');
}

if (elements.closeStatsBtn) {
    elements.closeStatsBtn.addEventListener('click', () => {
        if (elements.statsScreen) elements.statsScreen.classList.add('hidden');
    });
}

// ========================
// GAME FUNCTIONS
// ========================

function startGame(level) {
    if (!isLevelUnlocked(level)) return;

    const config = LEVEL_CONFIG[level];
    
    // Reset state
    gameState.currentLevel = level;
    gameState.foundWords = [];
    gameState.timeRemaining = config.timeLimit;
    gameState.isPlaying = true;
    gameState.gridSize = config.gridSize;
    gameState.totalScore = (level === 1) ? 0 : gameState.totalScore; // Reset score if level 1, else keep accumulating? 
    // Actually, if we select a level from menu, we should probably reset score or treat it as a new run.
    // For simplicity, let's say selecting from menu starts fresh run from that level.
    // But if we are proceeding to next level, we keep score.
    // The 'startGame' function is called from menu. 'nextLevel' calls 'startLevel'.
    
    startLevel(level);
}

function startLevel(level) {
    const config = LEVEL_CONFIG[level];
    
    gameState.currentLevel = level;
    gameState.foundWords = [];
    gameState.timeRemaining = config.timeLimit;
    gameState.isPlaying = true;
    gameState.gridSize = config.gridSize;
    
    // Select random words
    gameState.hiddenWords = selectRandomWords(config.wordCount, config.minWordLen, config.maxWordLen);
    
    // Generate grid
    generateGrid();
    
    // Update UI
    updateUI();
    showScreen('game');
    
    // Start timer
    startTimer();
    
    // Track game start with timestamp
    gameStartTime = Date.now();
    if (typeof trackGameStart === 'function') {
        trackGameStart('letterquest');
    }
    
    saveGameState();
    
    // Remove any existing grace period notification
    const notification = document.querySelector('.grace-period-notification');
    if (notification) notification.remove();
}

function selectRandomWords(count, minLen, maxLen) {
    const validWords = WORD_DICTIONARY.filter(word => 
        word.length >= minLen && word.length <= maxLen
    );
    
    // Shuffle and select
    const shuffled = validWords.sort(() => Math.random() - 0.5);
    return shuffled.slice(0, count).map(w => w.toUpperCase());
}

function generateGrid() {
    const size = gameState.gridSize;
    gameState.grid = Array(size).fill(null).map(() => Array(size).fill(''));
    gameState.wordPositions = [];
    
    // Place each word
    for (const word of gameState.hiddenWords) {
        let placed = false;
        let attempts = 0;
        
        while (!placed && attempts < 100) {
            const direction = DIRECTIONS[Math.floor(Math.random() * DIRECTIONS.length)];
            const startRow = Math.floor(Math.random() * size);
            const startCol = Math.floor(Math.random() * size);
            
            if (canPlaceWord(word, startRow, startCol, direction)) {
                placeWord(word, startRow, startCol, direction);
                placed = true;
            }
            attempts++;
        }
    }
    
    // Fill empty cells with random letters
    for (let r = 0; r < size; r++) {
        for (let c = 0; c < size; c++) {
            if (gameState.grid[r][c] === '') {
                gameState.grid[r][c] = String.fromCharCode(65 + Math.floor(Math.random() * 26));
            }
        }
    }
}

function canPlaceWord(word, startRow, startCol, direction) {
    const size = gameState.gridSize;
    
    for (let i = 0; i < word.length; i++) {
        const row = startRow + i * direction.dr;
        const col = startCol + i * direction.dc;
        
        // Check bounds
        if (row < 0 || row >= size || col < 0 || col >= size) {
            return false;
        }
        
        // Check if cell is empty or has the same letter
        if (gameState.grid[row][col] !== '' && gameState.grid[row][col] !== word[i]) {
            return false;
        }
    }
    
    return true;
}

function placeWord(word, startRow, startCol, direction) {
    const positions = [];
    
    for (let i = 0; i < word.length; i++) {
        const row = startRow + i * direction.dr;
        const col = startCol + i * direction.dc;
        gameState.grid[row][col] = word[i];
        positions.push({ row, col });
    }
    
    gameState.wordPositions.push({ word, positions });
}

function renderGrid() {
    elements.gridContainer.innerHTML = '';
    elements.gridContainer.style.gridTemplateColumns = `repeat(${gameState.gridSize}, 1fr)`;
    
    // Adjust font size based on grid size
    const isSmall = gameState.gridSize > 12;
    
    for (let r = 0; r < gameState.gridSize; r++) {
        for (let c = 0; c < gameState.gridSize; c++) {
            const cell = document.createElement('div');
            cell.className = 'grid-cell';
            if (isSmall) cell.classList.add('small-text');
            
            cell.textContent = gameState.grid[r][c];
            cell.dataset.row = r;
            cell.dataset.col = c;
            
            // Add event listeners for selection
            cell.addEventListener('mousedown', handleCellMouseDown);
            cell.addEventListener('mouseenter', handleCellMouseEnter);
            cell.addEventListener('mouseup', handleCellMouseUp);
            cell.addEventListener('touchstart', handleCellTouchStart);
            cell.addEventListener('touchmove', handleCellTouchMove);
            cell.addEventListener('touchend', handleCellTouchEnd);
            
            elements.gridContainer.appendChild(cell);
        }
    }
    
    // Re-highlight found words
    gameState.foundWords.forEach(word => {
        const wordData = gameState.wordPositions.find(wp => wp.word === word);
        if (wordData) {
            wordData.positions.forEach(({row, col}) => {
                const cell = document.querySelector(`.grid-cell[data-row="${row}"][data-col="${col}"]`);
                if (cell) cell.classList.add('found');
            });
        }
    });
}

function renderWordList() {
    elements.wordList.innerHTML = '';
    
    for (const word of gameState.hiddenWords) {
        const wordItem = document.createElement('div');
        wordItem.className = 'word-item';
        wordItem.textContent = word;
        
        if (gameState.foundWords.includes(word)) {
            wordItem.classList.add('found');
        }
        
        elements.wordList.appendChild(wordItem);
    }
}

function updateUI() {
    if (elements.levelDisplay) elements.levelDisplay.textContent = gameState.currentLevel;
    if (elements.timerDisplay) elements.timerDisplay.textContent = formatTime(gameState.timeRemaining);
    if (elements.wordsDisplay) elements.wordsDisplay.textContent = `${gameState.foundWords.length}/${gameState.hiddenWords.length}`;
    if (elements.scoreDisplay) elements.scoreDisplay.textContent = gameState.totalScore;
    
    renderGrid();
    renderWordList();
}

function formatTime(seconds) {
    const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
    const secs = (seconds % 60).toString().padStart(2, '0');
    return `${mins}:${secs}`;
}

// ========================
// WORD SELECTION LOGIC
// ========================

function handleCellMouseDown(e) {
    if (!gameState.isPlaying) return;
    gameState.selecting = true;
    const row = parseInt(e.target.dataset.row);
    const col = parseInt(e.target.dataset.col);
    gameState.startCell = { row, col };
    gameState.selectedCells = [gameState.startCell];
    updateCellSelection();
}

function handleCellMouseEnter(e) {
    if (!gameState.selecting) return;
    const row = parseInt(e.target.dataset.row);
    const col = parseInt(e.target.dataset.col);
    const currentCell = { row, col };
    
    gameState.selectedCells = getCellsAlongLine(gameState.startCell, currentCell);
    updateCellSelection();
}

function handleCellMouseUp(e) {
    if (!gameState.selecting) return;
    gameState.selecting = false;
    gameState.startCell = null;
    checkSelectedWord();
}

function handleCellTouchStart(e) {
    e.preventDefault();
    if (!gameState.isPlaying) return;
    const touch = e.touches[0];
    const element = document.elementFromPoint(touch.clientX, touch.clientY);
    if (element && element.classList.contains('grid-cell')) {
        gameState.selecting = true;
        const row = parseInt(element.dataset.row);
        const col = parseInt(element.dataset.col);
        gameState.startCell = { row, col };
        gameState.selectedCells = [gameState.startCell];
        updateCellSelection();
    }
}

function handleCellTouchMove(e) {
    e.preventDefault();
    if (!gameState.selecting) return;
    const touch = e.touches[0];
    const element = document.elementFromPoint(touch.clientX, touch.clientY);
    if (element && element.classList.contains('grid-cell')) {
        const row = parseInt(element.dataset.row);
        const col = parseInt(element.dataset.col);
        const currentCell = { row, col };
        
        gameState.selectedCells = getCellsAlongLine(gameState.startCell, currentCell);
        updateCellSelection();
    }
}

function handleCellTouchEnd(e) {
    e.preventDefault();
    if (!gameState.selecting) return;
    gameState.selecting = false;
    gameState.startCell = null;
    checkSelectedWord();
}

function getCellsAlongLine(start, end) {
    const cells = [];
    const dr = end.row - start.row;
    const dc = end.col - start.col;

    // Check if horizontal, vertical, or diagonal
    if (dr === 0 || dc === 0 || Math.abs(dr) === Math.abs(dc)) {
        const steps = Math.max(Math.abs(dr), Math.abs(dc));
        const stepR = dr === 0 ? 0 : dr / Math.abs(dr); // 1, -1, or 0
        const stepC = dc === 0 ? 0 : dc / Math.abs(dc); // 1, -1, or 0

        for (let i = 0; i <= steps; i++) {
            cells.push({
                row: start.row + (stepR * i),
                col: start.col + (stepC * i)
            });
        }
    } else {
        // If not a straight line, just return start cell to indicate invalid path
        cells.push(start);
    }
    return cells;
}

function updateCellSelection() {
    // Clear previous selection styling
    document.querySelectorAll('.grid-cell').forEach(cell => {
        cell.classList.remove('selecting');
    });


    // Add selection styling to selected cells
    for (const {row, col} of gameState.selectedCells) {
        const cell = document.querySelector(`.grid-cell[data-row="${row}"][data-col="${col}"]`);
        if (cell && !cell.classList.contains('found')) {
            cell.classList.add('selecting');
        }
    }
}

function checkSelectedWord() {
    if (gameState.selectedCells.length === 0) return;
    
    // Extract word from selected cells
    const selectedWord = gameState.selectedCells.map(({row, col}) => gameState.grid[row][col]).join('');
    
    // Check if it matches any hidden word (forward or backward)
    const reversed = selectedWord.split('').reverse().join('');
    
    if (gameState.hiddenWords.includes(selectedWord) && !gameState.foundWords.includes(selectedWord)) {
        markWordAsFound(selectedWord, gameState.selectedCells);
    } else if (gameState.hiddenWords.includes(reversed) && !gameState.foundWords.includes(reversed)) {
        markWordAsFound(reversed, gameState.selectedCells);
    }
    
    // Clear selection
    gameState.selectedCells = [];
    updateCellSelection();
}

function markWordAsFound(word, cells) {
    gameState.foundWords.push(word);
    
    // Mark cells as found
    for (const {row, col} of cells) {
        const cell = document.querySelector(`.grid-cell[data-row="${row}"][data-col="${col}"]`);
        if (cell) {
            cell.classList.remove('selecting');
            cell.classList.add('found');
        }
    }
    
    // Update UI
    updateUI();
    
    // Check if level is complete
    if (gameState.foundWords.length === gameState.hiddenWords.length) {
        levelComplete();
    } else {
        saveGameState();
    }
}

// ========================
// TIMER
// ========================

function startTimer() {
    if (gameState.timer) {
        clearInterval(gameState.timer);
    }
    
    gameState.timer = setInterval(() => {
        gameState.timeRemaining--;
        if (elements.timerDisplay) elements.timerDisplay.textContent = formatTime(gameState.timeRemaining);
        
        if (gameState.timeRemaining <= 0) {
            clearInterval(gameState.timer);
            levelFailed();
        }
        
        saveGameState();
    }, 1000);
}

// ========================
// LEVEL COMPLETION
// ========================

function levelComplete() {
    gameState.isPlaying = false;
    clearInterval(gameState.timer);
    
    // Track game end with metrics
    if (typeof trackGameEnd === 'function' && gameStartTime) {
        const duration = Date.now() - gameStartTime;
        const timeBonus = gameState.timeRemaining * 10;
        trackGameEnd('letterquest', duration, {
            metrics: {
                level: gameState.currentLevel,
                score: gameState.totalScore,
                wordsFound: gameState.foundWords.length,
                totalWords: gameState.hiddenWords.length,
                timeBonus: timeBonus,
                result: 'complete'
            }
        });
    }
    
    // Calculate score
    const timeBonus = gameState.timeRemaining * 10;
    const levelScore = (gameState.foundWords.length * 100) + timeBonus;
    gameState.totalScore += levelScore;
    
    // Update Max Level and Unlocked Levels
    if (gameState.currentLevel >= gameProgress.maxLevel && gameState.currentLevel < 20) {
        gameProgress.maxLevel = gameState.currentLevel + 1;
        unlockNextLevel(gameState.currentLevel);
    }

    // Update High Score
    if (gameState.totalScore > gameProgress.highScore) {
        gameProgress.highScore = gameState.totalScore;
    }

    // Update Level Stats
    if (!gameProgress.stats[gameState.currentLevel]) {
        gameProgress.stats[gameState.currentLevel] = { completions: 0, failures: 0, bestTime: null, bestScore: 0 };
    }
    
    const stats = gameProgress.stats[gameState.currentLevel];
    stats.completions++;
    
    // Update Best Score
    if (levelScore > stats.bestScore) {
        stats.bestScore = levelScore;
    }
    
    // Update Best Time
    if (gameStartTime) {
        const elapsedSeconds = Math.floor((Date.now() - gameStartTime) / 1000);
        if (stats.bestTime === null || elapsedSeconds < stats.bestTime) {
            stats.bestTime = elapsedSeconds;
        }
    }
    
    saveProgress();
    
    // Update complete screen
    document.getElementById('lc-words-found').textContent = gameState.foundWords.length;
    document.getElementById('lc-time-bonus').textContent = timeBonus;
    document.getElementById('lc-level-score').textContent = levelScore;
    
    // Check if game is complete
    if (gameState.currentLevel === 20) {
        gameComplete();
    } else {
        showScreen('level-complete');
        clearGameState(); // Clear state when level completes
    }
}

function levelFailed() {
    gameState.isPlaying = false;
    
    // Track game end with metrics
    if (typeof trackGameEnd === 'function' && gameStartTime) {
        const duration = Date.now() - gameStartTime;
        trackGameEnd('letterquest', duration, {
            metrics: {
                level: gameState.currentLevel,
                score: gameState.totalScore,
                wordsFound: gameState.foundWords.length,
                totalWords: gameState.hiddenWords.length,
                result: 'failed'
            }
        });
        gameStartTime = null;
    }
    
    document.getElementById('lf-words-found').textContent = `${gameState.foundWords.length}/${gameState.hiddenWords.length}`;
    
    // Update High Score on failure
    if (gameState.totalScore > gameProgress.highScore) {
        gameProgress.highScore = gameState.totalScore;
    }

    // Update Level Stats
    if (!gameProgress.stats[gameState.currentLevel]) {
        gameProgress.stats[gameState.currentLevel] = { completions: 0, failures: 0, bestTime: null, bestScore: 0 };
    }
    gameProgress.stats[gameState.currentLevel].failures++;
    
    saveProgress();

    showScreen('level-failed');
    clearGameState();
}

function gameComplete() {
    gameState.isPlaying = false;
    
    // Update high score
    if (gameState.totalScore > gameProgress.highScore) {
        gameProgress.highScore = gameState.totalScore;
        saveProgress();
    }
    
    document.getElementById('gc-total-score').textContent = gameState.totalScore;
    document.getElementById('gc-high-score').textContent = gameProgress.highScore;
    
    showScreen('game-complete');
    clearGameState();
}

function nextLevel() {
    gameState.currentLevel++;
    startLevel(gameState.currentLevel);
}

function retryLevel() {
    startLevel(gameState.currentLevel);
}

function backToMenu() {
    clearInterval(gameState.timer);
    
    // Update High Score when quitting
    if (gameState.totalScore > gameProgress.highScore) {
        gameProgress.highScore = gameState.totalScore;
        saveProgress();
    }

    // Only save if game was active AND player has made some progress
    if (gameState.isPlaying) {
        // Check if player has found any words
        const hasFoundWords = gameState.foundWords && gameState.foundWords.length > 0;
        
        // Only save if player has found at least one word
        if (hasFoundWords) {
            const state = {
                ...gameState,
                gameStartTime: gameStartTime,
                timestamp: Date.now(),
                timer: null
            };
            localStorage.setItem('letterquest-state', JSON.stringify(state));
        } else {
            // No words found, clear any existing state
            clearGameState();
        }
    }

    gameState.isPlaying = false;
    showScreen('start');
    // Do NOT clear game state here, to allow grace period
}

function playAgain() {
    gameState.totalScore = 0;
    startLevel(1);
}

// ========================
// UI HELPERS
// ========================

function showScreen(screen) {
    elements.startScreen.classList.add('hidden');
    elements.levelCompleteScreen.classList.add('hidden');
    elements.levelFailedScreen.classList.add('hidden');
    elements.gameCompleteScreen.classList.add('hidden');
    
    const gameScreen = document.getElementById('game-screen');
    if (gameScreen) gameScreen.classList.add('hidden');
    
    // Also hide stats screen when switching screens
    if (elements.statsScreen) elements.statsScreen.classList.add('hidden');

    switch(screen) {
        case 'start':
            renderStartScreen();
            elements.startScreen.classList.remove('hidden');
            break;
        case 'game':
            if (gameScreen) {
                gameScreen.classList.remove('hidden');
                // Trigger layout recalculation
                if (window.gameLayout) {
                    requestAnimationFrame(() => {
                        requestAnimationFrame(() => {
                            window.gameLayout.performLayout();
                        });
                    });
                }
            }
            break;
        case 'level-complete':
            elements.levelCompleteScreen.classList.remove('hidden');
            break;
        case 'level-failed':
            elements.levelFailedScreen.classList.remove('hidden');
            break;
        case 'game-complete':
            elements.gameCompleteScreen.classList.remove('hidden');
            break;
    }
}

// ========================
// LEVEL LOCKING SYSTEM
// ========================

function isLevelUnlocked(level) {
    return gameProgress.unlockedLevels.includes(level);
}

function unlockNextLevel(currentLevel) {
    const nextLevel = currentLevel + 1;
    if (nextLevel <= 20 && !gameProgress.unlockedLevels.includes(nextLevel)) {
        gameProgress.unlockedLevels.push(nextLevel);
        saveProgress();
    }
}

function renderStartScreen() {
    // Update stats
    if (elements.maxLevelDisplay) elements.maxLevelDisplay.textContent = gameProgress.maxLevel;
    if (elements.highScoreDisplay) elements.highScoreDisplay.textContent = gameProgress.highScore;
    
    updateTotalStatsUI();
    
    // Generate Level Grid
    if (elements.levelGrid) {
        elements.levelGrid.innerHTML = '';
        for (let i = 1; i <= 20; i++) {
            const btn = document.createElement('button');
            btn.className = 'level-card';
            
            // Level Number
            const numDiv = document.createElement('div');
            numDiv.className = 'level-number';
            numDiv.textContent = i;
            btn.appendChild(numDiv);
            
            // Status Container
            const statusDiv = document.createElement('div');
            statusDiv.className = 'level-status';
            
            if (!isLevelUnlocked(i)) {
                btn.classList.add('locked');
                btn.disabled = true;
                
                const lockIcon = document.createElement('i');
                lockIcon.className = 'fas fa-lock lock-icon';
                statusDiv.appendChild(lockIcon);
            } else {
                btn.onclick = () => {
                    gameState.totalScore = 0;
                    startLevel(i);
                };
                
                // Check if completed
                if (i < gameProgress.maxLevel) {
                    btn.classList.add('completed');
                    
                    // Stars (just one for now to indicate completion)
                    const starsDiv = document.createElement('div');
                    starsDiv.className = 'level-stars';
                    starsDiv.innerHTML = '<i class="fas fa-star"></i>';
                    statusDiv.appendChild(starsDiv);
                    
                    // Best Score (if available)
                    if (gameProgress.stats[i] && gameProgress.stats[i].bestScore > 0) {
                        const scoreDiv = document.createElement('div');
                        scoreDiv.className = 'level-score';
                        scoreDiv.textContent = gameProgress.stats[i].bestScore;
                        statusDiv.appendChild(scoreDiv);
                    }
                } else if (i === gameProgress.maxLevel) {
                    btn.classList.add('current');
                    // Current level indicator or just empty status
                }
            }
            
            btn.appendChild(statusDiv);
            elements.levelGrid.appendChild(btn);
        }
    }
}

// ========================
// STATE PERSISTENCE
// ========================

function showStats() {
    console.log('showStats called');
    const statsTableBody = document.getElementById('stats-table-body');
    const statsScreen = document.getElementById('stats-screen');
    
    if (!statsTableBody || !statsScreen) {
        console.error('Stats elements not found:', { statsTableBody, statsScreen });
        return;
    }
    
    // Fetch fresh stats from API and display
    fetch('/api/sessions/game-stats/letterquest')
        .then(response => response.json())
        .then(data => {
            statsTableBody.innerHTML = '';
            
            // Use detailed stats from API if available, otherwise fall back to localStorage
            const statsToDisplay = data.detailedStats && Object.keys(data.detailedStats).length > 0 
                ? data.detailedStats 
                : gameProgress.stats;
            
            // Iterate through all 20 levels
            for (let level = 1; level <= 20; level++) {
                const stats = statsToDisplay[level];
                if (!stats) {
                    // No data for this level yet
                    continue;
                }
                
                const row = document.createElement('tr');
                const bestTime = stats.bestTime ? formatTime(stats.bestTime) : '-';
                const bestScore = stats.bestScore || '-';
                
                row.innerHTML = `
                    <td>${level}</td>
                    <td class="stat-highlight">${stats.completions || 0}</td>
                    <td>${stats.failures || 0}</td>
                    <td>${bestTime}</td>
                    <td>${bestScore}</td>
                `;
                statsTableBody.appendChild(row);
            }
            
            statsScreen.classList.remove('hidden');
        })
        .catch(error => {
            console.error('Error fetching stats:', error);
            // Fall back to localStorage stats
            displayLocalStats();
        });
}

function displayLocalStats() {
    const statsTableBody = document.getElementById('stats-table-body');
    const statsScreen = document.getElementById('stats-screen');
    
    if (!statsTableBody || !statsScreen) return;
    
    statsTableBody.innerHTML = '';
    
    // Use gameProgress.stats which is { level: { completions, failures, bestTime, bestScore } }
    for (let level = 1; level <= 20; level++) {
        if (!gameProgress.stats[level]) continue;
        
        const stats = gameProgress.stats[level];
        const row = document.createElement('tr');
        const bestTime = stats.bestTime ? formatTime(stats.bestTime) : '-';
        const bestScore = stats.bestScore || '-';
        
        row.innerHTML = `
            <td>${level}</td>
            <td class="stat-highlight">${stats.completions}</td>
            <td>${stats.failures}</td>
            <td>${bestTime}</td>
            <td>${bestScore}</td>
        `;
        statsTableBody.appendChild(row);
    }
    
    statsScreen.classList.remove('hidden');
}

function formatTime(seconds) {
    if (seconds === null) return '-';
    const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
    const secs = (seconds % 60).toString().padStart(2, '0');
    return `${mins}:${secs}`;
}

function saveGameState() {
    if (!gameState.isPlaying) return;

    try {
        const stateToSave = {
            ...gameState,
            gameStartTime: gameStartTime, // Save the start time
            timestamp: Date.now(),
            timer: null // Don't save the timer ID
        };
        localStorage.setItem('letterquest-state', JSON.stringify(stateToSave));
    } catch (e) {
        console.error('Failed to save game state:', e);
    }
}

function loadGameState() {
    const savedState = localStorage.getItem('letterquest-state');
    if (!savedState) return false;

    try {
        const parsedState = JSON.parse(savedState);
        
        // Grace period check (10 seconds)
        const GRACE_PERIOD_MS = 10000;
        const now = Date.now();
        const savedTime = parsedState.timestamp || 0;
        const timeDiff = now - savedTime;
        
        if (timeDiff > GRACE_PERIOD_MS) {
            console.log('Game state expired (grace period exceeded)');
            clearGameState();
            return false;
        }
        
        // Don't penalize time remaining for grace period
        // Just resume where we left off
        if (parsedState.timeRemaining <= 0) {
            clearGameState();
            return false;
        }

        // Restore gameStartTime
        // Adjust start time so that (now - gameStartTime) equals the actual duration played
        // effectively "pausing" the clock during the time away
        if (parsedState.gameStartTime) {
            gameStartTime = parsedState.gameStartTime + timeDiff;
        } else {
            // Fallback if missing
            gameStartTime = Date.now(); 
        }

        // Restore game state
        gameState = { ...gameState, ...parsedState };
        gameState.isPlaying = true;
        
        // Restore UI
        updateUI();
        showScreen('game');
        
        // Trigger layout recalculation
        if (window.gameLayout) {
            requestAnimationFrame(() => {
                requestAnimationFrame(() => {
                    window.gameLayout.performLayout();
                });
            });
        }
        
        startTimer();
        
        return true;
    } catch (e) {
        console.error('Failed to load game state', e);
        clearGameState();
        return false;
    }
}

function clearGameState() {
    localStorage.removeItem('letterquest-state');
}

function saveProgress() {
    try {
        localStorage.setItem('letterquest-progress', JSON.stringify(gameProgress));
    } catch (e) {
        console.error('Failed to save progress:', e);
    }
}

async function loadGameStats() {
    try {
        const response = await fetch('/api/sessions/game-stats/letterquest');
        if (response.ok) {
            const data = await response.json();
            
            // Update wins/losses display
            const totalWinsEl = document.getElementById('total-wins');
            const totalLossesEl = document.getElementById('total-losses');
            
            if (totalWinsEl) totalWinsEl.textContent = data.totalWins || 0;
            if (totalLossesEl) totalLossesEl.textContent = data.totalLosses || 0;
        }
    } catch (error) {
        console.error('Error loading game stats:', error);
    }
}

function loadProgress() {
    const saved = localStorage.getItem('letterquest-progress');
    if (saved) {
        try {
            const parsed = JSON.parse(saved);
            gameProgress = { ...gameProgress, ...parsed };
            
            // Ensure stats object exists
            if (!gameProgress.stats) {
                gameProgress.stats = {};
            }
            
            // Initialize stats for known levels if missing
            Object.keys(LEVEL_CONFIG).forEach(level => {
                if (!gameProgress.stats[level]) {
                    gameProgress.stats[level] = {
                        completions: 0,
                        failures: 0,
                        bestTime: null,
                        bestScore: 0
                    };
                }
            });
            
            // Ensure unlockedLevels exists and is an array
            if (!Array.isArray(gameProgress.unlockedLevels)) {
                gameProgress.unlockedLevels = [];
                // Migration: unlock up to maxLevel
                const max = gameProgress.maxLevel || 1;
                for (let i = 1; i <= max; i++) {
                    gameProgress.unlockedLevels.push(i);
                }
            }
        } catch (e) {
            console.error('Failed to load progress', e);
            // Reset to default if corrupted
            gameProgress = {
                maxLevel: 1,
                highScore: 0,
                unlockedLevels: [1],
                stats: {}
            };
        }
    }

    // Update UI
    if (elements.maxLevelDisplay) elements.maxLevelDisplay.textContent = gameProgress.maxLevel;
    if (elements.highScoreDisplay) elements.highScoreDisplay.textContent = gameProgress.highScore;
    
    // Update Total Stats on Start Screen
    updateTotalStatsUI();
}

function updateTotalStatsUI() {
    if (!gameProgress.stats) return;
    
    const totalWins = Object.values(gameProgress.stats).reduce((acc, curr) => acc + (curr.completions || 0), 0);
    const totalLosses = Object.values(gameProgress.stats).reduce((acc, curr) => acc + (curr.failures || 0), 0);
    
    const winsDisplay = document.getElementById('total-wins');
    const lossesDisplay = document.getElementById('total-losses');
    
    if (winsDisplay) winsDisplay.textContent = totalWins;
    if (lossesDisplay) lossesDisplay.textContent = totalLosses;
}

// ========================
// GRACE PERIOD SYSTEM
// ========================

let gracePeriodInterval = null;

function startGracePeriodChecker() {
    if (gracePeriodInterval) clearInterval(gracePeriodInterval);
    gracePeriodInterval = setInterval(checkGracePeriod, 1000);
    checkGracePeriod();
}

function checkGracePeriod() {
    // If game is active in current session, don't show notification
    if (gameState.isPlaying && !document.hidden) {
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }

    const activeGame = localStorage.getItem('letterquest-state');
    if (!activeGame) {
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }

    try {
        const savedState = JSON.parse(activeGame);
        const GRACE_PERIOD_MS = 10000;
        const now = Date.now();
        const savedTime = savedState.timestamp || 0;
        const timeDiff = now - savedTime;
        const remainingTime = Math.ceil((GRACE_PERIOD_MS - timeDiff) / 1000);

        // If expired
        if (remainingTime <= 0) {
            localStorage.removeItem('letterquest-state');
            const notification = document.querySelector('.grace-period-notification');
            if (notification) notification.remove();
            return;
        }

        // If we are in the menu (game not active in memory) OR page is hidden
        // But we have an active game in storage that is valid
        if (!gameState.isPlaying || document.hidden) {
            showGracePeriodNotification(remainingTime, savedState.currentLevel);
        }
    } catch (e) {
        console.error('Error checking grace period:', e);
    }
}

function showGracePeriodNotification(remainingTime, level) {
    let notification = document.querySelector('.grace-period-notification');
    const GRACE_PERIOD_MS = 10000;
    const progressPercent = (remainingTime / (GRACE_PERIOD_MS / 1000)) * 100;
    
    if (!notification) {
        notification = document.createElement('div');
        notification.className = 'game-notification grace-period-notification show';
        notification.innerHTML = `
            <div class="notification-icon"><i class="fas fa-clock"></i></div>
            <div class="notification-content">
                <div class="notification-title">Game Session Active</div>
                <div class="notification-message">Resuming Level ${level}...</div>
            </div>
            <div class="notification-timer">${remainingTime}s</div>
            <div class="notification-progress-bar" style="width: ${progressPercent}%"></div>
        `;
        
        notification.addEventListener('click', () => {
            // Resume game by loading state
            if (loadGameState()) {
                notification.remove();
                // Clear the grace period interval since game is now active
                // Actually, we should keep it running to handle future pauses, 
                // but checkGracePeriod handles the isPlaying check.
            }
        });
        
        document.body.appendChild(notification);
    } else {
        // Update existing notification
        const timer = notification.querySelector('.notification-timer');
        if (timer) timer.textContent = `${remainingTime}s`;
        
        const progressBar = notification.querySelector('.notification-progress-bar');
        if (progressBar) progressBar.style.width = `${progressPercent}%`;
    }
}

// Initialize Responsive Layout Module
let gameLayout = null;
if (window.ResponsiveGameLayout) {
    gameLayout = new ResponsiveGameLayout({
        gameScreenId: 'game-screen',
        topBarSelector: '.game-top-bar',
        bottomBarSelector: '.control-panel',
        boardWrapperSelector: '.game-board-wrapper',
        boardId: 'letter-grid',
        hasTopLeftBar: true,
        hasBottomRightBar: true,
        boardSizeMode: 'square',
        gap: 24
    });
    window.gameLayout = gameLayout;
}

// Initialize
loadProgress();
loadGameStats(); // Load stats from API

// Try to resume game or show start screen FIRST
// This prevents the notification from briefly appearing when auto-resuming
if (!loadGameState()) {
    showScreen('start');
}

// Back to Portal button
const backToPortalBtn = document.getElementById('back-to-portal-btn');
if (backToPortalBtn) {
    backToPortalBtn.addEventListener('click', () => {
        window.location.href = '/';
    });
}

// Start grace period checker AFTER attempting to load game
// If game was loaded, this won't show notification since isPlaying = true
startGracePeriodChecker();

// Save state when page is hidden/closed
document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
        saveGameState();
    }
});
window.addEventListener('beforeunload', () => {
    saveGameState();
});
