import React, { useState, useEffect, useCallback, useRef } from 'react';
import ReactDOM from 'react-dom/client';

// =================================================================================
// TYPES
// =================================================================================
interface GameLevel {
  id: number;
  image: string;
  answer: string;
  question: string;
  info?: string;
  letters: string[];
}

interface KeyboardLetter {
  letter: string;
  id: number;
  used: boolean;
}

interface GuessSlot {
  letter: string;
  keyboardId: number;
}

interface SavedGameState {
  levelId: number;
  guess: (GuessSlot | null)[];
  keyboardLetters: KeyboardLetter[];
  revealUsed: boolean;
  removedTiles: number[];
}

interface PlayerStats {
  completedLevelIds: number[];
  totalLettersRevealed: number;
  achievements: string[];
  totalPlayTimeSeconds: number;
  achievementUnlockTimes: { [key: string]: number };
  hasUnlockedFullGame: boolean;
}

interface Achievement {
  id: string;
  name: string;
  description: string;
  check: (stats: PlayerStats) => boolean;
  icon: string;
}

// =================================================================================
// CONSTANTS
// =================================================================================
const definedLevels: Omit<GameLevel, 'id'>[] = [
    { answer: 'الكعبة', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/1.png', letters: ['ك', 'ع', 'ا', 'ل', 'ة', 'ب', 'د', 'ر', 'س', 'ش', 'ص', 'ض'] },
    { answer: 'روضة طاهرة', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/2.png', letters: ['ر', 'و', 'ض', 'ة', 'ط', 'ا', 'ه', 'ر', 'ة', 'ك', 'ل', 'م'] },
    { answer: 'المعظم', question: 'كئي مسجد؟', image: 'https://zahabapps.store/games/maqamaat_img/3.png', letters: ['ا', 'ل', 'م', 'ع', 'ظ', 'م', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ'] },
    { answer: 'غرة المساجد', question: 'كئي مسجد؟', image: 'https://zahabapps.store/games/maqamaat_img/4.png', letters: ['غ', 'ر', 'ة', 'ا', 'ل', 'م', 'س', 'ا', 'ج', 'د', 'ف', 'ق', 'ك', 'ن', 'ه'] },
    { answer: 'حطيب مبارك', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/5.png', letters: ['ح', 'ط', 'ي', 'ب', 'م', 'ب', 'ا', 'ر', 'ك', 'س', 'ش', 'ص'] },
    { answer: 'جامنگر', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/6.png', letters: ['ج', 'ا', 'م', 'ن', 'گ', 'ر', 'د', 'ذ', 'ز', 'س', 'ش', 'ص'] },
    { answer: 'برهانپور', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/7.png', letters: ['ب', 'ر', 'ه', 'ا', 'ن', 'پ', 'و', 'ر', 'س', 'ش', 'ص', 'ض'] },
    { answer: 'اجين', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/8.png', letters: ['ا', 'ج', 'ي', 'ن', 'ق', 'ب', 'ت', 'ث', 'ح', 'خ', 'د', 'م'] },
    { answer: 'أنور', question: 'كئي جامع؟', image: 'https://zahabapps.store/games/maqamaat_img/9.png', letters: ['أ', 'ن', 'و', 'ر', 'د', 'ذ', 'ز', 'س', 'ش', 'ص', 'ض', 'ط'] },
    { answer: 'گلياكوت', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/10.png', letters: ['گ', 'ل', 'ي', 'ا', 'ك', 'و', 'ت', 'ب', 'ث', 'ج', 'ح', 'خ'] },
    { answer: 'أحمدآباد', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/11.png', letters: ['أ', 'ح', 'م', 'د', 'آ', 'ب', 'ا', 'د', 'ر', 'ز', 'س', 'ش'] },
    { answer: 'أقمر', question: 'كئي جامع؟', image: 'https://zahabapps.store/games/maqamaat_img/12.png', letters: ['أ', 'ق', 'م', 'ر', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ'] },
    { answer: 'ماندوي', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/13.png', letters: ['م', 'ا', 'ن', 'د', 'و', 'ي', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ'] },
    { answer: 'سورت', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/14.png', letters: ['س', 'و', 'ر', 'ت', 'ج', 'ح', 'خ', 'د', 'ذ', 'ز', 'ش', 'ص'] },
    { answer: 'شبام', question: 'كئي جگه؟', info: 'Syedna Idris Imaduddin RA', image: 'https://zahabapps.store/games/maqamaat_img/15.png', letters: ['ش', 'ب', 'ا', 'م', 'د', 'ذ', 'ر', 'ز', 'س', 'ص', 'ض', 'ط'] },
    { answer: 'شارقة', question: 'كئي جگه؟', info: 'Syedna Ali Shamsuddin RA', image: 'https://zahabapps.store/games/maqamaat_img/16.png', letters: ['ش', 'ا', 'ر', 'ق', 'ة', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د'] },
    { answer: 'أزهر', question: 'كئي جامع؟', image: 'https://zahabapps.store/games/maqamaat_img/17.png', letters: ['أ', 'ز', 'ه', 'ر', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ'] },
    { answer: 'برودا', question: 'كئي جگه؟', info: 'Syedi Moosanji Bin Taj QR', image: 'https://zahabapps.store/games/maqamaat_img/18.png', letters: ['ب', 'ر', 'و', 'د', 'ا', 'ج', 'ح', 'خ', 'ذ', 'ز', 'س', 'ش'] },
    { answer: 'سورت', question: 'كئي جگه؟', info: 'Mulla Waheb bs QR', image: 'https://zahabapps.store/games/maqamaat_img/19.png', letters: ['س', 'و', 'ر', 'ت', 'ا', 'ب', 'ج', 'ح', 'د', 'ذ', 'ز', 'ش'] },
    { answer: 'كهمبات', question: 'كئي جگه؟', info: 'Moulai Abdullah Saheb(QS)', image: 'https://zahabapps.store/games/maqamaat_img/20.png', letters: ['ك', 'ه', 'م', 'ب', 'ا', 'ت', 'د', 'ذ', 'ر', 'ز', 'س', 'ش'] },
    { answer: 'موربي', question: 'كئي جگه؟', info: 'Mawalaya Raj QR', image: 'https://zahabapps.store/games/maqamaat_img/21.png', letters: ['م', 'و', 'ر', 'ب', 'ي', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ'] },
    { answer: 'ذي جبلة', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/22.png', letters: ['ذ', 'ي', 'ج', 'ب', 'ل', 'ة', 'ح', 'خ', 'د', 'ر', 'ز', 'س'] },
    { answer: 'DONGAON', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/23.png', letters: ['D', 'O', 'N', 'G', 'A', 'O', 'N', 'B', 'C', 'E', 'F', 'H'] },
    { answer: 'جيوشي', question: 'كئي جامع؟', image: 'https://zahabapps.store/games/maqamaat_img/24.png', letters: ['ج', 'ي', 'و', 'ش', 'ي', 'ا', 'ب', 'ت', 'ث', 'ح', 'خ', 'د'] },
    { answer: 'دينمال', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/25.png', letters: ['د', 'ي', 'ن', 'م', 'ا', 'ل', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص'] },
    { answer: 'سيدهپور', question: 'كئي جگه؟', info: 'Syedi Qazi Khan Saheb(QS)', image: 'https://zahabapps.store/games/maqamaat_img/26.png', letters: ['س', 'ي', 'د', 'ه', 'پ', 'و', 'ر', 'ذ', 'ز', 'ش', 'ص', 'ض'] },
    { answer: 'لؤلؤة', question: 'كئي جامع؟', image: 'https://zahabapps.store/games/maqamaat_img/27.png', letters: ['ل', 'ؤ', 'ل', 'ؤ', 'ة', 'ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ'] },
    { answer: 'طيبة', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/28.png', letters: ['ط', 'ي', 'ب', 'ة', 'ا', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ'] },
    { answer: 'زبيد', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/29.png', letters: ['ز', 'ب', 'ي', 'د', 'ا', 'ت', 'ث', 'ج', 'ح', 'خ', 'ذ', 'ر'] },
    { answer: 'كراچي', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/30.png', letters: ['ك', 'ر', 'ا', 'چ', 'ي', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د'] },
    { answer: 'نيروبي', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/31.png', letters: ['ن', 'ي', 'ر', 'و', 'ب', 'ي', 'ت', 'ث', 'ج', 'ح', 'خ', 'د'] },
    { answer: 'MAISAHEBA', question: 'كئي جگه؟', info: 'Noor Biwi Saheba(QS), Fatema Biwi Saheba(QS)', image: 'https://zahabapps.store/games/maqamaat_img/32.png', letters: ['M', 'A', 'I', 'S', 'H', 'E', 'B', 'A', 'D', 'F', 'G', 'K'] },
    { answer: 'نجف', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/33.png', letters: ['ن', 'ج', 'ف', 'ا', 'ب', 'ت', 'ث', 'ح', 'خ', 'د', 'ذ', 'ر'] },
    { answer: 'المدينة', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/34.png', letters: ['ا', 'ل', 'م', 'د', 'ي', 'ن', 'ة', 'ر', 'ز', 'س', 'ش', 'ص'] },
    { answer: 'اجين', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/35.png', letters: ['ا', 'ج', 'ي', 'ن', 'ف', 'ت', 'ث', 'ح', 'خ', 'د', 'ذ', 'م'] },
    { answer: 'كربلاء', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/36.png', letters: ['ك', 'ر', 'ب', 'ل', 'ا', 'ء', 'د', 'ذ', 'ز', 'س', 'ش', 'ص'] },
    { answer: 'رامپورا', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/37.png', letters: ['ر', 'ا', 'م', 'پ', 'و', 'ر', 'ا', 'ب', 'ت', 'ث', 'ج', 'ح'] },
    { answer: 'GODHRA', question: 'كئي جگه؟', info: 'Syedi Ismailji Shaheed Saheb (QR)', image: 'https://zahabapps.store/games/maqamaat_img/38.png', letters: ['G', 'O', 'D', 'H', 'R', 'A', 'B', 'C', 'E', 'F', 'I', 'J'] },
    { answer: 'BANSWARA', question: 'كئي جگه؟', info: 'Moulaya Abdul Rasul Shaheed Saheb(QS)', image: 'https://zahabapps.store/games/maqamaat_img/39.png', letters: ['B', 'A', 'N', 'S', 'W', 'A', 'R', 'A', 'C', 'D', 'E', 'F'] },
    { answer: 'AHMEDNAGAR', question: 'كئي جگه؟', info: 'Ganje Shohoda (QS)', image: 'https://zahabapps.store/games/maqamaat_img/40.png', letters: ['A', 'H', 'M', 'E', 'D', 'N', 'A', 'G', 'A', 'R', 'S', 'T'] },
    { answer: 'غيل بني حامد', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/41.png', letters: ['غ', 'ي', 'ل', 'ب', 'ن', 'ي', 'ح', 'ا', 'م', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط'] },
    { answer: 'كهف النعيم', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/42.png', letters: ['ك', 'ه', 'ف', 'ا', 'ل', 'ن', 'ع', 'ي', 'م', 'ب', 'ت', 'ث'] },
    { answer: 'LONDON', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/43.png', letters: ['L', 'O', 'N', 'D', 'O', 'N', 'A', 'B', 'C', 'E', 'F', 'G'] },
    { answer: 'الشام', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/44.png', letters: ['ا', 'ل', 'ش', 'ا', 'م', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د'] },
    { answer: 'الأردن', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/45.png', letters: ['ا', 'ل', 'أ', 'ر', 'د', 'ن', 'ذ', 'ز', 'س', 'ش', 'ص', 'ض'] },
    { answer: 'ذي جبلة', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/46.png', letters: ['ذ', 'ي', 'ج', 'ب', 'ل', 'ة', 'ت', 'ث', 'ح', 'خ', 'د', 'ر'] },
    { answer: 'ذي مرمر', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/47.png', letters: ['ذ', 'ي', 'م', 'ر', 'م', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط'] },
    { answer: 'PAKHTI', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/48.png', letters: ['P', 'A', 'K', 'H', 'T', 'I', 'B', 'C', 'D', 'E', 'F', 'G'] },
    { answer: 'رأس الحسين', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/49.png', letters: ['ر', 'أ', 'س', 'ا', 'ل', 'ح', 'س', 'ي', 'ن', 'ش', 'ص', 'ض'] },
    { answer: 'مالك الأشتر', question: 'كوني زيارة؟', image: 'https://zahabapps.store/games/maqamaat_img/50.png', letters: ['م', 'ا', 'ل', 'ك', 'ا', 'ل', 'أ', 'ش', 'ت', 'ر', 'ب', 'ث', 'ج', 'ح', 'خ', 'د', 'ز', 'ز'] },
    { answer: 'نفيسة', question: 'كوني زيارة؟', image: 'https://zahabapps.store/games/maqamaat_img/51.png', letters: ['ن', 'ف', 'ي', 'س', 'ة', 'ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ'] },
    { answer: 'مخلفات', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/52.png', letters: ['م', 'خ', 'ل', 'ف', 'ا', 'ت', 'ر', 'ب', 'ث', 'ج', 'ح', 'د'] },
    { answer: 'رقية', question: 'كوني زيارة؟', image: 'https://zahabapps.store/games/maqamaat_img/53.png', letters: ['ر', 'ق', 'ي', 'ة', 'د', 'ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ'] },
    { answer: 'زينب', question: 'كوني زيارة؟', image: 'https://zahabapps.store/games/maqamaat_img/54.png', letters: ['ز', 'ي', 'ن', 'ب', 'ا', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ'] },
    { answer: 'باب النصر', question: 'باب نو نام؟', image: 'https://zahabapps.store/games/maqamaat_img/55.png', letters: ['ب', 'ا', 'ب', 'ا', 'ل', 'ن', 'ص', 'ر', 'ض', 'ط', 'ظ', 'ع'] },
    { answer: 'باب الفتوح', question: 'باب نو نام؟', image: 'https://zahabapps.store/games/maqamaat_img/56.png', letters: ['ب', 'ا', 'ب', 'ا', 'ل', 'ف', 'ت', 'و', 'ح', 'خ', 'د', 'ز'] },
    { answer: 'ابن طولون', question: 'كئي جامع؟', image: 'https://zahabapps.store/games/maqamaat_img/57.png', letters: ['ا', 'ب', 'ن', 'ط', 'و', 'ل', 'و', 'ن', 'م', 'ه', 'ي', 'ك'] },
    { answer: 'امير الجامعة', question: 'كوني زيارة؟', image: 'https://zahabapps.store/games/maqamaat_img/58.png', letters: ['ا', 'م', 'ي', 'ر', 'ا', 'ل', 'ج', 'ا', 'م', 'ع', 'ة', 'ف'] },
    { answer: 'مرول', question: 'كئي جگه؟', image: 'https://zahabapps.store/games/maqamaat_img/59.png', letters: ['م', 'ر', 'و', 'ل', 'ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د'] },
    { answer: 'أحمدآباد', question: 'كئي جگه؟', info: 'Maulaya Adam QS', image: 'https://zahabapps.store/games/maqamaat_img/60.png', letters: ['أ', 'ح', 'م', 'د', 'آ', 'ب', 'ا', 'د', 'ر', 'ز', 'س', 'ش'] },
    { answer: 'WAKANER', question: 'كئي جگه؟', info: 'Moulai Looqmanji Saheb (QS)', image: 'https://zahabapps.store/games/maqamaat_img/61.png', letters: ['W', 'A', 'K', 'A', 'N', 'E', 'R', 'B', 'C', 'D', 'F', 'G'] },
    { answer: 'AMRELI', question: 'كئي جگه؟', info: 'Syedi Jafferjee Jivaji Saheb (QS)', image: 'https://zahabapps.store/games/maqamaat_img/62.png', letters: ['A', 'M', 'R', 'E', 'L', 'I', 'B', 'C', 'D', 'F', 'G', 'H'] },
    { answer: 'KALAVAD', question: 'كئي جگه؟', info: 'Moulai Ganipeer', image: 'https://zahabapps.store/games/maqamaat_img/63.png', letters: ['K', 'A', 'L', 'A', 'V', 'A', 'D', 'B', 'C', 'E', 'F', 'G'] },
    { answer: 'KAMLAPUR', question: 'كئي جگه؟', info: 'Syedi Aliji Shaheed (QS.)', image: 'https://zahabapps.store/games/maqamaat_img/64.png', letters: ['K', 'A', 'M', 'L', 'A', 'P', 'U', 'R', 'B', 'C', 'D', 'E'] },
    { answer: 'UMRETH', question: 'كئي جگه؟', info: 'Syedi Miyaji Bin Taj Saheb (Q.R.)', image: 'https://zahabapps.store/games/maqamaat_img/65.png', letters: ['U', 'M', 'R', 'E', 'T', 'H', 'A', 'B', 'C', 'D', 'F', 'G'] },
    { answer: 'SHAJAPUR', question: 'كئي جگه؟', info: 'Syedi Yusufkhan Saheb (QS)', image: 'https://zahabapps.store/games/maqamaat_img/66.png', letters: ['S', 'H', 'A', 'J', 'A', 'P', 'U', 'R', 'B', 'C', 'D', 'E'] },
    { answer: 'RANPUR', question: 'كئي جگه؟', info: 'Moulai Sheikhpeer Saheb (QS)', image: 'https://zahabapps.store/games/maqamaat_img/67.png', letters: ['R', 'A', 'N', 'P', 'U', 'R', 'B', 'C', 'D', 'E', 'F', 'G'] },
    { answer: 'SELAVI', question: 'كئي جگه؟', info: 'Mullah Nooh bhaisaheb (QS)', image: 'https://zahabapps.store/games/maqamaat_img/68.png', letters: ['S', 'E', 'L', 'A', 'V', 'I', 'B', 'C', 'D', 'F', 'G', 'H'] },
    { answer: 'PISAWADA', question: 'كئي جگه؟', info: 'Maulai Burhanuddin Saheb (QS)', image: 'https://zahabapps.store/games/maqamaat_img/69.png', letters: ['P', 'I', 'S', 'A', 'W', 'A', 'D', 'A', 'B', 'C', 'E', 'F'] },
    { answer: 'AURANGABAD', question: 'كئي جگه؟', info: 'Maulai Najam Khan RA', image: 'https://zahabapps.store/games/maqamaat_img/70.png', letters: ['A', 'U', 'R', 'A', 'N', 'G', 'A', 'B', 'A', 'D', 'E', 'F'] },
    { answer: 'PRATAPGARH', question: 'كئي جگه؟', info: 'Kakaji Saheb Mulla Eesa bhaisaheb(QS)', image: 'https://zahabapps.store/games/maqamaat_img/71.png', letters: ['P', 'R', 'A', 'T', 'A', 'P', 'G', 'A', 'R', 'H', 'C', 'D'] },
    { answer: 'MUNDRA', question: 'كئي جگه؟', info: 'SYEDA RAANI BEN SAHEBA BINTE SYEDNA ISMAIL BADRUDDIN (38TH DAI)', image: 'https://zahabapps.store/games/maqamaat_img/72.png', letters: ['M', 'U', 'N', 'D', 'R', 'A', 'B', 'C', 'E', 'F', 'G', 'H'] },
    { answer: 'DHROL', question: 'كئي جگه؟', info: 'Ganje Shohada QR', image: 'https://zahabapps.store/games/maqamaat_img/73.png', letters: ['D', 'H', 'R', 'O', 'L', 'A', 'B', 'C', 'E', 'F', 'G', 'I'] },
    { answer: 'GAZA', question: 'كئي جگه؟', info: 'Moulana Hashim SA', image: 'https://zahabapps.store/games/maqamaat_img/74.png', letters: ['G', 'A', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J'] },
    { answer: 'KUFA', question: 'كئي جگه؟', info: 'Muslim Bin Aqeel RA', image: 'https://zahabapps.store/games/maqamaat_img/75.png', letters: ['K', 'U', 'F', 'A', 'B', 'C', 'D', 'E', 'G', 'H', 'I', 'J'] },
    { answer: 'KUFA', question: 'كئي جگه؟', info: 'Hani Bin Urwa RA', image: 'https://zahabapps.store/games/maqamaat_img/76.png', letters: ['K', 'U', 'F', 'A', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S'] },
    { answer: 'KUFA', question: 'كئي جگه؟', info: 'Maytham al-tammar', image: 'https://zahabapps.store/games/maqamaat_img/77.png', letters: ['K', 'U', 'F', 'A', 'T', 'V', 'W', 'X', 'Y', 'Z', 'B', 'C'] },
];

const allLevels: GameLevel[] = definedLevels.map((level, index) => ({ 
    ...level, 
    id: index + 1,
}));

const TOTAL_LEVEL_COUNT = allLevels.length;
const LEVELS: GameLevel[] = allLevels;
const PAYWALL_LEVEL_ID = 15;

const ACHIEVEMENTS: Achievement[] = [
  { id: 'talib', name: 'Talib', description: 'Complete your first level.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= 1, icon: '👣' },
  { id: 'mujtahid', name: 'Mujtahid', description: 'Complete 5 levels.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= 5, icon: '📜' },
  { id: 'samajhnaar', name: 'Samajhnaar', description: 'Complete 15 levels.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= 15, icon: '💡' },
  { id: 'aalim', name: 'Aalim', description: 'Complete 25 levels.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= 25, icon: '📖' },
  { id: 'aarif', name: 'Aarif', description: 'Complete 53 levels.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= 53, icon: '✒️' },
  { id: 'mahir', name: 'Mahir', description: 'Complete 72 levels.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= 72, icon: '🧠' },
  { id: 'ustaad', name: 'Ustaad', description: 'Complete all levels.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= TOTAL_LEVEL_COUNT, icon: '🏆' },
];

// =================================================================================
// AUDIO
// =================================================================================
const audioContext = typeof window !== 'undefined' ? new (window.AudioContext || (window as any).webkitAudioContext)() : null;
type SoundType = 'click' | 'place' | 'remove' | 'incorrect' | 'correct' | 'hint' | 'achievement';

const playNote = (frequency: number, type: OscillatorType, duration: number, volume: number = 0.2) => {
    if (!audioContext) return;
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    oscillator.type = type;
    oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
    gainNode.gain.setValueAtTime(volume, audioContext.currentTime);

    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + duration);
}

const sounds: { [key in SoundType]: () => void } = {
  click: () => playNote(440, 'sine', 0.05, 0.2),
  place: () => playNote(660, 'sine', 0.05, 0.2),
  remove: () => playNote(330, 'sine', 0.05, 0.2),
  hint: () => {
    if (!audioContext) return;
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    oscillator.type = 'sine';
    oscillator.frequency.setValueAtTime(880, audioContext.currentTime);
    gainNode.gain.setValueAtTime(0.2, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.0001, audioContext.currentTime + 0.2);

    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 0.2);
  },
  incorrect: () => {
    if (!audioContext) return;
    playNote(392.00, 'sine', 0.1, 0.25); // G4
    setTimeout(() => playNote(329.63, 'sine', 0.15, 0.25), 120); // E4
  },
  correct: () => {
    if (!audioContext) return;
    playNote(523.25, 'sine', 0.08, 0.3); // C5
    setTimeout(() => playNote(659.25, 'sine', 0.08, 0.3), 100); // E5
    setTimeout(() => playNote(783.99, 'sine', 0.08, 0.3), 200); // G5
    setTimeout(() => playNote(1046.50, 'triangle', 0.12, 0.3), 300); // C6 (sparkle)
  },
  achievement: () => {
    if (!audioContext) return;
    playNote(523.25, 'triangle', 0.1, 0.25); // C5
    setTimeout(() => playNote(783.99, 'triangle', 0.1, 0.25), 100); // G5
    setTimeout(() => playNote(1046.50, 'triangle', 0.2, 0.25), 200); // C6
  },
};

const playSound = (sound: SoundType) => {
  if (audioContext && audioContext.state === 'suspended') {
    audioContext.resume();
  }
  if (sounds[sound]) {
    sounds[sound]();
  }
};

// =================================================================================
// UTILS
// =================================================================================
const formatSecondsToTime = (totalSeconds: number): string => {
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    
    let timeString = "";
    if (hours > 0) timeString += `${hours}h `;
    if (minutes > 0 || hours > 0) timeString += `${minutes}m `;
    timeString += `${seconds}s`;
    
    return timeString.trim() || "0s";
};

const preloadImages = (urls: string[]): Promise<void[]> => {
  const promises = urls.map(src => {
    return new Promise<void>((resolve) => {
      const img = new Image();
      img.src = src;
      img.onload = () => resolve();
      img.onerror = () => resolve();
    });
  });
  return Promise.all(promises);
};

const shuffleArray = <T,>(array: T[]): T[] => {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
};

// =================================================================================
// HOOKS
// =================================================================================
const useFullScreen = () => {
  const [isFullScreen, setIsFullScreen] = useState(() => {
    if (typeof document === 'undefined') return false;
    return !!document.fullscreenElement;
  });

  const toggleFullScreen = useCallback(() => {
    if (typeof document === 'undefined') return;

    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen().catch((err) => {
        console.error(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
      });
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
  }, []);

  useEffect(() => {
    if (typeof document === 'undefined') return;
    const handleFullScreenChange = () => {
      setIsFullScreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullScreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullScreenChange);
    };
  }, []);

  return { isFullScreen, toggleFullScreen };
};

const usePlayerStats = () => {
  const [stats, setStats] = useState<PlayerStats>(() => {
    try {
      const savedStats = localStorage.getItem('maqamaat_playerStats');
      if (savedStats) {
        const parsed = JSON.parse(savedStats);
        return {
          completedLevelIds: [],
          totalLettersRevealed: 0,
          achievements: [],
          totalPlayTimeSeconds: 0,
          achievementUnlockTimes: {},
          hasUnlockedFullGame: false,
          ...parsed,
        };
      }
    } catch (error) {
      console.error('Error loading player stats:', error);
    }
    return {
      completedLevelIds: [],
      totalLettersRevealed: 0,
      achievements: [],
      totalPlayTimeSeconds: 0,
      achievementUnlockTimes: {},
      hasUnlockedFullGame: false,
    };
  });

  const [newlyUnlocked, setNewlyUnlocked] = useState<Achievement[]>([]);

  useEffect(() => {
    try {
      localStorage.setItem('maqamaat_playerStats', JSON.stringify(stats));
    } catch (error) {
      console.error('Error saving player stats:', error);
    }
  }, [stats]);
  
  const getNewAchievements = (currentStats: PlayerStats): Achievement[] => {
    const newAchievements: Achievement[] = [];
    ACHIEVEMENTS.forEach(achievement => {
        const isAlreadyUnlocked = currentStats.achievements.includes(achievement.id);
        if (!isAlreadyUnlocked && achievement.check(currentStats)) {
            newAchievements.push(achievement);
        }
    });
    return newAchievements;
  };

  const completeLevel = useCallback((levelId: number) => {
    setStats(prevStats => {
      if (prevStats.completedLevelIds.includes(levelId)) {
        return prevStats;
      }

      const intermediateStats = {
        ...prevStats,
        completedLevelIds: [...prevStats.completedLevelIds, levelId].sort((a, b) => a - b),
      };
      
      const newAchievements = getNewAchievements(intermediateStats);

      if (newAchievements.length > 0) {
        setNewlyUnlocked(newAchievements);
        const newAchievementUnlockTimes = { ...intermediateStats.achievementUnlockTimes };
        newAchievements.forEach(a => {
          newAchievementUnlockTimes[a.id] = intermediateStats.totalPlayTimeSeconds || 0;
        });

        return {
          ...intermediateStats,
          achievements: [...intermediateStats.achievements, ...newAchievements.map(a => a.id)],
          achievementUnlockTimes: newAchievementUnlockTimes,
        };
      }
      return intermediateStats;
    });
  }, []);

  const addRevealedLetters = useCallback((count: number) => {
    if (count === 0) return;
    setStats(prevStats => {
      const intermediateStats = { ...prevStats, totalLettersRevealed: (prevStats.totalLettersRevealed || 0) + count };
      const newAchievements = getNewAchievements(intermediateStats);

      if (newAchievements.length > 0) {
        setNewlyUnlocked(newAchievements);
        const newAchievementUnlockTimes = { ...intermediateStats.achievementUnlockTimes };
        newAchievements.forEach(a => {
          newAchievementUnlockTimes[a.id] = intermediateStats.totalPlayTimeSeconds || 0;
        });
        return {
          ...intermediateStats,
          achievements: [...intermediateStats.achievements, ...newAchievements.map(a => a.id)],
          achievementUnlockTimes: newAchievementUnlockTimes,
        };
      }
      return intermediateStats;
    });
  }, []);

  const clearNewlyUnlocked = useCallback(() => {
    setNewlyUnlocked([]);
  }, []);

  const addPlayTime = useCallback((seconds: number) => {
    setStats(prevStats => ({
      ...prevStats,
      totalPlayTimeSeconds: (prevStats.totalPlayTimeSeconds || 0) + seconds,
    }));
  }, []);

  const unlockFullGame = useCallback(() => {
    setStats(prevStats => ({
      ...prevStats,
      hasUnlockedFullGame: true,
    }));
  }, []);

  return { stats, completeLevel, addRevealedLetters, newlyUnlocked, clearNewlyUnlocked, addPlayTime, unlockFullGame };
};

// =================================================================================
// UI COMPONENTS
// =================================================================================
const LockIcon: React.FC = () => (
    <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8 text-gray-500" viewBox="0 0 20 20" fill="currentColor">
        <path fillRule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clipRule="evenodd" />
    </svg>
);

const ProfileIcon: React.FC<{ className?: string }> = ({ className = "h-6 w-6" }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
    </svg>
);

const ShareIcon: React.FC = () => (
    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
        <path d="M15 8a3 3 0 10-2.977-2.63l-4.94 2.47a3 3 0 100 4.319l4.94 2.47a3 3 0 10.895-1.789l-4.94-2.47a3.027 3.027 0 000-.74l4.94-2.47C13.456 7.68 14.19 8 15 8z" />
    </svg>
);

const RefreshIcon: React.FC<{ className?: string }> = ({ className = "h-6 w-6" }) => (
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" className={className}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0011.664 0M2.985 19.644A8.25 8.25 0 0116.023 9.348" />
    </svg>
);

const StatCard: React.FC<{ label: string; value: number | string }> = ({ label, value }) => (
  <div className="bg-[#F0F0F0] p-2 rounded-lg shadow-md text-center flex-1 flex flex-col justify-center">
    <p className="text-xl font-bold text-[#008080]">{value}</p>
    <p className="text-xs text-gray-600 font-semibold leading-tight">{label}</p>
  </div>
);

declare global {
  interface Window {
    adsbygoogle: any[];
  }
}

const AdsenseAd: React.FC = () => {
  useEffect(() => {
    try {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch (e) {
      console.error('Adsense error:', e);
    }
  }, []);

  return (
    <div
      className="w-full flex justify-center my-2 flex-shrink-0 min-h-[90px] bg-[#F0F0F0]"
      aria-hidden="true"
    >
      <ins
        className="adsbygoogle"
        style={{ display: 'block', width: '100%' }}
        data-ad-client="ca-pub-1678247058695040"
        data-ad-slot="9843279854"
        data-ad-format="auto"
        data-full-width-responsive="true"
      ></ins>
    </div>
  );
};

// =================================================================================
// MODAL COMPONENTS
// =================================================================================
const CorrectAnswerModal: React.FC<{
  isOpen: boolean;
  level: GameLevel;
  onContinue: () => void;
}> = ({ isOpen, level, onContinue }) => {
    if (!isOpen) return null;

    const answerLength = level.answer.length;
    let answerFontSize = 'text-4xl';
    if (answerLength > 22) {
        answerFontSize = 'text-xl';
    } else if (answerLength > 18) {
        answerFontSize = 'text-2xl';
    } else if (answerLength > 14) {
        answerFontSize = 'text-3xl';
    }
    
    const isRTL = /[\u0600-\u06FF]/.test(level.answer);

    return (
        <div className="fixed inset-0 bg-[#FFFFFF] z-50 flex flex-col items-center justify-center p-4 text-[#3D3D3D]">
            <div className="w-full max-w-sm flex flex-col items-center gap-4 animate-fade-in">
                <h1 className="text-4xl font-bold">Well Done!</h1>
                <div className="w-full px-4">
                    <img src={level.image} alt={level.answer} className="w-full h-auto rounded-lg shadow-lg" />
                </div>
                <div 
                  className="text-center flex flex-wrap justify-center items-center gap-x-2 gap-y-1 px-2" 
                  style={{ direction: isRTL ? 'rtl' : 'ltr' }}
                >
                    {level.answer.split(' ').map((word, wordIndex) => {
                        if (word === '') return null;
                        const animationDelay = `${wordIndex * 0.15}s`;
                        return (
                            <span
                                key={wordIndex}
                                className={`${answerFontSize} font-bold inline-block`}
                                style={{
                                    animation: `letter-pop-in 0.5s both`,
                                    animationDelay,
                                }}
                            >
                                {word}
                            </span>
                        );
                    })}
                </div>
                {level.info && (
                    <div className="mt-2 p-3 bg-[#F0F0F0] rounded-lg w-full max-w-xs text-center">
                        <p className="text-sm font-semibold text-gray-700">{level.info}</p>
                    </div>
                )}
                 <button onClick={() => { playSound('click'); onContinue(); }} className="w-full max-w-xs bg-[#008080] hover:bg-[#00695C] text-white font-bold py-3 px-4 rounded-lg transition-transform duration-300 shadow-lg active:scale-95 hover:scale-105 mt-4">
                    Continue
                </button>
            </div>
        </div>
    );
};

const AchievementModal: React.FC<{
  achievement: Achievement;
  stats: PlayerStats;
  onDismiss: () => void;
}> = ({ achievement, stats, onDismiss }) => {
  const [isSharing, setIsSharing] = useState(false);

  const handleShare = async () => {
    playSound('click');
    if (isSharing) return;
    setIsSharing(true);
    
    const solvedCount = stats.completedLevelIds.length;
    const timeString = formatSecondsToTime(stats.totalPlayTimeSeconds || 0);
    const link = window.location.href;
    const message = `I unlocked the "${achievement.name}"\nI have solved ${solvedCount} Maqamaat in ${timeString}. Join me in this challenge ${link}`;
    
    try {
        if (navigator.share) {
            await navigator.share({ title: 'Maqamaat Muqaddasah Achievement!', text: message });
        } else if (navigator.clipboard) {
            await navigator.clipboard.writeText(message);
            alert('Achievement message copied to clipboard!');
        } else {
            alert("Sharing is not supported on your device.");
        }
    } catch (error) {
        console.error("Failed to share achievement:", error);
    } finally {
        setIsSharing(false);
    }
  };

  const handleContinue = () => {
    playSound('click');
    onDismiss();
  };

  return (
    <div 
      className="fixed inset-0 bg-black/70 z-[100] flex items-center justify-center p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="achievement-title"
    >
      <div 
        className="bg-[#FFFFFF] text-[#3D3D3D] rounded-2xl shadow-xl w-full max-w-sm flex flex-col items-center text-center p-6 pt-8 relative animate-fade-in"
      >
        <span className="text-7xl mb-4" style={{ animation: `letter-pop-in 0.5s both` }}>{achievement.icon}</span>
        <h2 id="achievement-title" className="text-3xl font-bold text-[#008080]">{achievement.name}</h2>
        <p className="text-md mt-2 mb-6">{achievement.description}</p>
        
        <div className="w-full flex flex-col gap-3">
            <button
                onClick={handleShare}
                disabled={isSharing}
                className="w-full bg-[#FF6F61] hover:bg-[#D8584B] text-white font-bold py-3 px-4 rounded-lg transition-all duration-300 shadow-md active:scale-95 disabled:bg-gray-400 flex items-center justify-center gap-2"
            >
                {isSharing ? <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div> : <ShareIcon />}
                <span>Share</span>
            </button>
            <button 
                onClick={handleContinue} 
                className="w-full bg-[#008080] hover:bg-[#00695C] text-white font-bold py-3 px-4 rounded-lg transition-all duration-300 shadow-lg active:scale-95"
            >
                Continue
            </button>
        </div>
      </div>
    </div>
  );
};

const OnboardingModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  title: string;
  message: string;
}> = ({ isOpen, onClose, title, message }) => {
  if (!isOpen) return null;

  const handleClose = () => {
    playSound('click');
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" onClick={handleClose}>
      <div className="bg-white text-[#3D3D3D] rounded-2xl shadow-xl w-full max-w-sm p-6 text-center animate-fade-in" onClick={(e) => e.stopPropagation()}>
        <h2 className="text-2xl font-bold text-[#008080] mb-4">{title}</h2>
        <p className="mb-6">{message}</p>
        <button
          onClick={handleClose}
          className="w-full bg-[#008080] hover:bg-[#00695C] text-white font-bold py-3 px-4 rounded-lg transition-transform duration-300 shadow-lg active:scale-95"
        >
          Got it!
        </button>
      </div>
    </div>
  );
};

// =================================================================================
// GAME COMPONENTS
// =================================================================================
const TiledImage: React.FC<{
    imageUrl: string;
    onTileRemove: (index: number) => void;
    removedTiles: Set<number>;
    gridSize?: number;
    maxRemoved?: number;
}> = ({ imageUrl, onTileRemove, removedTiles, gridSize = 4, maxRemoved = 6 }) => {
    const [isImageLoaded, setIsImageLoaded] = useState(false);

    useEffect(() => {
        const img = new Image();
        img.src = imageUrl;
        img.onload = () => setIsImageLoaded(true);
    }, [imageUrl]);

    const handleTileClick = (index: number) => {
        if (removedTiles.has(index) || removedTiles.size >= maxRemoved) {
            return;
        }
        onTileRemove(index);
    };

    const totalTiles = gridSize * gridSize;
    const tiles = Array.from({ length: totalTiles }, (_, i) => i);
    const canRemoveMore = removedTiles.size < maxRemoved;

    return (
        <div 
            className="relative aspect-square w-full max-w-[400px] overflow-hidden rounded-lg shadow-lg bg-cover bg-center"
            style={{ 
                backgroundImage: isImageLoaded ? `url(${imageUrl})` : 'none',
                backgroundColor: isImageLoaded ? 'transparent' : '#F0F0F0'
            }}
        >
            {!isImageLoaded && <div className="absolute inset-0 bg-[#F0F0F0] animate-pulse"></div>}
            
            <div className="absolute inset-0 grid grid-cols-4 grid-rows-4 gap-0">
                {tiles.map(index => {
                    const isRemoved = removedTiles.has(index);
                    const isDisabled = isRemoved || !canRemoveMore;
                    
                    let tileClass = 'transition-opacity duration-300 ease-in-out ';
                    if (isRemoved) {
                        tileClass += 'opacity-0 pointer-events-none';
                    } else {
                        tileClass += 'bg-[#008080] ';
                        if (isDisabled) {
                            tileClass += 'cursor-not-allowed';
                        } else {
                            tileClass += 'hover:bg-[#00695C] cursor-pointer';
                        }
                    }

                    return (
                        <button
                            key={index}
                            onClick={() => handleTileClick(index)}
                            disabled={isDisabled}
                            className={tileClass}
                            aria-label={`Tile ${index + 1}${isRemoved ? ' (revealed)' : ''}`}
                        />
                    );
                })}
            </div>
            
            <div className="absolute bottom-2 right-2 bg-black/50 text-white text-xs font-bold px-2 py-1 rounded">
                {removedTiles.size} / {maxRemoved}
            </div>
        </div>
    );
};

const GameBoard: React.FC<{ level: GameLevel, onLevelComplete: () => void, onLettersRevealed: (count: number) => void }> = ({ level, onLevelComplete, onLettersRevealed }) => {
  const isRTL = /[\u0600-\u06FF]/.test(level.answer);
  const processedAnswer = isRTL ? level.answer : level.answer.toUpperCase();
  const answerForLogic = processedAnswer.replace(/\s/g, '').replace(/[\u064B-\u0652\u0670]/g, '');

  const loadState = (): SavedGameState | null => {
    const savedStateRaw = localStorage.getItem('maqamaat_gameState');
    if (!savedStateRaw) return null;
    try {
        const savedState: SavedGameState = JSON.parse(savedStateRaw);
        if (savedState.levelId === level.id) return savedState;
    } catch (e) { console.error("Failed to parse saved game state:", e); }
    return null;
  };
  
  const [guess, setGuess] = useState<(GuessSlot | null)[]>(() => loadState()?.guess || Array(answerForLogic.length).fill(null));
  const [keyboardLetters, setKeyboardLetters] = useState<KeyboardLetter[]>(() => {
    const savedKeyboard = loadState()?.keyboardLetters;
    if (savedKeyboard) {
      return savedKeyboard;
    }
    const shuffled = shuffleArray(level.letters);
    return shuffled.map((letter, index) => ({ letter, id: index, used: false }));
  });
  const [revealUsed, setRevealUsed] = useState<boolean>(() => loadState()?.revealUsed || false);
  const [removedTiles, setRemovedTiles] = useState<Set<number>>(() => new Set(loadState()?.removedTiles || []));
  const [status, setStatus] = useState<'playing' | 'correct' | 'incorrect'>('playing');
  const [isSharing, setIsSharing] = useState(false);
  const [showOnboardingHint, setShowOnboardingHint] = useState(false);
  const [timeOnLevel, setTimeOnLevel] = useState(0);
  const maxTilesToRemove = 7;

  useEffect(() => {
    if (level.id === 1) {
        const hasSeenHint = localStorage.getItem('maqamaat_hasSeenFirstLevelHint');
        if (!hasSeenHint) {
            setShowOnboardingHint(true);
        }
    }
  }, [level.id]);

  useEffect(() => {
    if (status === 'playing') {
      const interval = setInterval(() => {
        setTimeOnLevel(prev => prev + 1);
      }, 1000);
      return () => clearInterval(interval);
    }
  }, [status]);

  useEffect(() => {
    if (status === 'playing') {
      const stateToSave: SavedGameState = { 
          levelId: level.id,
          guess,
          keyboardLetters,
          revealUsed,
          removedTiles: Array.from(removedTiles)
      };
      localStorage.setItem('maqamaat_gameState', JSON.stringify(stateToSave));
    }
  }, [guess, keyboardLetters, revealUsed, removedTiles, level.id, status]);

  useEffect(() => {
    if (status === 'playing' && guess.every(g => g !== null)) {
      if (guess.map(g => g!.letter).join('') === answerForLogic) { 
          playSound('correct'); 
          setStatus('correct'); 
      }
      else { playSound('incorrect'); setStatus('incorrect'); }
    }
  }, [guess, answerForLogic, status]);

  useEffect(() => {
    if (status === 'incorrect') {
      const timer = setTimeout(() => {
        setGuess(Array(answerForLogic.length).fill(null));
        setKeyboardLetters(prev => prev.map(key => ({ ...key, used: false })));
        setStatus('playing');
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [status, answerForLogic.length]);

  const handleKeyboardClick = (clickedLetter: string, clickedId: number) => {
    const letterState = keyboardLetters.find(l => l.id === clickedId);
    if (status !== 'playing' || letterState?.used) return;
    const firstEmptyIndex = guess.findIndex(g => g === null);
    if (firstEmptyIndex !== -1) {
      playSound('place');
      const newGuess = [...guess];
      newGuess[firstEmptyIndex] = { letter: clickedLetter, keyboardId: clickedId };
      setGuess(newGuess);
      setKeyboardLetters(prev => prev.map(key => (key.id === clickedId ? { ...key, used: true } : key)));
    }
  };

  const handleAnswerClick = (guessIndex: number) => {
    if (status !== 'playing') return;
    const guessSlot = guess[guessIndex];
    if (guessSlot) {
      playSound('remove');
      const newGuess = [...guess];
      newGuess[guessIndex] = null;
      setGuess(newGuess);
      setKeyboardLetters(prev => prev.map(key => (key.id === guessSlot.keyboardId ? { ...key, used: false } : key)));
    }
  };

  const handleRevealClick = () => {
    if (revealUsed || status !== 'playing') return;

    // 1. Find all potential reveals by matching empty slots to available keyboard letters
    const availableKeyboard = keyboardLetters.filter(k => !k.used);
    const emptyGuessIndices = guess.map((g, i) => (g === null ? i : -1)).filter(i => i !== -1);
    
    const possibleReveals: { guessIndex: number; keyboardId: number; letter: string }[] = [];

    for (const guessIndex of emptyGuessIndices) {
        const correctLetter = answerForLogic[guessIndex];
        const keyboardMatchIndex = availableKeyboard.findIndex(k => k.letter === correctLetter);

        if (keyboardMatchIndex !== -1) {
            const keyboardLetter = availableKeyboard[keyboardMatchIndex];
            possibleReveals.push({ guessIndex, keyboardId: keyboardLetter.id, letter: correctLetter });
            // Temporarily remove from availableKeyboard to prevent using the same keyboard letter twice in one hint
            availableKeyboard.splice(keyboardMatchIndex, 1);
        }
    }

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

    // 2. Shuffle possibilities and pick up to 3 to apply
    const shuffledReveals = shuffleArray(possibleReveals);
    const revealsToApply = shuffledReveals.slice(0, 3);
    
    // 3. Apply the reveals to temporary state copies
    let tempGuess = [...guess];
    const revealedKeyboardIds = new Set(revealsToApply.map(r => r.keyboardId));

    for (const reveal of revealsToApply) {
        tempGuess[reveal.guessIndex] = { letter: reveal.letter, keyboardId: reveal.keyboardId };
    }
    
    const tempKeyboard = keyboardLetters.map(k => 
        revealedKeyboardIds.has(k.id) ? { ...k, used: true } : k
    );

    // 4. Update the actual state
    playSound('hint');
    onLettersRevealed(revealsToApply.length);
    setGuess(tempGuess);
    setKeyboardLetters(tempKeyboard);
    setRevealUsed(true);
  };

  const handleAskFriend = async () => {
    if (isSharing) return;
    setIsSharing(true);
    playSound('click');
    try {
      const shareText = `Mane aa Maqamaat solve karwama madad kari sako cho?\n\nQuestion: ${level.question || 'No question available'}\nLetters: ${level.letters.join(', ')}\nAnswer length: ${answerForLogic.length} letters\n\nAap bhi shamil thaiye aa activity ma: ${window.location.href}`;
      if (navigator.share) await navigator.share({ title: 'Help me solve this Maqamaat!', text: shareText });
      else window.open(`https://wa.me/?text=${encodeURIComponent(shareText)}`, '_blank');
    } catch (error) { if (error instanceof Error && error.name !== 'AbortError') alert("Could not share. Please try again."); }
    finally { setIsSharing(false); }
  };

  const handleRevealAnswerClick = () => {
    if (timeOnLevel < 120 || status !== 'playing') return;
    playSound('correct');
    setStatus('correct');
  };

  const answerLength = answerForLogic.length;
  
  let sizing = {
    box: 'w-10 h-10 text-xl',
    letterGap: 'gap-x-1',
    wordContainer: 'gap-y-2 gap-x-2',
  };

  if (answerLength > 15) { // 16+ letters: Very small
    sizing = {
      box: 'w-6 h-6 text-sm',
      letterGap: 'gap-x-0.5',
      wordContainer: 'gap-y-1 gap-x-1',
    };
  } else if (answerLength > 11) { // 12-15 letters: Small
    sizing = {
      box: 'w-7 h-7 text-base',
      letterGap: 'gap-x-1',
      wordContainer: 'gap-y-1 gap-x-1.5',
    };
  } else if (answerLength > 8) { // 9-11 letters: Medium
    sizing = {
      box: 'w-8 h-8 text-lg',
      letterGap: 'gap-x-1',
      wordContainer: 'gap-y-2 gap-x-2',
    };
  }

  const words = processedAnswer.split(' ');
  let cumulativeLetterIndex = 0;
  
  return (
    <div className="flex-grow min-h-0 flex flex-col gap-2 w-full">
      <OnboardingModal
        isOpen={showOnboardingHint}
        onClose={() => {
            setShowOnboardingHint(false);
            localStorage.setItem('maqamaat_hasSeenFirstLevelHint', 'true');
        }}
        title="How to Play"
        message="Click and remove tiles to reveal the picture!"
      />
      <CorrectAnswerModal isOpen={status === 'correct'} level={level} onContinue={onLevelComplete} />
      
      <p className="text-2xl font-bold text-center flex-shrink-0">{level.question}</p>

      <div className="flex-grow w-full flex items-center justify-center min-h-0">
        <TiledImage 
            imageUrl={level.image}
            removedTiles={removedTiles}
            onTileRemove={(index) => {
                playSound('remove');
                const newTiles = new Set(removedTiles);
                newTiles.add(index);
                setRemovedTiles(newTiles);
            }}
            maxRemoved={maxTilesToRemove}
        />
      </div>

      <div className="w-full flex flex-col items-center gap-3 flex-shrink-0">
        <div 
            className={`flex flex-row flex-wrap justify-center items-center px-1 max-w-full ${sizing.wordContainer}`}
            style={{
                animation: status === 'incorrect' ? 'shake 0.5s' : '',
                direction: isRTL ? 'rtl' : 'ltr'
            }}
        >
            {words.map((word, wordIndex) => {
                const sanitizedWord = word.replace(/[\u064B-\u0652\u0670]/g, '');
                if (sanitizedWord.length === 0) return null;
                const wordStartLetterIndex = cumulativeLetterIndex;
                const wordElement = (
                    <div key={`word-${wordIndex}`} className={`flex items-center flex-nowrap justify-center ${sizing.letterGap}`}>
                        {sanitizedWord.split('').map((_, letterInWordIndex) => {
                            const guessIndex = wordStartLetterIndex + letterInWordIndex;
                            const guessSlot = guess[guessIndex];
                            const borderColor = status === 'incorrect' ? 'border-red-500' : status === 'correct' ? 'border-green-500' : 'border-gray-500';
                            return (
                                <button key={guessIndex} onClick={() => handleAnswerClick(guessIndex)} disabled={!guessSlot} className={`${sizing.box} flex items-center justify-center font-bold uppercase transition-colors border-b-4 ${borderColor} ${guessSlot ? 'cursor-pointer' : 'cursor-default'}`} aria-label={guessSlot ? `Remove letter ${guessSlot.letter}` : `Empty letter slot ${guessIndex + 1}`}>
                                    {guessSlot?.letter && <span key={guessSlot.keyboardId} className="inline-block animate-fade-in">{guessSlot.letter}</span>}
                                </button>
                            );
                        })}
                    </div>
                );
                cumulativeLetterIndex += sanitizedWord.length;
                return wordElement;
            })}
        </div>
        <div className="w-full max-w-sm flex items-stretch gap-2">
            <button onClick={handleRevealClick} disabled={revealUsed || status !== 'playing'} className="flex-1 bg-[#008080] hover:bg-[#00695C] text-white font-bold py-2 px-2 text-xs rounded-lg transition-all duration-300 shadow-md active:scale-95 disabled:bg-gray-400 disabled:cursor-not-allowed hover:scale-105">Reveal Letter</button>
            <button onClick={handleAskFriend} disabled={isSharing || status !== 'playing'} className="flex-1 bg-[#FF6F61] hover:bg-[#D8584B] text-white font-bold py-2 px-2 text-xs rounded-lg transition-all duration-300 shadow-md active:scale-95 disabled:bg-gray-400 disabled:cursor-not-allowed hover:scale-105">{isSharing ? 'Sharing...' : 'Ask Friend'}</button>
            
            {timeOnLevel < 120 ? (
                <div className="flex-1 text-xs text-center font-semibold text-gray-500 bg-[#F0F0F0] py-2 px-2 rounded-lg shadow-inner flex items-center justify-center">
                    Reveal in<br/>{120 - timeOnLevel}s
                </div>
            ) : (
                <button 
                    onClick={handleRevealAnswerClick}
                    disabled={status !== 'playing'}
                    className="flex-1 bg-[#008080] hover:bg-[#00695C] text-white font-bold py-2 px-2 text-xs rounded-lg transition-all duration-300 shadow-md active:scale-95 disabled:bg-gray-400 disabled:cursor-not-allowed hover:scale-105"
                >
                    Reveal Answer
                </button>
            )}
        </div>
        <div className="w-full max-w-sm grid grid-cols-6 gap-2">
          {keyboardLetters.map(({ letter, id, used }) => ( <button key={id} onClick={() => handleKeyboardClick(letter, id)} disabled={used} className="h-11 bg-[#008080] text-white rounded-md text-2xl font-bold flex items-center justify-center transition-all duration-200 shadow-md border-b-4 border-[#004D40] hover:bg-[#00695C] active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed">{letter}</button>))}
        </div>
      </div>
    </div>
  );
};

const LevelSelect: React.FC<{
  levels: GameLevel[];
  onSelectLevel: (level: GameLevel) => void;
  playerStats: PlayerStats;
  onShowProfile: () => void;
}> = ({ levels, onSelectLevel, playerStats, onShowProfile }) => {
  const [currentPage, setCurrentPage] = useState(0);
  const levelsPerPage = 24;
  const pageCount = Math.ceil(levels.length / levelsPerPage);
  const highestUnlockedLevel = playerStats.completedLevelIds.length + 1;

  const handleNextPage = () => {
    playSound('click');
    setCurrentPage(prev => Math.min(prev + 1, pageCount - 1));
  };

  const handlePrevPage = () => {
    playSound('click');
    setCurrentPage(prev => Math.max(prev - 1, 0));
  };

  const handleRefresh = () => {
    playSound('click');
    localStorage.removeItem('maqamaat_gameState');
    window.location.reload();
  };

  const startIndex = currentPage * levelsPerPage;
  const currentLevels = levels.slice(startIndex, startIndex + levelsPerPage);
  const totalPlayableLevels = levels.filter(l => l.answer !== "قادم").length;
  const completionPercentage = totalPlayableLevels > 0 ? Math.round((playerStats.completedLevelIds.length / totalPlayableLevels) * 100) : 0;

  return (
    <div className="flex-grow flex flex-col h-full animate-fade-in">
      <header className="flex justify-between items-center pt-2 pb-1">
        <h1 className="text-xl font-bold text-[#008080] whitespace-nowrap">Select a Level</h1>
        <div className="flex items-center gap-2">
            <button
                onClick={handleRefresh}
                aria-label="Refresh levels"
                className="bg-[#008080] text-white font-bold px-2.5 py-1.5 rounded-full shadow-md hover:bg-[#00695C] active:scale-95 transition-all duration-200"
            >
                <span className="text-xs font-semibold">Refresh levels</span>
            </button>
            <button
                onClick={() => { playSound('click'); onShowProfile(); }}
                aria-label="View Profile"
                className="flex items-center gap-1 bg-[#008080] text-white font-bold px-2.5 py-1.5 rounded-full shadow-md hover:bg-[#00695C] active:scale-95 transition-all duration-200"
            >
                <ProfileIcon className="h-5 w-5" />
                <span className="text-xs font-semibold">Profile</span>
            </button>
        </div>
      </header>
       <div className="w-full my-2">
            <div className="flex justify-between text-sm font-bold text-gray-600 mb-1">
                <span>Game Progress</span>
                <span>{completionPercentage}%</span>
            </div>
            <div className="w-full bg-[#F0F0F0] rounded-full h-2.5"><div className="bg-[#008080] h-2.5 rounded-full" style={{ width: `${completionPercentage}%` }}></div></div>
        </div>
        <div className="my-2">
            <a 
                href="https://zahabapps.store/games/4picture1rivayat_game/" 
                target="_blank" 
                rel="noopener noreferrer"
                className="flex items-center justify-between p-3 rounded-lg bg-gradient-to-r from-[#008080] to-[#00695C] text-white shadow-lg hover:shadow-xl transition-shadow duration-300"
                onClick={() => playSound('click')}
            >
                <div className="flex items-center gap-3">
                    <div className="text-3xl">🧩</div>
                    <div>
                        <p className="text-sm font-semibold">Try our other game!</p>
                        <p className="text-lg font-bold">4 Pic 1 Rivayat</p>
                    </div>
                </div>
                <div className="text-xs font-bold bg-white text-[#008080] py-1 px-3 rounded-full">
                Play Now
                </div>
            </a>
        </div>
        <AdsenseAd />
      <div className="py-2 flex-grow overflow-y-auto">
        <div className="grid grid-cols-4 gap-3">
          {currentLevels.map((level) => {
            const isBeyondPaywall = level.id > PAYWALL_LEVEL_ID && !playerStats.hasUnlockedFullGame;
            const isLockedByProgress = level.id > highestUnlockedLevel && level.id !== 1;
            const isLocked = isBeyondPaywall || isLockedByProgress;
            const isCompleted = playerStats.completedLevelIds.includes(level.id);
            let buttonClass = 'bg-[#008080] text-white shadow-lg border-b-4 border-[#004D40] hover:bg-[#00695C] active:scale-95';
            if (isLocked) buttonClass = 'bg-[#F0F0F0] cursor-not-allowed';
            else if (isCompleted) buttonClass = 'bg-[#2E7D32] text-white shadow-lg border-b-4 border-[#1B5E20] hover:bg-[#1B5E20] active:scale-95';
            return (
              <button
                key={level.id}
                onClick={() => !isLocked && onSelectLevel(level)}
                disabled={isLocked}
                className={`aspect-square rounded-lg flex flex-col items-center justify-center p-1 text-center transition-all duration-200 ${buttonClass}`}
                aria-label={isLocked ? `Level ${level.id} (Locked)` : `Start Level ${level.id}`}
              >
                {isLocked ? <LockIcon /> : (
                  <>
                    <span className="font-bold text-xl">{level.id}</span>
                    {isCompleted && (
                      <span className="text-[10px] font-normal leading-tight">{level.answer}</span>
                    )}
                  </>
                )}
              </button>
            );
          })}
        </div>
      </div>
       {pageCount > 1 && (
        <div className="mt-auto flex items-center justify-between p-2 flex-shrink-0">
            <button onClick={handlePrevPage} disabled={currentPage === 0} className="px-4 py-2 bg-[#008080] text-white font-bold rounded-lg shadow-md active:scale-95 disabled:bg-gray-400">Prev</button>
            <span className="font-semibold text-lg">Page {currentPage + 1} of {pageCount}</span>
            <button onClick={handleNextPage} disabled={currentPage === pageCount - 1} className="px-4 py-2 bg-[#008080] text-white font-bold rounded-lg shadow-md active:scale-95 disabled:bg-gray-400">Next</button>
        </div>
      )}
    </div>
  );
};

const ProfileScreen: React.FC<{ stats: PlayerStats; onClose: () => void; }> = ({ stats, onClose }) => {
    const [sharingId, setSharingId] = useState<string | null>(null);

    const handleShareAchievement = async (achievement: Achievement) => {
        playSound('click');
        if (sharingId) return;
        setSharingId(achievement.id);

        const solvedCount = stats.completedLevelIds.length;
        const timeString = formatSecondsToTime(stats.totalPlayTimeSeconds || 0);
        const link = window.location.href;
        const message = `I unlocked the "${achievement.name}"\nI have solved ${solvedCount} Maqamaat in ${timeString}. Join me in this challenge ${link}`;

        try {
            if (navigator.share) {
                await navigator.share({ title: 'Maqamaat Muqaddasah Achievement!', text: message });
            } else if (navigator.clipboard) {
                await navigator.clipboard.writeText(message);
                alert('Achievement message copied to clipboard!');
            } else {
                alert("Sharing is not supported, but you're awesome!");
            }
        } catch (error) {
            console.error('Sharing failed:', error);
        } finally {
            setSharingId(null);
        }
    };
    
    const formattedPlayTime = () => {
        return formatSecondsToTime(stats.totalPlayTimeSeconds || 0);
    };

    return (
        <div className="flex-grow flex flex-col h-full animate-fade-in">
            <header className="flex items-center justify-between py-2 relative">
                <button onClick={() => { playSound('click'); onClose(); }} aria-label="Back to Menu" className="p-2">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                    </svg>
                </button>
                <h1 className="text-2xl font-bold text-[#008080]">My Profile</h1>
                <div className="w-9"></div>
            </header>

            <div className="py-4">
                <h2 className="text-xl font-bold mb-3">Statistics</h2>
                <div className="flex items-stretch gap-3">
                    <StatCard label="Puzzles Solved" value={stats.completedLevelIds.length} />
                    <StatCard label="Letters Revealed" value={stats.totalLettersRevealed || 0} />
                    <StatCard label="Play Time" value={formattedPlayTime()} />
                </div>
            </div>

            <div className="flex-grow flex flex-col min-h-0">
                <h2 className="text-xl font-bold mb-3">Achievements</h2>
                <div className="flex-grow overflow-y-auto bg-[#F0F0F0] p-3 rounded-lg shadow-inner">
                    <ul className="space-y-3">
                        {ACHIEVEMENTS.map(achievement => {
                            const isUnlocked = stats.achievements.includes(achievement.id);
                            const unlockMetric = stats.achievementUnlockTimes?.[achievement.id];
                            return (
                                <li key={achievement.id} className={`flex items-center gap-4 p-3 rounded-lg ${isUnlocked ? 'bg-[#FFFFFF] shadow' : 'opacity-50'}`}>
                                    <span className="text-4xl">{achievement.icon}</span>
                                    <div className="flex-grow">
                                        <h3 className="font-bold text-md">{achievement.name}</h3>
                                        <p className="text-sm text-gray-600">{achievement.description}</p>
                                         {isUnlocked && unlockMetric !== undefined && (
                                            <p className="text-xs text-gray-500 italic mt-1">
                                                {unlockMetric > 1000000000000
                                                    ? `Unlocked on ${new Date(unlockMetric).toLocaleDateString()}`
                                                    : `Unlocked at: ${formatSecondsToTime(unlockMetric)}`
                                                }
                                            </p>
                                        )}
                                    </div>
                                     {isUnlocked && (
                                        <button 
                                            onClick={() => handleShareAchievement(achievement)} 
                                            disabled={!!sharingId}
                                            aria-label={`Share ${achievement.name}`}
                                            className="flex-shrink-0 w-10 h-10 bg-[#008080] text-white rounded-full flex items-center justify-center transition-colors hover:bg-[#00695C] active:scale-95 disabled:bg-gray-400"
                                        >
                                            {sharingId === achievement.id ? <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div> : <ShareIcon />}
                                        </button>
                                     )}
                                </li>
                            );
                        })}
                    </ul>
                </div>
            </div>
        </div>
    );
};

const MubarakMohannaScreen: React.FC<{ onBack: () => void; }> = ({ onBack }) => {
    return (
        <div className="flex-grow flex flex-col items-center justify-center h-full animate-fade-in text-center p-4">
            <header className="absolute top-2 left-2">
                <button onClick={() => { playSound('click'); onBack(); }} aria-label="Back to Menu" className="p-2">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                    </svg>
                </button>
            </header>
            
            <div className="mb-8">
                <h1 className="text-5xl font-bold text-[#008080] mb-2 font-['Amiri']">Mubarak Mohanna</h1>
                <p className="text-lg">Aap 15 levels paas kari chuka cho</p>
            </div>

            <button
                onClick={() => {
                    playSound('click');
                    window.location.href = 'https://rzp.io/rzp/maqamaat';
                }}
                className="w-full max-w-xs bg-green-700 hover:bg-green-800 text-white font-bold py-4 px-4 rounded-lg transition-transform duration-300 shadow-lg active:scale-95 hover:scale-105"
            >
                Unlock all Levels now
            </button>
        </div>
    );
};

const GameEndScreen: React.FC<{ onBack: () => void; onShare: () => void; }> = ({ onBack, onShare }) => {
    return (
        <div className="flex-grow flex flex-col items-center justify-center h-full animate-fade-in text-center">
            <span className="text-7xl mb-4">🎉</span>
            <div className="mb-8">
                <h1 className="text-4xl font-bold text-[#008080] mb-4 font-['Amiri']">Mubarak Mohanna</h1>
                <p className="text-md text-gray-700 leading-relaxed">
                    You have completed all the levels successfully. We request you to visit again and do a refresh levels to get new levels when available.
                </p>
                <p className="text-md text-gray-700 mt-4 font-semibold">
                    Shukran and please share! Dua ma yaad
                </p>
            </div>

            <div className="w-full max-w-xs flex flex-col gap-3">
                <button
                    onClick={() => { playSound('click'); onShare(); }}
                    className="w-full bg-[#FF6F61] hover:bg-[#D8584B] text-white font-bold py-3 px-4 rounded-lg transition-transform duration-300 shadow-lg active:scale-95 hover:scale-105 flex items-center justify-center gap-2"
                >
                    <ShareIcon />
                    <span>Share</span>
                </button>
                <button
                    onClick={() => { playSound('click'); onBack(); }}
                    className="w-full bg-[#008080] hover:bg-[#00695C] text-white font-bold py-3 px-4 rounded-lg transition-transform duration-300 shadow-lg active:scale-95 hover:scale-105"
                >
                    Back to Menu
                </button>
            </div>
        </div>
    );
};


const UncoverIcon = () => (
    <svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="text-[#008080] flex-shrink-0">
        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
);

const SpellIcon = () => (
    <svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="text-[#008080] flex-shrink-0">
        <path d="M17 5H3C2.44772 5 2 5.44772 2 6V18C2 18.5523 2.44772 19 3 19H17C17.5523 19 18 18.5523 18 18V6C18 5.44772 17.5523 5 17 5Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M6 9.5H14" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
        <path d="M6 14.5H12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    </svg>
);

const WelcomeScreen: React.FC<{ onStart: () => void; }> = ({ onStart }) => {
    return (
        <div className="flex flex-col justify-between h-full animate-fade-in text-[#3D3D3D] bg-[#FAF8F7] p-4">
            <div>
                <div className="text-center">
                    <h1 className="text-4xl font-bold text-[#008080] mb-2 font-['Amiri']">اهلا وسهلا</h1>
                    <div className="text-sm text-gray-700 space-y-1">
                        <p>Su aap ye Sagla Maqamaat Muqaddasah ni ziyarat kidi che?</p>
                        <p className="font-semibold">Khuda Taala Aqa Moula TUS na saathe jaawu naseeb kare</p>
                    </div>
                </div>
                <div className="flex justify-center my-3">
                    <img src="https://zahabapps.store/games/maqamaat_img/front.png" alt="Maqamaat Muqaddasah" className="rounded-lg shadow-md max-w-full h-auto" style={{maxWidth: '200px'}}/>
                </div>
            </div>
            <div className="space-y-3">
                <h2 className="text-lg font-bold text-center text-gray-800">How to Play</h2>
                <div className="space-y-2">
                    <div className="flex items-center gap-3 bg-white p-3 rounded-xl shadow-md">
                        <UncoverIcon />
                        <div>
                            <strong className="font-bold text-[#008080] text-sm">Uncover the Image</strong>
                            <p className="text-xs">Tap tiles to reveal the hidden picture of a Maqamaat Muqaddasah.</p>
                        </div>
                    </div>
                    <div className="flex items-center gap-3 bg-white p-3 rounded-xl shadow-md">
                        <SpellIcon />
                        <div>
                            <strong className="font-bold text-[#008080] text-sm">Spell the Name</strong>
                            <p className="text-xs">Use the letters provided to guess the name of the Maqam.</p>
                        </div>
                    </div>
                </div>
            </div>
            <button
                onClick={() => { playSound('click'); onStart(); }}
                className="w-full bg-[#008080] hover:bg-[#00695C] text-white font-bold py-3 px-4 text-md rounded-lg transition-transform duration-300 shadow-lg active:scale-95 hover:scale-105 flex items-center justify-center gap-2"
            >
                <span>Let's Begin</span>
                <span className="font-['Amiri'] text-lg">مع التوفيق</span>
            </button>
        </div>
    );
};

// =================================================================================
// APP ROOT COMPONENT
// =================================================================================
type Screen = 'welcome' | 'level_select' | 'playing' | 'profile' | 'unlock' | 'game_end';

const App: React.FC = () => {
  const [screen, setScreen] = useState<Screen>(() => {
    if (typeof window !== 'undefined' && localStorage.getItem('maqamaat_hasSeenWelcomeScreen') === 'true') {
      return 'level_select';
    }
    return 'welcome';
  });
  const [currentLevel, setCurrentLevel] = useState<GameLevel | null>(null);
  const { stats, completeLevel, addRevealedLetters, newlyUnlocked, clearNewlyUnlocked, addPlayTime, unlockFullGame } = usePlayerStats();
  const { isFullScreen, toggleFullScreen } = useFullScreen();
  const [achievementQueue, setAchievementQueue] = useState<Achievement[]>([]);
  const playTimeIntervalRef = useRef<number | null>(null);
  
  useEffect(() => {
    const shouldUnlock = new URLSearchParams(window.location.search).get('unlock') === 'true';
    if (shouldUnlock && !stats.hasUnlockedFullGame) {
      unlockFullGame();
      window.history.replaceState(null, '', window.location.pathname);
    }
  }, [stats.hasUnlockedFullGame, unlockFullGame]);

  const startPlayTimeTracking = useCallback(() => {
    if (playTimeIntervalRef.current) clearInterval(playTimeIntervalRef.current);
    playTimeIntervalRef.current = window.setInterval(() => addPlayTime(1), 1000);
  }, [addPlayTime]);

  const stopPlayTimeTracking = useCallback(() => {
    if (playTimeIntervalRef.current) { clearInterval(playTimeIntervalRef.current); playTimeIntervalRef.current = null; }
  }, []);

  useEffect(() => {
    if (screen === 'playing' && currentLevel) startPlayTimeTracking(); else stopPlayTimeTracking();
    return () => stopPlayTimeTracking();
  }, [screen, currentLevel, startPlayTimeTracking, stopPlayTimeTracking]);

  useEffect(() => {
    if (currentLevel) {
      const nextLevel = LEVELS.find(l => l.id === currentLevel.id + 1);
      if (nextLevel && nextLevel.answer !== "قادم") {
        const isBeyondPaywall = nextLevel.id > PAYWALL_LEVEL_ID && !stats.hasUnlockedFullGame;
        if (!isBeyondPaywall) {
          preloadImages([nextLevel.image]);
        }
      }
    }
  }, [currentLevel, stats.hasUnlockedFullGame]);

  useEffect(() => {
    if (newlyUnlocked.length > 0) {
      playSound('achievement');
      setAchievementQueue(prev => [...prev, ...newlyUnlocked]);
      clearNewlyUnlocked();
    }
  }, [newlyUnlocked, clearNewlyUnlocked]);

  useEffect(() => {
    if (screen === 'welcome' || screen === 'unlock' || screen === 'playing') return;
    const savedStateRaw = localStorage.getItem('maqamaat_gameState');
    if (savedStateRaw) {
      try {
        const { levelId } = JSON.parse(savedStateRaw);
        const levelToLoad = LEVELS.find(l => l.id === levelId);
        
        if (levelToLoad) {
          const highestUnlockedLevel = stats.completedLevelIds.length + 1;
          const isPastPaywall = levelToLoad.id > PAYWALL_LEVEL_ID && !stats.hasUnlockedFullGame;
          const isLockedByProgress = levelToLoad.id > highestUnlockedLevel;

          if (!isPastPaywall && !isLockedByProgress) {
             setCurrentLevel(levelToLoad);
             setScreen('playing');
          } else {
             localStorage.removeItem('maqamaat_gameState');
          }
        } else {
          localStorage.removeItem('maqamaat_gameState');
        }
      } catch (e) { localStorage.removeItem('maqamaat_gameState'); }
    }
  }, [screen, stats.completedLevelIds.length, stats.hasUnlockedFullGame]);

  const handleStartGame = () => {
    playSound('click');
    localStorage.setItem('maqamaat_hasSeenWelcomeScreen', 'true');
    setScreen('level_select');
  };

  const handleLevelSelect = (level: GameLevel) => { playSound('click'); setCurrentLevel(level); setScreen('playing'); };
  
  const handleBackToMenu = () => { playSound('click'); setCurrentLevel(null); setScreen('level_select'); localStorage.removeItem('maqamaat_gameState'); };
  
  const handleLevelComplete = () => {
    if (currentLevel) {
      completeLevel(currentLevel.id);
      localStorage.removeItem('maqamaat_gameState');
      
      const nextLevel = LEVELS.find(level => level.id === currentLevel.id + 1);

      if (!nextLevel || nextLevel.answer === "قادم") {
        setScreen('game_end');
        return;
      }
      
      const isNextLevelBeyondPaywall = nextLevel.id > PAYWALL_LEVEL_ID && !stats.hasUnlockedFullGame;

      if (isNextLevelBeyondPaywall) {
        setScreen('unlock');
      } else {
        setCurrentLevel(nextLevel);
      }
    }
  };

  const handleShareGame = async (isGameEnd = false) => {
    playSound('click');
    const shareText = isGameEnd
        ? `Alhamdulillah, I've completed all the levels in Maqamaat Muqaddasah! Join me in this challenge. Dua ma yaad. ${window.location.href}`
        : `Salam, Maqamaat Muqaddasah ni activity zaroor try karjo. Ekdum maza aavse. aa link par jaiye ${window.location.href}`;

    try {
        if (navigator.share) await navigator.share({ title: "Maqamaat Muqaddasah", text: shareText });
        else window.open(`https://wa.me/?text=${encodeURIComponent(shareText)}`, '_blank');
    } catch (error) { console.log('Sharing failed:', error); }
  };
  
  const handleToggleFullScreen = () => {
    playSound('click');
    toggleFullScreen();
  };

  const renderScreen = () => {
    switch(screen) {
      case 'welcome': return <WelcomeScreen onStart={handleStartGame} />;
      case 'unlock': return <MubarakMohannaScreen onBack={handleBackToMenu} />;
      case 'game_end': return <GameEndScreen onBack={handleBackToMenu} onShare={() => handleShareGame(true)} />;
      case 'profile': return <ProfileScreen stats={stats} onClose={() => setScreen('level_select')} />;
      case 'playing': 
        return currentLevel ? (
          <div className="flex flex-col h-full">
            <header className="flex items-center justify-between py-2 relative flex-shrink-0">
                <div className="flex items-center flex-1"><button onClick={handleBackToMenu} aria-label="Menu" className="p-2"><svg xmlns="http://www.w3.org/2000/svg" className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" /></svg></button></div>
                <h1 className="text-3xl font-bold">Level {currentLevel.id}</h1>
                <div className="flex items-center justify-end flex-1 gap-2">
                    <button onClick={handleToggleFullScreen} aria-label={isFullScreen ? 'Exit full screen' : 'Enter full screen'} className="p-2 text-[#008080] border-2 border-[#008080] rounded-lg hover:bg-[#008080] hover:text-[#FFFFFF] transition-colors duration-200 active:scale-95">
                        {isFullScreen ? (
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 8V4h4m12 4V4h-4M4 16v4h4m12-4v4h-4" /></svg>
                        ) : (
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 4H4v4m12-4h4v4M8 20H4v-4m12 4h4v-4" /></svg>
                        )}
                    </button>
                    <button onClick={() => handleShareGame()} aria-label="Share Game" className="p-2 text-[#008080] border-2 border-[#008080] rounded-lg hover:bg-[#008080] hover:text-[#FFFFFF] transition-colors duration-200 active:scale-95">
                        <ShareIcon />
                    </button>
                </div>
            </header>
            <GameBoard key={currentLevel.id} level={currentLevel} onLevelComplete={handleLevelComplete} onLettersRevealed={addRevealedLetters} />
          </div>
        ) : null;
      case 'level_select': 
      default: 
        return <LevelSelect levels={LEVELS} onSelectLevel={handleLevelSelect} playerStats={stats} onShowProfile={() => setScreen('profile')} />;
    }
  }

  const paddingClass = screen === 'welcome' || screen === 'game_end' ? '' : 'px-3 pt-2 pb-3';
  const bgClass = screen === 'welcome' || screen === 'game_end' ? 'bg-[#FAF8F7]' : 'bg-[#FFFFFF]';
  
  return (
    <div className={`max-w-sm mx-auto h-full ${bgClass} text-[#3D3D3D] flex flex-col shadow-2xl overflow-hidden ${paddingClass}`}>
      {renderScreen()}
      {achievementQueue.length > 0 && <AchievementModal achievement={achievementQueue[0]} stats={stats} onDismiss={() => setAchievementQueue(q => q.slice(1))} />}
    </div>
  );
};


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