

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

// From types.ts
interface GameLevel {
  id: number;
  images: string[];
  answer: string;
  letters: string[];
  hint?: string;
}

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

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

interface SavedGameState {
  levelId: number;
  lives: number;
  guessedLetters: string[]; // Storing as array for JSON compatibility
}

interface PlayerStats {
  completedLevelIds: number[];
  totalHintsUsed: number;
  totalAnswersRevealed: number;
  achievements: string[]; // Array of unlocked achievement IDs
  totalPlayTimeSeconds: number;
  achievementUnlockTimes: { [key: string]: number };
  hasUnlockedFullGame: boolean;
  levelsCompletedWithFullStars: number;
}

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

// From constants.ts
// FIX: Changed `shuffleArray` from a generic arrow function to a standard function declaration. This resolves a TSX parsing ambiguity that was causing a cascade of errors throughout the file.
function 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;
}

const GAME_KEY_PREFIX = '4PIC1RIVAYAT';
const PLAYER_STATS_KEY = `${GAME_KEY_PREFIX}_playerStats`;
const GAME_STATE_KEY = `${GAME_KEY_PREFIX}_gameState`;

const definedLevels: Omit<GameLevel, 'id'>[] = [
  { answer: 'زياد الاسود', hint: 'NATHI DEEN MAGAR MOHABBAT', images: [ 'https://zahabapps.store/games/img/level_1_1.jpg', 'https://zahabapps.store/games/img/level_1_2.jpg', 'https://zahabapps.store/games/img/level_1_3.jpg', 'https://zahabapps.store/games/img/level_1_4.jpg' ], letters: [ 'و', 'د', 'ا', 'س', 'ل', 'ا', 'ي', 'ز', 'د', 'ا', 'ب', 'ت' ] },
  { answer: 'نبي ابراهيم', hint: 'NABIULLAH SA NO MOJIZO CHE', images: [ 'https://zahabapps.store/games/img/level_2_1.jpg', 'https://zahabapps.store/games/img/level_2_2.jpg', 'https://zahabapps.store/games/img/level_2_3.jpg', 'https://zahabapps.store/games/img/level_2_4.jpg' ], letters: [ 'ي', 'ب', 'م', 'ا', 'ه', 'ي', 'ا', 'ر', 'ب', 'ن', 'ل', 'ت' ] },
  { answer: 'الفيل', hint: 'JUZ AMMA NI EK SURAT', images: [ 'https://zahabapps.store/games/img/level_3_1.jpg', 'https://zahabapps.store/games/img/level_3_2.jpg', 'https://zahabapps.store/games/img/level_3_3.jpg', 'https://zahabapps.store/games/img/level_3_4.jpg' ], letters: [ 'ا', 'ل', 'ف', 'ي', 'ل', 'ش', 'م', 'ب', 'ص', 'ه', 'غ', 'ت' ] },
  { answer: 'سيدنا حاتم', hint: 'HAR DAREES MA TILAWat THAI CHE', images: [ 'https://zahabapps.store/games/img/level_4_1.jpg', 'https://zahabapps.store/games/img/level_4_2.jpg', 'https://zahabapps.store/games/img/level_4_3.jpg', 'https://zahabapps.store/games/img/level_4_4.jpg' ], letters: [ 'ع', 'ح', 'م', 'ا', 'س', 'ي', 'د', 'ن', 'ا', 'ت', 'م', 'ل' ] },
  { answer: 'مولاي راج', hint: 'MORBI', images: [ 'https://zahabapps.store/games/img/level_5_1.jpg', 'https://zahabapps.store/games/img/level_5_2.jpg', 'https://zahabapps.store/games/img/level_5_3.jpg', 'https://zahabapps.store/games/img/level_5_4.jpg' ], letters: [ 'ج', 'ا', 'ل', 'و', 'ر', 'م', 'ي', 'ا', 'ي', 'ه', 'ق', 'س' ] },
  { answer: 'مجوسي', hint: 'IMAM HUSAIN SA MADAD MA PADHARA', images: [ 'https://zahabapps.store/games/img/level_6_1.jpg', 'https://zahabapps.store/games/img/level_6_2.jpg', 'https://zahabapps.store/games/img/level_6_3.jpg', 'https://zahabapps.store/games/img/level_6_4.jpg' ], letters: [ 'ش', 'س', 'ج', 'و', 'م', 'ي', 'ث', 'ف', 'ب', 'ا', 'غ', 'ح' ] },
  { answer: 'بني رياح', hint: 'GULAAM NA QABILA NU NAAM', images: [ 'https://zahabapps.store/games/img/level_7_1.jpg', 'https://zahabapps.store/games/img/level_7_2.jpg', 'https://zahabapps.store/games/img/level_7_3.jpg', 'https://zahabapps.store/games/img/level_7_4.jpg' ], letters: [ 'ي', 'ب', 'ح', 'ا', 'ن', 'ر', 'ي', 'ا', 'ش', 'ز', 'و', 'ت' ] },
  { answer: 'خيبر', hint: 'MARHAB', images: [ 'https://zahabapps.store/games/img/level_8_1.jpg', 'https://zahabapps.store/games/img/level_8_2.jpg', 'https://zahabapps.store/games/img/level_8_3.jpg', 'https://zahabapps.store/games/img/level_8_4.jpg' ], letters: [ 'ب', 'ي', 'ر', 'خ', 'ص', 'س', 'ح', 'ت', 'ث', 'ذ', 'ن', 'ا' ] },
  { answer: 'بڑهيا', hint: 'KARBALA KI ZIYARAT BINA...', images: [ 'https://zahabapps.store/games/img/level_9_1.jpg', 'https://zahabapps.store/games/img/level_9_2.jpg', 'https://zahabapps.store/games/img/level_9_3.jpg', 'https://zahabapps.store/games/img/level_9_4.jpg' ], letters: [ 'ا', 'ڑ', 'ي', 'ه', 'ب', 'ز', 'م', 'ر', 'ت', 'غ', 'ح', 'ج' ] },
  { answer: 'هجرة', hint: 'طلع البدر علينا', images: [ 'https://zahabapps.store/games/img/level_10_1.jpg', 'https://zahabapps.store/games/img/level_10_2.jpg', 'https://zahabapps.store/games/img/level_10_3.jpg', 'https://zahabapps.store/games/img/level_10_4.jpg' ], letters: [ 'ة', 'ج', 'ر', 'ه', 'ي', 'ع', 'ل', 'ا', 'ك', 'م', 'س', 'ب' ] },
  { answer: 'خندق', hint: 'AA ZIKR NA BAAD NARAE TAKBEER BOLYE CHE', images: [ 'https://zahabapps.store/games/img/level_11_1.jpg', 'https://zahabapps.store/games/img/level_11_2.jpg', 'https://zahabapps.store/games/img/level_11_3.jpg', 'https://zahabapps.store/games/img/level_11_4.jpg' ], letters: [ 'ن', 'ق', 'خ', 'د', 'ت', 'ج', 'ب', 'ذ', 'ص', 'ش', 'س', 'ا' ] },
  { answer: 'ركوع', hint: 'KAYA HALAT MA SADAQA?', images: [ 'https://zahabapps.store/games/img/level_12_1.jpg', 'https://zahabapps.store/games/img/level_12_2.jpg', 'https://zahabapps.store/games/img/level_12_3.jpg', 'https://zahabapps.store/games/img/level_12_4.jpg' ], letters: [ 'و', 'ك', 'ع', 'ر', 'س', 'ا', 'ي', 'ب', 'ه', 'ح', 'ش', 'ل' ] },
  { answer: 'صدقة', hint: 'EK AMAL NA SABAB UMAR LAMBI THAI', images: [ 'https://zahabapps.store/games/img/level_13_1.jpg', 'https://zahabapps.store/games/img/level_13_2.jpg', 'https://zahabapps.store/games/img/level_13_3.jpg', 'https://zahabapps.store/games/img/level_13_4.jpg' ], letters: [ 'ص', 'ة', 'ق', 'د', 'ط', 'ا', 'ر', 'ب', 'ز', 'ح', 'س', 'ت' ] },
  { answer: 'RAINMAKER', hint: 'SMB RA NO MOJIZO', images: [ 'https://zahabapps.store/games/img/level_14_1.jpg', 'https://zahabapps.store/games/img/level_14_2.jpg', 'https://zahabapps.store/games/img/level_14_3.jpg', 'https://zahabapps.store/games/img/level_14_4.jpg' ], letters: [ 'R', 'A', 'I', 'N', 'M', 'A', 'K', 'E', 'R', 'J', 'Y', 'B' ] },
  { answer: 'يهودية', hint: 'AHSIN ILA MAN ASAA ILAIKA', images: [ 'https://zahabapps.store/games/img/level_15_1.jpg', 'https://zahabapps.store/games/img/level_15_2.jpg', 'https://zahabapps.store/games/img/level_15_3.jpg', 'https://zahabapps.store/games/img/level_15_4.jpg' ], letters: [ 'د', 'و', 'ة', 'ي', 'ه', 'ي', 'ا', 'ج', 'ب', 'ل', 'ت', 'ر' ] },
  { answer: 'خانجي فير', hint: 'SAFAI KIDI', images: [ 'https://zahabapps.store/games/img/level_16_1.jpg', 'https://zahabapps.store/games/img/level_16_2.jpg', 'https://zahabapps.store/games/img/level_16_3.jpg', 'https://zahabapps.store/games/img/level_16_4.jpg' ], letters: [ 'خ', 'ا', 'ن', 'ج', 'ي', 'ف', 'ي', 'ر', 'ا', 'ب', 'م', 'ت' ] },
  { answer: 'فاتحة', hint: '40 WAAR KAI SURAT?', images: [ 'https://zahabapps.store/games/img/level_17_1.jpg', 'https://zahabapps.store/games/img/level_17_2.jpg', 'https://zahabapps.store/games/img/level_17_3.jpg', 'https://zahabapps.store/games/img/level_17_4.jpg' ], letters: [ 'ح', 'ة', 'ت', 'ا', 'ف', 'ا', 'ص', 'ب', 'م', 'ل', 'ك', 'ي' ] },
  { answer: 'معوّذتين', hint: 'KAI BE SURAT?', images: [ 'https://zahabapps.store/games/img/level_18_1.jpg', 'https://zahabapps.store/games/img/level_18_2.jpg', 'https://zahabapps.store/games/img/level_18_3.jpg', 'https://zahabapps.store/games/img/level_18_4.jpg' ], letters: [ 'ع', 'و', 'ذ', 'ت', 'ي', 'ن', 'م', 'ص', 'ض', 'ب', 'ل', 'ا' ] },
  { answer: 'جابر', hint: 'ZIYARAT NO SHAUQ', images: [ 'https://zahabapps.store/games/img/level_19_1.jpg', 'https://zahabapps.store/games/img/level_19_2.jpg', 'https://zahabapps.store/games/img/level_19_3.jpg', 'https://zahabapps.store/games/img/level_19_4.jpg' ], letters: [ 'ر', 'ا', 'ج', 'ب', 'ي', 'ه', 'ل', 'س', 'ح', 'م', 'ت', 'ك' ] },
  { answer: 'غدير خم', hint: 'MAN KUNTO MAWLAHO', images: [ 'https://zahabapps.store/games/img/level_20_1.jpg', 'https://zahabapps.store/games/img/level_20_2.jpg', 'https://zahabapps.store/games/img/level_20_3.jpg', 'https://zahabapps.store/games/img/level_20_4.jpg' ], letters: [ 'غ', 'د', 'ي', 'ر', 'خ', 'م', 'ا', 'ل', 'ف', 'ن', 'ب', 'س' ] },
  { answer: 'موسى', hint: 'KAYA NABI AS?', images: [ 'https://zahabapps.store/games/img/level_21_1.jpg', 'https://zahabapps.store/games/img/level_21_2.jpg', 'https://zahabapps.store/games/img/level_21_3.jpg', 'https://zahabapps.store/games/img/level_21_4.jpg' ], letters: [ 'م', 'و', 'س', 'ى', 'ت', 'ل', 'ي', 'ا', 'ب', 'ه', 'ح', 'ج' ] },
  { answer: 'انشقاق القمر', hint: 'GHANO AZEEM MOJIZA (ARABI)', images: [ 'https://zahabapps.store/games/img/level_22_1.jpg', 'https://zahabapps.store/games/img/level_22_2.jpg', 'https://zahabapps.store/games/img/level_22_3.jpg', 'https://zahabapps.store/games/img/level_22_4.jpg' ], letters: [ 'ا', 'ن', 'ش', 'ق', 'ا', 'ق', 'ا', 'ل', 'ق', 'م', 'ر', 'ت' ] },
  { answer: 'وعده', hint: 'RASULALLAH SAW NA WAFAAT NA BAAD AARABI AAYA ANE TALAB KIDU', images: [ 'https://zahabapps.store/games/img/level_23_1.jpg', 'https://zahabapps.store/games/img/level_23_2.jpg', 'https://zahabapps.store/games/img/level_23_3.jpg', 'https://zahabapps.store/games/img/level_23_4.jpg' ], letters: [ 'و', 'ع', 'د', 'ه', 'ح', 'ت', 'ا', 'ب', 'م', 'ي', 'ل', 'س' ] },
  { answer: 'حسن', hint: 'AGAR QABOOL KARAWI DO TO GULAAM AZAD. KAYA IMAM AS?', images: [ 'https://zahabapps.store/games/img/level_24_1.jpg', 'https://zahabapps.store/games/img/level_24_2.jpg', 'https://zahabapps.store/games/img/level_24_3.jpg', 'https://zahabapps.store/games/img/level_24_4.jpg' ], letters: [ 'ح', 'س', 'ن', 'ت', 'ج', 'ب', 'ا', 'ي', 'م', 'ل', 'ف', 'ه' ] },
  { answer: 'ردّ الشمس', hint: 'ASR NI NAMAZ ADAA FARMAVI', images: [ 'https://zahabapps.store/games/img/level_25_1.jpg', 'https://zahabapps.store/games/img/level_25_2.jpg', 'https://zahabapps.store/games/img/level_25_3.jpg', 'https://zahabapps.store/games/img/level_25_4.jpg' ], letters: [ 'ر', 'د', 'ا', 'ل', 'ش', 'م', 'س', 'س', 'ب', 'ي', 'ف', 'ت' ] },
  { answer: 'اٰدم', hint: 'IKHLAAS. MAWLAYA?', images: [ 'https://zahabapps.store/games/img/level_26_1.jpg', 'https://zahabapps.store/games/img/level_26_2.jpg', 'https://zahabapps.store/games/img/level_26_3.jpg', 'https://zahabapps.store/games/img/level_26_4.jpg' ], letters: [ 'ا', 'ٰ', 'د', 'م', 'ح', 'ج', 'ت', 'ب', 'ي', 'س', 'ه', 'و' ] },
  { answer: 'كهمبات', hint: 'KAKA ANE KAKI AKELA. JAGAH?', images: [ 'https://zahabapps.store/games/img/level_27_1.jpg', 'https://zahabapps.store/games/img/level_27_2.jpg', 'https://zahabapps.store/games/img/level_27_3.jpg', 'https://zahabapps.store/games/img/level_27_4.jpg' ], letters: [ 'ك', 'ه', 'م', 'ب', 'ا', 'ت', 'ا', 'ل', 'ي', 'س', 'ر', 'ح' ] },
  { answer: 'سلمان', hint: 'KAYA SAHEB NE AZAAD KIDA?', images: [ 'https://zahabapps.store/games/img/level_28_1.jpg', 'https://zahabapps.store/games/img/level_28_2.jpg', 'https://zahabapps.store/games/img/level_28_3.jpg', 'https://zahabapps.store/games/img/level_28_4.jpg' ], letters: [ 'س', 'ل', 'م', 'ا', 'ن', 'ح', 'ت', 'ب', 'ي', 'ه', 'ج', 'ف' ] },
  { answer: 'فتح مصر', hint: 'لمثل هذا اليوم ارادك امير المؤمنين', images: [ 'https://zahabapps.store/games/img/level_29_1.jpg', 'https://zahabapps.store/games/img/level_29_2.jpg', 'https://zahabapps.store/games/img/level_29_3.jpg', 'https://zahabapps.store/games/img/level_29_4.jpg' ], letters: [ 'ف', 'ت', 'ح', 'م', 'ص', 'ر', 'ا', 'ل', 'ي', 'ب', 'ن', 'ه' ] },
  { answer: 'عبد الله', hint: 'RAJA BHARMAL. KAYA SAHEB? MAWLAYA?', images: [ 'https://zahabapps.store/games/img/level_30_1.jpg', 'https://zahabapps.store/games/img/level_30_2.jpg', 'https://zahabapps.store/games/img/level_30_3.jpg', 'https://zahabapps.store/games/img/level_30_4.jpg' ], letters: [ 'ع', 'ب', 'د', 'ا', 'ل', 'ل', 'ه', 'ا', 'ح', 'م', 'ب', 'ج' ] },
  { answer: 'حسن فير', hint: 'KAYA SAHEB YE AA MISAL JAWAB AAPO?', images: [ 'https://zahabapps.store/games/img/level_31_1.jpg', 'https://zahabapps.store/games/img/level_31_2.jpg', 'https://zahabapps.store/games/img/level_31_3.jpg', 'https://zahabapps.store/games/img/level_31_4.jpg' ], letters: [ 'ح', 'س', 'ن', 'ف', 'ي', 'ر', 'ا', 'م', 'ج', 'ت', 'ب', 'ه' ] },
  { answer: 'لوكهو', hint: 'KEM BHAVE CHE?', images: [ 'https://zahabapps.store/games/img/level_32_1.jpg', 'https://zahabapps.store/games/img/level_32_2.jpg', 'https://zahabapps.store/games/img/level_32_3.jpg', 'https://zahabapps.store/games/img/level_32_4.jpg' ], letters: [ 'ل', 'و', 'ك', 'ه', 'و', 'ا', 'ب', 'ي', 'ت', 'س', 'ح', 'ج' ] },
  { answer: 'بابجي', hint: 'KAYA MOULA?', images: [ 'https://zahabapps.store/games/img/level_33_1.jpg', 'https://zahabapps.store/games/img/level_33_2.jpg', 'https://zahabapps.store/games/img/level_33_3.jpg', 'https://zahabapps.store/games/img/level_33_4.jpg' ], letters: [ 'ب', 'ا', 'ب', 'ج', 'ي', 'ل', 'ت', 'ح', 'ه', 'س', 'ن', 'ف' ] },
  { answer: 'داؤد', hint: 'KAYA DAI AL MUTLAQ RA?', images: [ 'https://zahabapps.store/games/img/level_34_1.jpg', 'https://zahabapps.store/games/img/level_34_2.jpg', 'https://zahabapps.store/games/img/level_34_3.jpg', 'https://zahabapps.store/games/img/level_34_4.jpg' ], letters: [ 'د', 'ا', 'ؤ', 'د', 'ج', 'ت', 'ب', 'ي', 'ل', 'ه', 'س', 'م' ] },
  { answer: 'عبد علي', hint: 'KAYA DAI AL MUTLAQ RA?', images: [ 'https://zahabapps.store/games/img/level_35_1.jpg', 'https://zahabapps.store/games/img/level_35_2.jpg', 'https://zahabapps.store/games/img/level_35_3.jpg', 'https://zahabapps.store/games/img/level_35_4.jpg' ], letters: [ 'ع', 'ب', 'د', 'ع', 'ل', 'ي', 'ي', 'ا', 'ت', 'ه', 'ج', 'س' ] },
  { answer: 'GULF WAR', hint: 'KAYA WAQT NI WAAT CHE?', images: [ 'https://zahabapps.store/games/img/level_36_1.jpg', 'https://zahabapps.store/games/img/level_36_2.jpg', 'https://zahabapps.store/games/img/level_36_3.jpg', 'https://zahabapps.store/games/img/level_36_4.jpg' ], letters: [ 'G', 'U', 'L', 'F', 'W', 'A', 'R', 'A', 'I', 'B', 'T', 'E' ] },
  { answer: 'الامين', hint: 'هذا ___ قد طلع', images: [ 'https://zahabapps.store/games/img/level_37_1.jpg', 'https://zahabapps.store/games/img/level_37_2.jpg', 'https://zahabapps.store/games/img/level_37_3.jpg', 'https://zahabapps.store/games/img/level_37_4.jpg' ], letters: [ 'ا', 'ل', 'ا', 'م', 'ي', 'ن', 'ا', 'ت', 'ه', 'س', 'ج', 'ف' ] },
  { answer: 'ابشّكما', hint: 'احبكما الي؟', images: [ 'https://zahabapps.store/games/img/level_38_1.jpg', 'https://zahabapps.store/games/img/level_38_2.jpg', 'https://zahabapps.store/games/img/level_38_3.jpg', 'https://zahabapps.store/games/img/level_38_4.jpg' ], letters: [ 'ا', 'ب', 'ش', 'ك', 'م', 'ا', 'ا', 'ت', 'ه', 'خ', 'ج', 'ل' ] },
  { answer: 'برنية', hint: 'IMAM AS NA DEEDAAR.. SU CHEEZ CHE?', images: [ 'https://zahabapps.store/games/img/level_39_1.jpg', 'https://zahabapps.store/games/img/level_39_2.jpg', 'https://zahabapps.store/games/img/level_39_3.jpg', 'https://zahabapps.store/games/img/level_39_4.jpg' ], letters: [ 'ب', 'ر', 'ن', 'ي', 'ة', 'خ', 'ا', 'ت', 'م', 'ل', 'ه', 'ج' ] },
  { answer: 'نور', hint: 'BEWE THAYA EK PAIDA', images: [ 'https://zahabapps.store/games/img/level_40_1.jpg', 'https://zahabapps.store/games/img/level_40_2.jpg', 'https://zahabapps.store/games/img/level_40_3.jpg', 'https://zahabapps.store/games/img/level_40_4.jpg' ], letters: [ 'ن', 'و', 'ر', 'ت', 'ي', 'ا', 'ب', 'ل', 'م', 'س', 'خ', 'ج' ] },
  { answer: 'امينجي', hint: 'ILM MA IJTIHAAD', images: [ 'https://zahabapps.store/games/img/level_41_1.jpg', 'https://zahabapps.store/games/img/level_41_2.jpg', 'https://zahabapps.store/games/img/level_41_3.jpg', 'https://zahabapps.store/games/img/level_41_4.jpg' ], letters: [ 'ا', 'م', 'ي', 'ن', 'ج', 'ي', 'ا', 'ب', 'ت', 'ه', 'س', 'ف' ] },
  { answer: 'ولادة', hint: 'MOHAMMED SAW NI', images: [ 'https://zahabapps.store/games/img/level_42_1.jpg', 'https://zahabapps.store/games/img/level_42_2.jpg', 'https://zahabapps.store/games/img/level_42_3.jpg', 'https://zahabapps.store/games/img/level_42_4.jpg' ], letters: [ 'و', 'ل', 'ا', 'د', 'ة', 'ة', 'ب', 'ت', 'ي', 'م', 'ه', 'س' ] },
  { answer: 'راهب', hint: 'KONI ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_43_1.jpg', 'https://zahabapps.store/games/img/level_43_2.jpg', 'https://zahabapps.store/games/img/level_43_3.jpg', 'https://zahabapps.store/games/img/level_43_4.jpg' ], letters: [ 'ر', 'ا', 'ه', 'ب', 'ي', 'ل', 'ت', 'م', 'خ', 'س', 'ج', 'ن' ] },
  { answer: 'سيدنا حاتم', hint: 'KONO MOJIZO CHE?', images: [ 'https://zahabapps.store/games/img/level_44_1.jpg', 'https://zahabapps.store/games/img/level_44_2.jpg', 'https://zahabapps.store/games/img/level_44_3.jpg', 'https://zahabapps.store/games/img/level_44_4.jpg' ], letters: [ 'س', 'ي', 'د', 'ن', 'ا', 'ح', 'ا', 'ت', 'م', 'ا', 'م', 'ب' ] },
  { answer: 'قصاص', hint: 'SU CHEEZ NO KHAUF?', images: [ 'https://zahabapps.store/games/img/level_45_1.jpg', 'https://zahabapps.store/games/img/level_45_2.jpg', 'https://zahabapps.store/games/img/level_45_3.jpg', 'https://zahabapps.store/games/img/level_45_4.jpg' ], letters: [ 'ق', 'ص', 'ا', 'ص', 'ص', 'خ', 'ب', 'ت', 'م', 'ه', 'س', 'ج' ] },
  { answer: 'مستنصر', hint: 'KAYA IMAM AS MOJIZO CHE?', images: [ 'https://zahabapps.store/games/img/level_46_1.jpg', 'https://zahabapps.store/games/img/level_46_2.jpg', 'https://zahabapps.store/games/img/level_46_3.jpg', 'https://zahabapps.store/games/img/level_46_4.jpg' ], letters: [ 'م', 'س', 'ت', 'ن', 'ص', 'ر', 'ا', 'ا', 'ل', 'ب', 'خ', 'ه' ] },
  { answer: 'كولمبو', hint: 'KAI JAGAH AA MOJIZO THAYO?', images: [ 'https://zahabapps.store/games/img/level_47_1.jpg', 'https://zahabapps.store/games/img/level_47_2.jpg', 'https://zahabapps.store/games/img/level_47_3.jpg', 'https://zahabapps.store/games/img/level_47_4.jpg' ], letters: [ 'ك', 'و', 'ل', 'م', 'ب', 'و', 'ا', 'خ', 'ت', 'ه', 'س', 'ج' ] },
  { answer: 'فاطمة', hint: 'ANDHA SI PARDO? KOIYE? SUKAM?', images: [ 'https://zahabapps.store/games/img/level_48_1.jpg', 'https://zahabapps.store/games/img/level_48_2.jpg', 'https://zahabapps.store/games/img/level_48_3.jpg', 'https://zahabapps.store/games/img/level_48_4.jpg' ], letters: [ 'ف', 'ا', 'ط', 'م', 'ة', 'ي', 'ل', 'خ', 'ب', 'ت', 'ه', 'س' ] },
  { answer: 'حسد', hint: 'EK BAD KHULUQ NI ZIKR CHE', images: [ 'https://zahabapps.store/games/img/level_49_1.jpg', 'https://zahabapps.store/games/img/level_49_2.jpg', 'https://zahabapps.store/games/img/level_49_3.jpg', 'https://zahabapps.store/games/img/level_49_4.jpg' ], letters: [ 'ح', 'س', 'د', 'ت', 'ج', 'ب', 'ا', 'ي', 'م', 'ل', 'ه', 'ف' ] },
  { answer: 'عبد القادر', hint: 'KAYA SAHEB NI ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_50_1.jpg', 'https://zahabapps.store/games/img/level_50_2.jpg', 'https://zahabapps.store/games/img/level_50_3.jpg', 'https://zahabapps.store/games/img/level_50_4.jpg' ], letters: [ 'ع', 'ب', 'د', 'ا', 'ل', 'ق', 'ا', 'د', 'ر', 'ي', 'م', 'ن' ] },
  { answer: '1356', hint: 'AAP HAMARA QIBLA CHO (BAITULLAH NI CHAT) KAYA WARAS MA AAM BANU?', images: [ 'https://zahabapps.store/games/img/level_51_1.jpg', 'https://zahabapps.store/games/img/level_51_2.jpg', 'https://zahabapps.store/games/img/level_51_3.jpg', 'https://zahabapps.store/games/img/level_51_4.jpg' ], letters: [ '1', '3', '5', '6', '0', '4', '8', '2', '9', '7', '1', '3' ] },
  { answer: 'باوا ملا خان', hint: 'KAYA SAHEB AMAL KARTA? SU KARTA THA?', images: [ 'https://zahabapps.store/games/img/level_52_1.jpg', 'https://zahabapps.store/games/img/level_52_2.jpg', 'https://zahabapps.store/games/img/level_52_3.jpg', 'https://zahabapps.store/games/img/level_52_4.jpg' ], letters: [ 'ب', 'ا', 'و', 'ا', 'م', 'ل', 'ا', 'خ', 'ا', 'ن', 'ا', 'ن' ] },
  { answer: 'حسن فير', hint: 'KAYA SAHEB YE AA MISAL JAWAB AAPO?', images: [ 'https://zahabapps.store/games/img/level_53_1.jpg', 'https://zahabapps.store/games/img/level_53_2.jpg', 'https://zahabapps.store/games/img/level_53_3.jpg', 'https://zahabapps.store/games/img/level_53_4.jpg' ], letters: [ 'ح', 'س', 'ن', 'ف', 'ي', 'ر', 'ا', 'ا', 'ل', 'ب', 'ت', 'ه' ] },
  { answer: 'سيدنا عباس', hint: 'KAYA DAI RA SALAM WASTE HATH NHOTA AAPTA? SUKAM?', images: [ 'https://zahabapps.store/games/img/level_54_1.jpg', 'https://zahabapps.store/games/img/level_54_2.jpg', 'https://zahabapps.store/games/img/level_54_3.jpg', 'https://zahabapps.store/games/img/level_54_4.jpg' ], letters: [ 'س', 'ي', 'د', 'ن', 'ا', 'ع', 'ب', 'ا', 'س', 'ا', 'ل', 'ه' ] },
  { answer: 'هبة الله', hint: '1 LAKH 25 HAZAAR NU SAFINO. KAYA DAI NO MOJIZO?', images: [ 'https://zahabapps.store/games/img/level_55_1.jpg', 'https://zahabapps.store/games/img/level_55_2.jpg', 'https://zahabapps.store/games/img/level_55_3.jpg', 'https://zahabapps.store/games/img/level_55_4.jpg' ], letters: [ 'ه', 'ب', 'ة', 'ا', 'ل', 'ل', 'ه', 'ا', 'م', 'س', 'ج', 'ف' ] },
  { answer: 'طي الارض', hint: 'HABIB BIN MAZAHIR NI SHAAN (MOJIZO)', images: [ 'https://zahabapps.store/games/img/level_56_1.jpg', 'https://zahabapps.store/games/img/level_56_2.jpg', 'https://zahabapps.store/games/img/level_56_3.jpg', 'https://zahabapps.store/games/img/level_56_4.jpg' ], letters: [ 'ط', 'ي', 'ا', 'ل', 'ا', 'ر', 'ض', 'ا', 'ت', 'ب', 'ه', 'س' ] },
  { answer: 'ابراهيم', hint: 'KAYA SAHEB? QABR MA BARAKAT.', images: [ 'https://zahabapps.store/games/img/level_57_1.jpg', 'https://zahabapps.store/games/img/level_57_2.jpg', 'https://zahabapps.store/games/img/level_57_3.jpg', 'https://zahabapps.store/games/img/level_57_4.jpg' ], letters: [ 'ا', 'ب', 'ر', 'ا', 'ه', 'ي', 'م', 'ا', 'ت', 'س', 'ج', 'ف' ] },
  { answer: 'اخواني', hint: 'SU KAHI NE YAAD FARMAYA?', images: [ 'https://zahabapps.store/games/img/level_58_1.jpg', 'https://zahabapps.store/games/img/level_58_2.jpg', 'https://zahabapps.store/games/img/level_58_3.jpg', 'https://zahabapps.store/games/img/level_58_4.jpg' ], letters: [ 'ا', 'خ', 'و', 'ا', 'ن', 'ي', 'ا', 'ب', 'ت', 'م', 'ه', 'س' ] },
  { answer: 'النجاشي', hint: 'BADSHAH NO NAAM', images: [ 'https://zahabapps.store/games/img/level_59_1.jpg', 'https://zahabapps.store/games/img/level_59_2.jpg', 'https://zahabapps.store/games/img/level_59_3.jpg', 'https://zahabapps.store/games/img/level_59_4.jpg' ], letters: [ 'ا', 'ل', 'ن', 'ج', 'ا', 'ش', 'ي', 'ح', 'ت', 'ب', 'ه', 'س' ] },
  { answer: 'حسن', hint: 'KAYA SAHEB YE JAWAB FARMAYO?', images: [ 'https://zahabapps.store/games/img/level_60_1.jpg', 'https://zahabapps.store/games/img/level_60_2.jpg', 'https://zahabapps.store/games/img/level_60_3.jpg', 'https://zahabapps.store/games/img/level_60_4.jpg' ], letters: [ 'ح', 'س', 'ن', 'ت', 'ج', 'ب', 'ا', 'ي', 'م', 'ل', 'ه', 'ف' ] },
  { answer: 'حسن بن نوح', hint: 'KONO MOJIZO CHE?', images: [ 'https://zahabapps.store/games/img/level_61_1.jpg', 'https://zahabapps.store/games/img/level_61_2.jpg', 'https://zahabapps.store/games/img/level_61_3.jpg', 'https://zahabapps.store/games/img/level_61_4.jpg' ], letters: [ 'ح', 'س', 'ن', 'ب', 'ن', 'ن', 'و', 'ح', 'ا', 'ن', 'م', 'ل' ] },
  { answer: 'شهاب الدين', hint: 'KAYA SAHEB?', images: [ 'https://zahabapps.store/games/img/level_62_1.jpg', 'https://zahabapps.store/games/img/level_62_2.jpg', 'https://zahabapps.store/games/img/level_62_3.jpg', 'https://zahabapps.store/games/img/level_62_4.jpg' ], letters: [ 'ش', 'ه', 'ا', 'ب', 'ا', 'ل', 'د', 'ي', 'ن', 'د', 'ي', 'ن' ] },
  { answer: 'عيسى', hint: 'KHAUF ANE MOJIZA NI ZIKR. KAYA NABI AS?', images: [ 'https://zahabapps.store/games/img/level_63_1.jpg', 'https://zahabapps.store/games/img/level_63_2.jpg', 'https://zahabapps.store/games/img/level_63_3.jpg', 'https://zahabapps.store/games/img/level_63_4.jpg' ], letters: [ 'ع', 'ي', 'س', 'ى', 'ا', 'ح', 'ل', 'ب', 'ت', 'م', 'ه', 'ج' ] },
  { answer: 'حرز سيفي', hint: 'SIDHPUR MA, 53MA DAI RA YE KAI DUA FAZAL FARMAVI?', images: [ 'https://zahabapps.store/games/img/level_64_1.jpg', 'https://zahabapps.store/games/img/level_64_2.jpg', 'https://zahabapps.store/games/img/level_64_3.jpg', 'https://zahabapps.store/games/img/level_64_4.jpg' ], letters: [ 'ح', 'ر', 'ز', 'س', 'ي', 'ف', 'ي', 'ا', 'ب', 'م', 'ل', 'ن' ] },
  { answer: 'حكيم', hint: 'PURA MADINA BIMAAR CHE. KOIYE KAI TARAH SUDHARA?', images: [ 'https://zahabapps.store/games/img/level_65_1.jpg', 'https://zahabapps.store/games/img/level_65_2.jpg', 'https://zahabapps.store/games/img/level_65_3.jpg', 'https://zahabapps.store/games/img/level_65_4.jpg' ], letters: [ 'ح', 'ك', 'ي', 'م', 'ا', 'ل', 'ت', 'ب', 'ه', 'س', 'ج', 'ف' ] },
  { answer: 'بسم الله', hint: 'CROW', images: [ 'https://zahabapps.store/games/img/level_66_1.jpg', 'https://zahabapps.store/games/img/level_66_2.jpg', 'https://zahabapps.store/games/img/level_66_3.jpg', 'https://zahabapps.store/games/img/level_66_4.jpg' ], letters: [ 'ب', 'س', 'م', 'ا', 'ل', 'ل', 'ه', 'ا', 'ر', 'ك', 'ت', 'ه' ] },
  { answer: 'زوال', hint: 'MOULANA ALI NE JUNG MA SENI FIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_67_1.jpg', 'https://zahabapps.store/games/img/level_67_2.jpg', 'https://zahabapps.store/games/img/level_67_3.jpg', 'https://zahabapps.store/games/img/level_67_4.jpg' ], letters: [ 'ز', 'و', 'ا', 'ل', 'ي', 'ح', 'ت', 'ب', 'م', 'ه', 'س', 'ج' ] },
  { answer: 'كرب وبلاء', hint: 'IMAM HUSAIN SA YE SU FARMAYU?', images: [ 'https://zahabapps.store/games/img/level_68_1.jpg', 'https://zahabapps.store/games/img/level_68_2.jpg', 'https://zahabapps.store/games/img/level_68_3.jpg', 'https://zahabapps.store/games/img/level_68_4.jpg' ], letters: [ 'ك', 'ر', 'ب', 'و', 'ب', 'ل', 'ا', 'ء', 'ي', 'س', 'ن', 'م' ] },
  { answer: 'شهاب', hint: 'SHAYTAN NE SENA SI MARWAMA AAWE CHE?', images: [ 'https://zahabapps.store/games/img/level_69_1.jpg', 'https://zahabapps.store/games/img/level_69_2.jpg', 'https://zahabapps.store/games/img/level_69_3.jpg', 'https://zahabapps.store/games/img/level_69_4.jpg' ], letters: [ 'ش', 'ه', 'ا', 'ب', 'ل', 'ي', 'ح', 'ت', 'م', 'س', 'ج', 'ف' ] },
  { answer: 'يونس', hint: 'KAYA NABI NI ZIKR CHE', images: [ 'https://zahabapps.store/games/img/level_70_1.jpg', 'https://zahabapps.store/games/img/level_70_2.jpg', 'https://zahabapps.store/games/img/level_70_3.jpg', 'https://zahabapps.store/games/img/level_70_4.jpg' ], letters: [ 'ي', 'و', 'ن', 'س', 'ا', 'ل', 'ح', 'ب', 'ت', 'م', 'ه', 'ج' ] },
  { answer: 'ضيافة', hint: 'JABIR BIN ABDULLAH NA FARZANDO NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_71_1.jpg', 'https://zahabapps.store/games/img/level_71_2.jpg', 'https://zahabapps.store/games/img/level_71_3.jpg', 'https://zahabapps.store/games/img/level_71_4.jpg' ], letters: [ 'ض', 'ي', 'ا', 'ف', 'ة', 'ل', 'ح', 'ب', 'ت', 'م', 'ه', 'س' ] },
  { answer: 'ITALIAN MAIL', hint: 'KAYA DAI NI ZIKR CHE? SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_72_1.jpg', 'https://zahabapps.store/games/img/level_72_2.jpg', 'https://zahabapps.store/games/img/level_72_3.jpg', 'https://zahabapps.store/games/img/level_72_4.jpg' ], letters: [ 'I', 'T', 'A', 'L', 'I', 'A', 'N', 'M', 'A', 'I', 'L', 'P' ] },
  { answer: 'صلوات', hint: 'SU CHEEZ YE MARD NA HATH KAPWA SI BACHAYU?', images: [ 'https://zahabapps.store/games/img/level_73_1.jpg', 'https://zahabapps.store/games/img/level_73_2.jpg', 'https://zahabapps.store/games/img/level_73_3.jpg', 'https://zahabapps.store/games/img/level_73_4.jpg' ], letters: [ 'ص', 'ل', 'و', 'ا', 'ت', 'ي', 'ح', 'ب', 'م', 'ه', 'س', 'ج' ] },
  { answer: 'انذار خاص', hint: 'KAI RIVAYAT CHE? RASULLAH SAW NE SU FARMAN THAYA?', images: [ 'https://zahabapps.store/games/img/level_74_1.jpg', 'https://zahabapps.store/games/img/level_74_2.jpg', 'https://zahabapps.store/games/img/level_74_3.jpg', 'https://zahabapps.store/games/img/level_74_4.jpg' ], letters: [ 'ا', 'ن', 'ذ', 'ا', 'ر', 'خ', 'ا', 'ص', 'ب', 'ت', 'م', 'ل' ] },
  { answer: 'MADAGASCAR', hint: 'KAYA SHEHR MA SU MOJIZO THAYU?', images: [ 'https://zahabapps.store/games/img/level_75_1.jpg', 'https://zahabapps.store/games/img/level_75_2.jpg', 'https://zahabapps.store/games/img/level_75_3.jpg', 'https://zahabapps.store/games/img/level_75_4.jpg' ], letters: [ 'M', 'A', 'D', 'A', 'G', 'A', 'S', 'C', 'A', 'R', 'L', 'T' ] },
  { answer: 'ملا واحد', hint: 'KAYA SAHEB NI ZU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_76_1.jpg', 'https://zahabapps.store/games/img/level_76_2.jpg', 'https://zahabapps.store/games/img/level_76_3.jpg', 'https://zahabapps.store/games/img/level_76_4.jpg' ], letters: [ 'م', 'ل', 'ا', 'و', 'ا', 'ح', 'د', 'ب', 'ت', 'ه', 'س', 'ا' ] },
  { answer: 'سيف البحر', hint: 'KAYA JUNG NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_77_1.jpg', 'https://zahabapps.store/games/img/level_77_2.jpg', 'https://zahabapps.store/games/img/level_77_3.jpg', 'https://zahabapps.store/games/img/level_77_4.jpg' ], letters: [ 'س', 'ي', 'ف', 'ا', 'ل', 'ب', 'ح', 'ر', 'ت', 'م', 'ه', 'ا' ] },
  { answer: 'ذمرمر', hint: 'KAYA IMAM NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_78_1.jpg', 'https://zahabapps.store/games/img/level_78_2.jpg', 'https://zahabapps.store/games/img/level_78_3.jpg', 'https://zahabapps.store/games/img/level_78_4.jpg' ], letters: [ 'ذ', 'م', 'ر', 'م', 'ر', 'ا', 'ل', 'خ', 'ب', 'ت', 'ه', 'س' ] },
  { answer: 'يوسف', hint: 'KAYA NABI SABAQ LETA TO WARAMWAAR DOHRWATA? SUKAM AAM MISAL KARTA?', images: [ 'https://zahabapps.store/games/img/level_79_1.jpg', 'https://zahabapps.store/games/img/level_79_2.jpg', 'https://zahabapps.store/games/img/level_79_3.jpg', 'https://zahabapps.store/games/img/level_79_4.jpg' ], letters: [ 'ي', 'و', 'س', 'ف', 'ا', 'ل', 'خ', 'ب', 'ت', 'م', 'ه', 'ج' ] },
  { answer: 'نجم الدين', hint: 'KAYA DAI NA WASTE EK JYOTISH NE PESHINOGOI KIDI? ANE SU KIDI?', images: [ 'https://zahabapps.store/games/img/level_80_1.jpg', 'https://zahabapps.store/games/img/level_80_2.jpg', 'https://zahabapps.store/games/img/level_80_3.jpg', 'https://zahabapps.store/games/img/level_80_4.jpg' ], letters: [ 'ن', 'ج', 'م', 'ا', 'ل', 'د', 'ي', 'ن', 'ت', 'خ', 'ه', 'ب' ] },
  { answer: 'نجم الدين', hint: 'KAYA DAI NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_81_1.jpg', 'https://zahabapps.store/games/img/level_81_2.jpg', 'https://zahabapps.store/games/img/level_81_3.jpg', 'https://zahabapps.store/games/img/level_81_4.jpg' ], letters: [ 'ن', 'ج', 'م', 'ا', 'ل', 'د', 'ي', 'ن', 'ب', 'ت', 'خ', 'ه' ] },
  { answer: 'بنو ثعلبة', hint: 'KAYA QABILA NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_82_1.jpg', 'https://zahabapps.store/games/img/level_82_2.jpg', 'https://zahabapps.store/games/img/level_82_3.jpg', 'https://zahabapps.store/games/img/level_82_4.jpg' ], letters: [ 'ب', 'ن', 'و', 'ث', 'ع', 'ل', 'ب', 'ة', 'ا', 'خ', 'ت', 'م' ] },
  { answer: 'ميثاق', hint: '1347H MA SU THAYU? SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_83_1.jpg', 'https://zahabapps.store/games/img/level_83_2.jpg', 'https://zahabapps.store/games/img/level_83_3.jpg', 'https://zahabapps.store/games/img/level_83_4.jpg' ], letters: [ 'م', 'ي', 'ث', 'ا', 'ق', 'ل', 'خ', 'ب', 'ت', 'ه', 'س', 'ج' ] },
  { answer: 'مهدي', hint: 'KAYA IMAM AS NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_84_1.jpg', 'https://zahabapps.store/games/img/level_84_2.jpg', 'https://zahabapps.store/games/img/level_84_3.jpg', 'https://zahabapps.store/games/img/level_84_4.jpg' ], letters: [ 'م', 'ه', 'د', 'ي', 'ا', 'ل', 'خ', 'ب', 'ت', 'س', 'ج', 'ف' ] },
  { answer: 'معز امام', hint: 'KAYA IMAM AS NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_85_1.jpg', 'https://zahabapps.store/games/img/level_85_2.jpg', 'https://zahabapps.store/games/img/level_85_3.jpg', 'https://zahabapps.store/games/img/level_85_4.jpg' ], letters: [ 'م', 'ع', 'ز', 'ا', 'م', 'ا', 'م', 'ل', 'خ', 'ب', 'ت', 'ه' ] },
  { answer: 'حوالچي', hint: 'KONA HASTAK KAYA DAI RA KAAMO SOPTA HATA?', images: [ 'https://zahabapps.store/games/img/level_86_1.jpg', 'https://zahabapps.store/games/img/level_86_2.jpg', 'https://zahabapps.store/games/img/level_86_3.jpg', 'https://zahabapps.store/games/img/level_86_4.jpg' ], letters: [ 'ح', 'و', 'ا', 'ل', 'چ', 'ي', 'ا', 'ب', 'ت', 'م', 'ه', 'س' ] },
  { answer: 'امام حسن', hint: 'KAYA IMAM AS NI SU ZIKR CHE? HEIGHT OF?', images: [ 'https://zahabapps.store/games/img/level_87_1.jpg', 'https://zahabapps.store/games/img/level_87_2.jpg', 'https://zahabapps.store/games/img/level_87_3.jpg', 'https://zahabapps.store/games/img/level_87_4.jpg' ], letters: [ 'ا', 'م', 'ا', 'م', 'ح', 'س', 'ن', 'ا', 'ت', 'ل', 'ه', 'ف' ] },
  { answer: 'صراط', hint: 'SU CHEEZ ANE EHNA WASF MA SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_88_1.jpg', 'https://zahabapps.store/games/img/level_88_2.jpg', 'https://zahabapps.store/games/img/level_88_3.jpg', 'https://zahabapps.store/games/img/level_88_4.jpg' ], letters: [ 'ص', 'ر', 'ا', 'ط', 'ي', 'ل', 'خ', 'ب', 'ت', 'م', 'ه', 'س' ] },
  { answer: 'عبد القادر', hint: 'KAYA DAI RA YE AA AWQAAT MA BISMILLAH KEHWANU FARMAYU?', images: [ 'https://zahabapps.store/games/img/level_89_1.jpg', 'https://zahabapps.store/games/img/level_89_2.jpg', 'https://zahabapps.store/games/img/level_89_3.jpg', 'https://zahabapps.store/games/img/level_89_4.jpg' ], letters: [ 'ع', 'ب', 'د', 'ا', 'ل', 'ق', 'ا', 'د', 'ر', 'ه', 'ي', 'س' ] },
  { answer: 'سيدهو', hint: 'AMEER YE SU ADAA KIDU? GRAPH SU CHE? SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_90_1.jpg', 'https://zahabapps.store/games/img/level_90_2.jpg', 'https://zahabapps.store/games/img/level_90_3.jpg', 'https://zahabapps.store/games/img/level_90_4.jpg' ], letters: [ 'س', 'ي', 'د', 'ه', 'و', 'ا', 'ل', 'خ', 'ب', 'ت', 'م', 'ج' ] },
  { answer: 'منعم', hint: 'KONI QADR KARWANU FARMAYU?', images: [ 'https://zahabapps.store/games/img/level_91_1.jpg', 'https://zahabapps.store/games/img/level_91_2.jpg', 'https://zahabapps.store/games/img/level_91_3.jpg', 'https://zahabapps.store/games/img/level_91_4.jpg' ], letters: [ 'م', 'ن', 'ع', 'م', 'ي', 'ل', 'س', 'ب', 'ت', 'ا', 'ف', 'ج' ] },
  { answer: 'صدقة', hint: 'IMAM AS YE SU SIKHAMAN AAPI HATI? SALAMATI KEM KHARIDWU?', images: [ 'https://zahabapps.store/games/img/level_92_1.jpg', 'https://zahabapps.store/games/img/level_92_2.jpg', 'https://zahabapps.store/games/img/level_92_3.jpg', 'https://zahabapps.store/games/img/level_92_4.jpg' ], letters: [ 'ص', 'د', 'ق', 'ة', 'س', 'ل', 'ا', 'م', 'ت', 'ي', 'و', 'ه' ] },
  { answer: '49', hint: 'KITNA MA DAI RA NI SU ZIKR CHE? KONE KONE SADAQA APAI?', images: [ 'https://zahabapps.store/games/img/level_93_1.jpg', 'https://zahabapps.store/games/img/level_93_2.jpg', 'https://zahabapps.store/games/img/level_93_3.jpg', 'https://zahabapps.store/games/img/level_93_4.jpg' ], letters: [ '4', '9', '1', '2', '3', '5', '6', '7', '8', '0', 'A', 'B' ] },
  { answer: 'قيصر', hint: 'KAYA BADSHAH YE NABI NA KAGAZ NO JAWAB AAPO TO MUSIBAT NA UTRI', images: [ 'https://zahabapps.store/games/img/level_94_1.jpg', 'https://zahabapps.store/games/img/level_94_2.jpg', 'https://zahabapps.store/games/img/level_94_3.jpg', 'https://zahabapps.store/games/img/level_94_4.jpg' ], letters: [ 'ق', 'ي', 'ص', 'ر', 'ر', 'ل', 'ك', 'ج', 'خ', 'د', 'ا', 'ه' ] },
  { answer: 'اختبار', hint: 'KONA HASTAK KAYA DAI RA KAAMO SOPTA HATA?', images: [ 'https://zahabapps.store/games/img/level_95_1.jpg', 'https://zahabapps.store/games/img/level_95_2.jpg', 'https://zahabapps.store/games/img/level_95_3.jpg', 'https://zahabapps.store/games/img/level_95_4.jpg' ], letters: [ 'ا', 'خ', 'ت', 'ب', 'ا', 'ر', 'ي', 'ب', 'س', 'ش', 'ص', 'ض' ] },
  { answer: 'وياج', hint: 'YE MUMIN BHAI SU CHEEZ SI PAAK THAYA? SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_96_1.jpg', 'https://zahabapps.store/games/img/level_96_2.jpg', 'https://zahabapps.store/games/img/level_96_3.jpg', 'https://zahabapps.store/games/img/level_96_4.jpg' ], letters: [ 'و', 'ي', 'ا', 'ج', 'ج', 'س', 'ل', 'خ', 'م', 'ن', 'ه', 'ب' ] },
  { answer: 'سلمان', hint: 'KAYA SAHEB NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_97_1.jpg', 'https://zahabapps.store/games/img/level_97_2.jpg', 'https://zahabapps.store/games/img/level_97_3.jpg', 'https://zahabapps.store/games/img/level_97_4.jpg' ], letters: [ 'س', 'ل', 'م', 'ا', 'ن', 'ع', 'ي', 'ب', 'ت', 'ث', 'ج', 'خ' ] },
  { answer: 'خيشوان', hint: 'KAYA BADSHAH NA WAZIR NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_98_1.jpg', 'https://zahabapps.store/games/img/level_98_2.jpg', 'https://zahabapps.store/games/img/level_98_3.jpg', 'https://zahabapps.store/games/img/level_98_4.jpg' ], letters: [ 'خ', 'ي', 'ش', 'و', 'ا', 'ن', 'ب', 'ت', 'ص', 'ر', 'ل', 'م' ] },
  { answer: 'خمر', hint: 'KAI KHABEES CHEEZ NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_99_1.jpg', 'https://zahabapps.store/games/img/level_99_2.jpg', 'https://zahabapps.store/games/img/level_99_3.jpg', 'https://zahabapps.store/games/img/level_99_4.jpg' ], letters: [ 'خ', 'م', 'ر', 'خ', 'ا', 'د', 'ج', 'س', 'ش', 'ص', 'ض', 'ت' ] },
  { answer: 'سلمان', hint: 'KAYA SAHEB KONA TARAF SI LAI NE AAYA?', images: [ 'https://zahabapps.store/games/img/level_100_1.jpg', 'https://zahabapps.store/games/img/level_100_2.jpg', 'https://zahabapps.store/games/img/level_100_3.jpg', 'https://zahabapps.store/games/img/level_100_4.jpg' ], letters: [ 'س', 'ل', 'م', 'ا', 'ن', 'ف', 'ا', 'ر', 'ش', 'ي', 'ب', 'ت' ] },
  { answer: 'حرة الملكة', hint: 'KAYA MAWLAT NI SU ZIKR CHE?', images: [ 'https://zahabapps.store/games/img/level_101_1.jpg', 'https://zahabapps.store/games/img/level_101_2.jpg', 'https://zahabapps.store/games/img/level_101_3.jpg', 'https://zahabapps.store/games/img/level_101_4.jpg' ], letters: [ 'ح', 'ر', 'ة', 'ا', 'ل', 'م', 'ل', 'ك', 'ة', 'ي', 'ن', 'ش' ] },
  { answer: 'KODAICANAL', hint: 'KAI JAGAH NO SU MOJIZO CHE?', images: [ 'https://zahabapps.store/games/img/level_102_1.jpg', 'https://zahabapps.store/games/img/level_102_2.jpg', 'https://zahabapps.store/games/img/level_102_3.jpg', 'https://zahabapps.store/games/img/level_102_4.jpg' ], letters: [ 'K', 'O', 'D', 'A', 'I', 'C', 'A', 'N', 'A', 'L', 'M', 'S' ] },
  { answer: 'پل', hint: 'MAZDOOR YE SU BANAYU?', images: [ 'https://zahabapps.store/games/img/level_103_1.jpg', 'https://zahabapps.store/games/img/level_103_2.jpg', 'https://zahabapps.store/games/img/level_103_3.jpg', 'https://zahabapps.store/games/img/level_103_4.jpg' ], letters: [ 'پ', 'ل', 'ا', 'ب', 'ت', 'ح', 'ج', 'م', 'ن', 'و', 'ي', 'ص' ] }
].map(level => ({ ...level, answer: level.answer.normalize("NFC"), letters: shuffleArray(level.letters.map(l => l.normalize("NFC"))) }));


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

const TOTAL_LEVEL_COUNT = LEVELS.length;

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 103 levels.', check: (stats: PlayerStats) => stats.completedLevelIds.length >= TOTAL_LEVEL_COUNT, icon: '🏆' },
];

// From audio.ts
let audioContext: AudioContext | null = null;
let isAudioUnlocked = false;

const unlockAudio = () => {
    if (isAudioUnlocked || typeof window === 'undefined') return;
    if (!audioContext) {
        try {
            audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
        } catch (e) {
            console.error("Could not create AudioContext:", e);
            return;
        }
    }
    if (audioContext.state === 'suspended') {
        audioContext.resume().then(() => {
            isAudioUnlocked = true;
        }).catch(e => {});
    } else {
        isAudioUnlocked = true;
    }
}

type SoundType = 'click' | 'place' | 'remove' | 'incorrect' | 'correct' | 'hint' | 'achievement';

const triggerHapticFeedback = (pattern: number | number[]) => {
  if (typeof window !== 'undefined' && window.navigator && 'vibrate' in window.navigator) {
    try {
      window.navigator.vibrate(pattern);
    } catch (e) {
      console.warn("Haptic feedback failed:", e);
    }
  }
};

const hapticPatterns: { [key in SoundType]: number | number[] } = {
  click: 5,
  place: 10,
  remove: 5,
  incorrect: [10, 50, 10],
  correct: [100],
  hint: 20,
  achievement: [50, 50, 100]
};

const playNote = (frequency: number, type: OscillatorType, duration: number, volume: number = 0.2) => {
    if (!audioContext || !isAudioUnlocked) return;
    const context = audioContext;
    const oscillator = context.createOscillator();
    const gainNode = context.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(context.destination);
    oscillator.type = type;
    oscillator.frequency.setValueAtTime(frequency, context.currentTime);
    gainNode.gain.setValueAtTime(volume, context.currentTime);
    oscillator.start(context.currentTime);
    oscillator.stop(context.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 || !isAudioUnlocked) return;
    const context = audioContext;
    const oscillator = context.createOscillator();
    const gainNode = context.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(context.destination);
    oscillator.type = 'sine';
    oscillator.frequency.setValueAtTime(880, context.currentTime);
    gainNode.gain.setValueAtTime(0.2, context.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 0.2);
    oscillator.start(context.currentTime);
    oscillator.stop(context.currentTime + 0.2);
  },
  incorrect: () => {
    if (!audioContext || !isAudioUnlocked) return;
    playNote(392.00, 'sine', 0.1, 0.25); // G4
    setTimeout(() => playNote(329.63, 'sine', 0.15, 0.25), 120); // E4
  },
  correct: () => {
    if (!audioContext || !isAudioUnlocked) 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 || !isAudioUnlocked) 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) => {
  unlockAudio();
  if (sounds[sound]) {
    sounds[sound]();
  }
  if (hapticPatterns[sound]) {
    triggerHapticFeedback(hapticPatterns[sound]);
  }
};

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

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

  useEffect(() => {
    try {
      localStorage.setItem(PLAYER_STATS_KEY, JSON.stringify(stats));
    } catch (error) {
      console.error('Error saving player stats:', error);
    }
  }, [stats]);

  const checkForNewAchievements = useCallback((currentStats: PlayerStats) => {
    const newAchievements: Achievement[] = [];
    ACHIEVEMENTS.forEach(achievement => {
      const isAlreadyUnlocked = currentStats.achievements.includes(achievement.id);
      if (!isAlreadyUnlocked && achievement.check(currentStats)) {
        newAchievements.push(achievement);
      }
    });

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

  const completeLevel = useCallback((levelId: number, livesRemaining: number, isFirstAttempt: boolean) => {
    setStats(prevStats => {
      if (prevStats.completedLevelIds.includes(levelId)) {
        return prevStats;
      }
      
      const isPerfect = isFirstAttempt && livesRemaining === 3;

      const newStats = {
        ...prevStats,
        completedLevelIds: [...prevStats.completedLevelIds, levelId].sort((a, b) => a - b),
        levelsCompletedWithFullStars: isPerfect
            ? (prevStats.levelsCompletedWithFullStars || 0) + 1
            : (prevStats.levelsCompletedWithFullStars || 0),
      };
      checkForNewAchievements(newStats);
      return newStats;
    });
  }, [checkForNewAchievements]);

  const useHint = useCallback(() => {
    setStats(prevStats => {
      const newStats = { ...prevStats, totalHintsUsed: prevStats.totalHintsUsed + 1 };
      checkForNewAchievements(newStats);
      return newStats;
    });
  }, [checkForNewAchievements]);

  const useAnswerReveal = useCallback(() => {
    setStats(prevStats => ({
      ...prevStats,
      totalAnswersRevealed: (prevStats.totalAnswersRevealed || 0) + 1,
    }));
  }, []);

  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, useHint, useAnswerReveal, newlyUnlocked, clearNewlyUnlocked, addPlayTime, unlockFullGame };
};

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

// From utils/time.ts
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";
};

// From components/ui/icons.tsx
const LockIcon = () => (
    <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 = () => (
    <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" 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 RefreshIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" viewBox="0 0 20 20" fill="currentColor">
        <path fillRule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 110 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clipRule="evenodd" />
    </svg>
);
const ShareIcon = () => (
    <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 StarIcon: React.FC<{ filled?: boolean }> = ({ filled = true }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-8 w-8 ${filled ? 'text-yellow-400' : 'text-gray-400'}`} viewBox="0 0 20 20" fill="currentColor">
        <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
    </svg>
);

// From hooks/useFullScreen.ts
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 };
};

// From components/ui/FullScreenToggle.tsx
const FullScreenToggle: React.FC = () => {
  const { isFullScreen, toggleFullScreen } = useFullScreen();

  const handleToggle = () => {
    playSound('click');
    toggleFullScreen();
  };

  return (
    <button onClick={handleToggle} aria-label={isFullScreen ? 'Exit full screen' : 'Enter full screen'} className="p-2 text-[#C85A48] border-2 border-transparent rounded-full hover:bg-red-100 transition-colors">
      {isFullScreen ? (
        <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" 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>
      ) : (
        <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" 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>
      )}
    </button>
  );
};

// From components/LevelSelect.tsx
const LevelSelect: React.FC<{
  levels: GameLevel[];
  onSelectLevel: (level: GameLevel) => void;
  playerStats: PlayerStats;
  onShowProfile: () => void;
}> = ({ levels, onSelectLevel, playerStats, onShowProfile }) => {
  const [currentPage, setCurrentPage] = React.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');
    window.location.reload();
  };

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

  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-2xl font-bold text-[#C85A48]">Select a Level</h1>
        <div className="flex items-center gap-1">
            <button onClick={() => { playSound('click'); onShowProfile(); }} aria-label="View Profile" className="flex items-center gap-2 px-3 py-1.5 bg-[#C85A48] text-white font-bold rounded-full shadow-md transition-transform duration-200 hover:scale-105 active:scale-95">
              <ProfileIcon />
              <span className="text-sm">Profile</span>
            </button>
            <button onClick={handleRefresh} aria-label="Refresh for updates" className="p-2 text-[#C85A48] border-2 border-transparent rounded-full hover:bg-red-100 transition-colors">
              <RefreshIcon />
            </button>
            <FullScreenToggle />
        </div>
      </header>
       <a 
          href="https://www.zahabapps.store/games/maqamaat" 
          target="_blank" 
          rel="noopener noreferrer"
          className="block bg-[#5A8C8C] text-white p-3 rounded-lg shadow-md my-3 hover:bg-teal-700 transition-colors"
          onClick={() => playSound('click')}
        >
          <div className="flex justify-between items-center">
            <div>
              <h3 className="font-bold text-base">New Activity: Maqamaat Muqaddasah!</h3>
              <p className="text-xs">A new tile-removing guess activity. Check it out!</p>
            </div>
            <div className="bg-white/20 text-white font-bold py-2 px-4 rounded-lg flex-shrink-0 ml-2">
              Play Now
            </div>
          </div>
        </a>
       <div className="w-full my-2">
            <div className="flex justify-between text-sm font-bold text-gray-600 mb-1">
                <span>Activity Progress</span>
                <span>{completionPercentage}%</span>
            </div>
            <div className="w-full bg-[#EFE5D8] rounded-full h-2.5">
                <div className="bg-[#C85A48] h-2.5 rounded-full" style={{ width: `${completionPercentage}%` }}></div>
            </div>
        </div>
      <div className="py-2 flex-grow overflow-y-auto">
        <div className="grid grid-cols-4 gap-3">
          {currentLevels.map((level) => {
            const isBeyondPaywall = level.id > 25 && !playerStats.hasUnlockedFullGame;
            const isLockedByProgress = level.id > highestUnlockedLevel && level.id !== 1;
            const isLocked = isLockedByProgress || isBeyondPaywall;
            const isCompleted = playerStats.completedLevelIds.includes(level.id);
            
            let buttonClass = 'bg-[#C85A48] text-white shadow-lg border-b-4 border-red-800 hover:bg-red-700 active:scale-95';
            if (isLocked) {
              buttonClass = 'bg-[#EFE5D8] cursor-not-allowed';
            } else if (isCompleted) {
              buttonClass = 'bg-green-700 text-white shadow-lg border-b-4 border-green-900 hover:bg-green-800 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 font-bold transition-all duration-200 ${buttonClass}`}
                aria-label={isCompleted ? `Level ${level.id}, Answer: ${level.answer}` : isLocked ? `Level ${level.id} (Locked)` : `Start Level ${level.id}`}
              >
                {isLocked ? <LockIcon /> : (
                  <>
                    <span className="text-xl">{level.id}</span>
                    {isCompleted && (
                      <span className="text-[10px] leading-tight mt-1 break-words">{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-[#C85A48] 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-[#C85A48] text-white font-bold rounded-lg shadow-md active:scale-95 disabled:bg-gray-400">
                Next
            </button>
        </div>
      )}
    </div>
  );
};

// From components/modals/ModalBase.tsx
const ModalBase: React.FC<{ isOpen: boolean; onClose: () => void; children: React.ReactNode; ariaLabel: string; }> = ({ isOpen, onClose, children, ariaLabel }) => {
    if (!isOpen) return null;
    return (
        <div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" onClick={onClose} role="dialog" aria-modal="true" aria-label={ariaLabel}>
            <div className="bg-[#F8F0E3] text-[#4A2E2C] rounded-2xl shadow-xl w-full max-w-sm animate-fade-in" onClick={(e) => e.stopPropagation()}>
                {children}
            </div>
        </div>
    );
};

// From components/modals/ConfirmationModal.tsx
const ConfirmationModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  onConfirm: () => void;
  title: string;
  message: string;
}> = ({ isOpen, onClose, onConfirm, title, message }) => {
    return (
        <ModalBase isOpen={isOpen} onClose={onClose} ariaLabel={title}>
            <div className="p-6 flex flex-col gap-4 text-center">
                <h2 className="text-2xl font-bold text-[#C85A48]">{title}</h2>
                <p className="text-md">{message}</p>
                <div className="flex gap-4 mt-4">
                    <button 
                        onClick={() => { playSound('click'); onClose(); }} 
                        className="flex-1 bg-gray-400 hover:bg-gray-500 text-white font-bold py-2 px-4 rounded-lg shadow-md active:scale-95"
                    >
                        Cancel
                    </button>
                    <button 
                        onClick={() => { playSound('incorrect'); onConfirm(); }} 
                        className="flex-1 bg-[#C85A48] hover:bg-red-800 text-white font-bold py-2 px-4 rounded-lg shadow-md active:scale-95"
                    >
                        Confirm
                    </button>
                </div>
            </div>
        </ModalBase>
    );
};

// From components/ui/StatCard.tsx
const StatCard: React.FC<{ label: string; value: number | string }> = ({ label, value }) => (
  <div className="bg-[#EFE5D8] p-1 rounded-lg shadow-md text-center">
    <p className="text-xl font-bold text-[#C85A48]">{value}</p>
    <p className="text-xs text-gray-600 font-semibold">{label}</p>
  </div>
);

// From components/ProfileScreen.tsx
const ProfileScreen: React.FC<{ stats: PlayerStats; onClose: () => void; }> = ({ stats, onClose }) => {
    const [sharingId, setSharingId] = useState<string | null>(null);
    const [isResetModalOpen, setIsResetModalOpen] = useState(false);

    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} Rivayaat in ${timeString}. Join me in this challenge ${link}`;

        try {
            if (navigator.share) {
                await navigator.share({ title: '4 Picture 1 Rivayat 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);
    };

    const handleResetProgress = () => {
        localStorage.removeItem(PLAYER_STATS_KEY);
        localStorage.removeItem(GAME_STATE_KEY);
        window.location.reload();
    };

    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-[#C85A48]">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="grid grid-cols-5 gap-1">
                    <StatCard label="Activities Solved" value={stats.completedLevelIds.length} />
                    <StatCard label="Perfect Levels" value={stats.levelsCompletedWithFullStars || 0} />
                    <StatCard label="Hints Used" value={stats.totalHintsUsed} />
                    <StatCard label="Answers Revealed" value={stats.totalAnswersRevealed || 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-[#EFE5D8] 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-[#F8F0E3] 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-[#C85A48] text-white rounded-full flex items-center justify-center transition-colors hover:bg-red-700 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 className="mt-auto pt-2 flex-shrink-0">
                <button
                    onClick={() => { playSound('click'); setIsResetModalOpen(true); }}
                    className="w-full text-center text-sm text-red-600 hover:underline py-2"
                >
                    Reset All Progress
                </button>
            </div>

            <ConfirmationModal
                isOpen={isResetModalOpen}
                onClose={() => setIsResetModalOpen(false)}
                onConfirm={handleResetProgress}
                title="Reset Progress?"
                message="Are you sure you want to reset all your progress? This action cannot be undone."
            />
        </div>
    );
};

// From components/ui/ImageWithLoader.tsx
const imageCache = new Set<string>();
const ImageWithLoader: React.FC<{ 
  src: string; 
  alt: string; 
  onClick: () => void;
  ariaLabel: string;
}> = ({ src, alt, onClick, ariaLabel }) => {
  const [isLoaded, setIsLoaded] = useState(imageCache.has(src));

  useEffect(() => {
    if (imageCache.has(src)) {
      setIsLoaded(true);
      return;
    }

    let isMounted = true;
    const img = new Image();
    img.src = src;
    img.onload = () => {
      if (isMounted) {
        setIsLoaded(true);
        imageCache.add(src);
      }
    };
    
    return () => {
      isMounted = false;
    };
  }, [src]);

  return (
    <button
      onClick={onClick}
      className="rounded-lg overflow-hidden shadow-lg transition-transform duration-200 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-[#C85A48] relative w-full h-full"
      aria-label={ariaLabel}
    >
      {!isLoaded && (
        <div className="absolute inset-0 bg-[#EFE5D8] animate-pulse"></div>
      )}
      <img 
        src={src} 
        alt={alt} 
        className={`w-full h-full object-cover transition-opacity duration-500 ${isLoaded ? 'opacity-100' : 'opacity-0'}`}
        aria-hidden={!isLoaded} 
      />
    </button>
  );
};

// From components/ImageGrid.tsx
const ImageGrid: React.FC<{ images: string[], onImageClick: (url: string) => void }> = ({ images, onImageClick }) => (
  <div className="w-full max-w-sm aspect-square grid grid-cols-2 grid-rows-2 gap-2">
    {images.map((src, index) => (
      <ImageWithLoader
        key={index}
        src={src}
        alt={`Hint image ${index + 1}`}
        onClick={() => onImageClick(src)}
        ariaLabel={`Zoom hint image ${index + 1}`}
      />
    ))}
  </div>
);

// From components/modals/CorrectAnswerModal.tsx
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-[#F8F0E3] z-50 flex flex-col items-center justify-center p-4 text-[#4A2E2C]">
            <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">
                    <ImageGrid images={level.images} onImageClick={() => {}} />
                </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>
                 <button onClick={() => { playSound('click'); onContinue(); }} className="w-full max-w-xs bg-[#C85A48] hover:bg-red-800 text-white font-bold py-3 px-4 rounded-lg transition-transform duration-300 shadow-lg active:scale-95 hover:scale-105">
                    Continue
                </button>
            </div>
        </div>
    );
};

// From components/modals/HintModal.tsx
const HintModal: React.FC<{ isOpen: boolean; onClose: () => void; hintText: string; }> = ({ isOpen, onClose, hintText }) => (
    <ModalBase isOpen={isOpen} onClose={() => { playSound('click'); onClose(); }} ariaLabel="Game Hint">
        <div className="p-6 flex flex-col gap-4 text-center">
            <h2 className="text-2xl font-bold text-[#C85A48]">Hint</h2>
            <p className="text-lg">{hintText}</p>
            <button onClick={() => { playSound('click'); onClose(); }} className="mt-4 bg-[#C85A48] hover:bg-red-800 text-white font-bold py-2 px-4 rounded-lg shadow-md active:scale-95">
                Got it!
            </button>
        </div>
    </ModalBase>
);

// From components/modals/ImageZoomModal.tsx
const ImageZoomModal: React.FC<{ isOpen: boolean; imageUrl: string | null; onClose: () => void; }> = ({ isOpen, imageUrl, onClose }) => {
    if (!isOpen || !imageUrl) return null;
    return (
        <div className="fixed inset-0 bg-black/80 z-[60] flex items-center justify-center p-4" onClick={() => { playSound('click'); onClose(); }} role="dialog" aria-modal="true" aria-label="Zoomed Image">
            <div className="relative w-full max-w-sm bg-white p-2 rounded-lg shadow-xl animate-fade-in" onClick={(e) => e.stopPropagation()}>
                <button onClick={() => { playSound('click'); onClose(); }} className="absolute -top-3 -right-3 w-8 h-8 bg-white rounded-full flex items-center justify-center text-2xl font-bold z-10 border-2 border-[#4A2E2C]" aria-label="Close">
                    &times;
                </button>
                <img src={imageUrl} alt="Zoomed hint" className="w-full h-auto rounded-md" />
            </div>
        </div>
    );
};

// From components/GameBoard.tsx
const RevealAnswerModal: React.FC<{ isOpen: boolean; onClose: () => void; onShare: () => void; shareCount: number; }> = ({ isOpen, onClose, onShare, shareCount }) => {
    if (!isOpen) return null;
    return (
        <ModalBase isOpen={isOpen} onClose={onClose} ariaLabel="Reveal Answer by Sharing">
            <div className="p-6 flex flex-col gap-4 text-center">
                <h2 className="text-2xl font-bold text-[#C85A48]">Reveal Answer</h2>
                <p className="text-md">To instantly solve this level, please share the activity with 3 friends on WhatsApp.</p>
                <div className="my-2">
                    <p className="text-lg font-bold">Progress: <span className="text-[#C85A48]">{shareCount} / 3</span> Shares</p>
                </div>
                <button 
                    onClick={onShare} 
                    className="mt-2 bg-[#25D366] hover:bg-green-600 text-white font-bold py-3 px-4 rounded-lg shadow-md active:scale-95 flex items-center justify-center gap-2"
                >
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" viewBox="0 0 24 24" fill="currentColor"><path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.487 5.235 3.487 8.413 0 6.557-5.338 11.892-11.894 11.892-1.99 0-3.903-.52-5.687-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.885-.001 2.225.651 4.315 1.731 6.086l.06.105-1.037 3.777 3.879-1.017.129.075z" /></svg>
                    <span>Share on WhatsApp ({Math.min(shareCount + 1, 3)}/3)</span>
                </button>
                 <button onClick={onClose} className="text-sm text-gray-600 hover:underline mt-2">Cancel</button>
            </div>
        </ModalBase>
    );
};
const GameOverModal: React.FC<{ isOpen: boolean; onTryAgain: () => void; }> = ({ isOpen, onTryAgain }) => {
    return (
        <ModalBase isOpen={isOpen} onClose={() => {}} ariaLabel="Game Over">
            <div className="p-6 flex flex-col gap-4 text-center items-center">
                <h2 className="text-2xl font-bold text-red-600">Out of Lives!</h2>
                <p className="text-md">Don't worry, you can try again.</p>
                <button 
                    onClick={onTryAgain} 
                    className="mt-4 bg-[#C85A48] hover:bg-red-800 text-white font-bold py-3 px-4 rounded-lg shadow-md active:scale-95 w-full max-w-xs"
                >
                    Try Again
                </button>
            </div>
        </ModalBase>
    );
}
const GameBoard: React.FC<{ level: GameLevel, onLevelComplete: (livesRemaining: number, isFirstAttempt: boolean) => void, onHintUsed: () => void, onAnswerRevealed: () => void }> = ({ level, onLevelComplete, onHintUsed, onAnswerRevealed }) => {
  const answerForLogic = useMemo(() => level.answer.replace(/\s/g, '').replace(/[\u064B-\u0652\u0670]/g, ''), [level.answer]);
  const uniqueAnswerLetters = useMemo(() => new Set(answerForLogic.split('')), [answerForLogic]);
  const [lives, setLives] = useState(3);
  const [guessedLetters, setGuessedLetters] = useState<Set<string>>(new Set());
  const [gameStatus, setGameStatus] = useState<'playing' | 'won' | 'lost'>('playing');
  const [hasTriedAgain, setHasTriedAgain] = useState(false);
  const [showHintModal, setShowHintModal] = useState(false);
  const [zoomedImage, setZoomedImage] = useState<string | null>(null);
  const [isSharing, setIsSharing] = useState(false);
  const [timeOnLevel, setTimeOnLevel] = useState(0);
  const [isRevealAnswerEnabled, setIsRevealAnswerEnabled] = useState(false);
  const [showRevealModal, setShowRevealModal] = useState(false);
  const [shareCountForReveal, setShareCountForReveal] = useState(0);
  const isRTL = /[\u0600-\u06FF]/.test(level.answer);

  useEffect(() => {
    const savedStateRaw = localStorage.getItem(GAME_STATE_KEY);
    if (savedStateRaw) {
      try {
        const savedState: SavedGameState = JSON.parse(savedStateRaw);
        if (savedState.levelId === level.id) {
          setLives(savedState.lives);
          setGuessedLetters(new Set(savedState.guessedLetters));
        }
      } catch (e) { 
          console.error("Failed to parse saved game state:", e);
          localStorage.removeItem(GAME_STATE_KEY);
      }
    }
  }, [level.id]);

  useEffect(() => {
    if (gameStatus === 'playing') {
      const stateToSave: SavedGameState = { levelId: level.id, lives, guessedLetters: Array.from(guessedLetters) };
      localStorage.setItem(GAME_STATE_KEY, JSON.stringify(stateToSave));
    }
  }, [lives, guessedLetters, level.id, gameStatus]);

  useEffect(() => {
    if (gameStatus !== 'playing') return;
    const allLettersGuessed = [...uniqueAnswerLetters].every(letter => guessedLetters.has(letter));
    if (allLettersGuessed) {
        playSound('correct');
        setGameStatus('won');
    } else if (lives <= 0) {
        playSound('incorrect');
        setGameStatus('lost');
    }
  }, [guessedLetters, lives, gameStatus, uniqueAnswerLetters]);
  
  useEffect(() => {
    if (gameStatus !== 'playing') return;
    const interval = setInterval(() => {
      setTimeOnLevel(prevTime => {
        const newTime = prevTime + 1;
        if (newTime >= 120 && !isRevealAnswerEnabled) {
          setIsRevealAnswerEnabled(true);
        }
        return newTime;
      });
    }, 1000);
    return () => clearInterval(interval);
  }, [gameStatus, isRevealAnswerEnabled]);

    useEffect(() => {
        if (shareCountForReveal >= 3) {
            setShowRevealModal(false);
            onAnswerRevealed();
            setGameStatus('won');
        }
    }, [shareCountForReveal, onAnswerRevealed]);

  const resetLevel = () => {
      playSound('click');
      setLives(3);
      setGuessedLetters(new Set());
      setGameStatus('playing');
      setTimeOnLevel(0);
      setIsRevealAnswerEnabled(false);
      localStorage.removeItem(GAME_STATE_KEY);
      setHasTriedAgain(true);
  }

  const handleKeyboardClick = (letter: string) => {
    if (gameStatus !== 'playing' || guessedLetters.has(letter)) return;
    
    const newGuessedLetters = new Set(guessedLetters);
    newGuessedLetters.add(letter);
    setGuessedLetters(newGuessedLetters);

    if (uniqueAnswerLetters.has(letter)) {
      playSound('place');
    } else {
      playSound('incorrect');
      setLives(prev => prev - 1);
    }
  };

  const handleHintClick = () => {
    if (gameStatus !== 'playing') return;
    playSound('hint');
    onHintUsed();
    setShowHintModal(true);
  };
  
  const handleImageClick = (imageUrl: string) => {
    playSound('click');
    setZoomedImage(imageUrl);
  };
  
  const createShareText = () => `Mane aa rivayat solve karwama madad kari sako cho?\n\nHint: ${level.hint || 'No hint available'}\nLetters: ${level.letters.join(', ')}\nAnswer length: ${answerForLogic.length} letters\n\nAap bhi shamil thaiye aa activity ma: ${window.location.href}`;
  
  const handleAskFriend = async () => {
    if (isSharing) return;
    setIsSharing(true);
    playSound('click');
    try {
      const shareText = createShareText();
      if (navigator.share) await navigator.share({ title: 'Help me solve this Rivayat!', 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 handleShareForReveal = () => {
        const shareUrl = window.location.href;
        const shareText = `Salam, 4 Picture 1 Rivayat ni activity zaroor try karjo. Ekdum maza aavse. aa link par jaiye ${shareUrl}`;
        const whatsappUrl = `https://wa.me/?text=${encodeURIComponent(shareText)}`;
        window.open(whatsappUrl, '_blank');
        setShareCountForReveal(prev => prev + 1);
    };

  const answerLength = answerForLogic.length;
  let boxSizeClass = 'w-10 h-10 text-xl';
  if (answerLength > 16) boxSizeClass = 'w-7 h-7 text-base';
  else if (answerLength > 12) boxSizeClass = 'w-8 h-8 text-lg';
  
  const words = level.answer.split(' ');

  return (
    <div className="flex-grow flex flex-col gap-2 items-center w-full">
      <CorrectAnswerModal isOpen={gameStatus === 'won'} level={level} onContinue={() => onLevelComplete(lives, !hasTriedAgain)} />
      <GameOverModal isOpen={gameStatus === 'lost'} onTryAgain={resetLevel} />
      <HintModal isOpen={showHintModal} onClose={() => setShowHintModal(false)} hintText={level.hint || "No hint available."} />
      <ImageZoomModal isOpen={!!zoomedImage} imageUrl={zoomedImage} onClose={() => setZoomedImage(null)} />
      <RevealAnswerModal isOpen={showRevealModal} onClose={() => { setShowRevealModal(false); setShareCountForReveal(0); }} onShare={handleShareForReveal} shareCount={shareCountForReveal} />

      <div className="w-full flex-grow flex flex-col items-center justify-center">
          <ImageGrid images={level.images} onImageClick={handleImageClick} />
      </div>

      <div className="w-full flex flex-col items-center gap-3 flex-shrink-0">
        <div className="flex justify-center gap-2 my-2">
            {[...Array(3)].map((_, i) => <StarIcon key={i} filled={i < lives} />)}
        </div>
        <div className="flex flex-col items-center gap-y-2 px-1 max-w-full">
          {words.map((word, wordIndex) => {
            const sanitizedWord = word.replace(/[\u064B-\u0652\u0670]/g, '');
            if (sanitizedWord.length === 0) return null;
            return (
              <div key={`word-${wordIndex}`} className="flex items-center gap-x-1" style={{ direction: isRTL ? 'rtl' : 'ltr' }}>
                {sanitizedWord.split('').map((char, letterInWordIndex) => {
                  const isRevealed = guessedLetters.has(char);
                  return (
                    <div key={letterInWordIndex} className={`${boxSizeClass} flex items-center justify-center font-bold uppercase transition-colors border-b-4 border-gray-500`}>
                      {isRevealed && <span className="inline-block animate-fade-in">{char}</span>}
                    </div>
                  );
                })}
              </div>
            );
          })}
        </div>
          <div className="w-full max-w-sm flex flex-col gap-2">
            <div className="flex w-full gap-2 text-white font-bold text-sm">
                 <button onClick={handleHintClick} disabled={gameStatus !== 'playing'} className="flex-1 bg-[#C85A48] hover:bg-red-800 py-2 px-2 rounded-lg transition-all duration-300 shadow-md active:scale-95 disabled:bg-gray-400">Hint</button>
                 <button onClick={handleAskFriend} disabled={isSharing || gameStatus !== 'playing'} className="flex-1 bg-[#5A8C8C] hover:bg-teal-700 py-2 px-2 rounded-lg transition-all duration-300 shadow-md active:scale-95 disabled:bg-gray-400 disabled:cursor-not-allowed">{isSharing ? '...' : 'Ask Friend'}</button>
                 <button onClick={() => { playSound('click'); setShowRevealModal(true); }} disabled={!isRevealAnswerEnabled || gameStatus !== 'playing'} className="flex-1 bg-green-700 hover:bg-green-800 py-2 px-2 rounded-lg transition-all duration-300 shadow-md active:scale-95 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1">
                    {isRevealAnswerEnabled ? 'Reveal Answer' : (
                        <>
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor"><path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.414-1.414L11 10.586V6z" clipRule="evenodd" /></svg>
                            <span>{formatSecondsToTime(Math.max(0, 120 - timeOnLevel))}</span>
                        </>
                    )}
                 </button>
            </div>
          </div>
          <div className="w-full max-w-sm grid grid-cols-6 gap-2">
            {level.letters.map((letter, id) => {
              const isGuessed = guessedLetters.has(letter);
              const isCorrect = uniqueAnswerLetters.has(letter);
              
              let buttonClass = "bg-[#C85A48] border-red-800 hover:bg-red-700";
              if (isGuessed) {
                  buttonClass = isCorrect ? "bg-green-600 border-green-800" : "bg-red-600 border-red-800 opacity-70";
              }

              return (
              <button
                key={id}
                onClick={() => handleKeyboardClick(letter)}
                disabled={isGuessed}
                className={`h-11 text-white rounded-md text-2xl font-bold flex items-center justify-center transition-all duration-200 shadow-md border-b-4 active:scale-95 disabled:cursor-not-allowed ${buttonClass}`}
              >
                {letter}
              </button>
            )})}
          </div>
      </div>
    </div>
  );
};

// From components/modals/AchievementModal.tsx
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} Rivayaat in ${timeString}. Join me in this challenge ${link}`;
    
    try {
        if (navigator.share) {
            await navigator.share({ title: '4 Picture 1 Rivayat 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-[#F8F0E3] text-[#4A2E2C] 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-[#C85A48]">{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-[#5A8C8C] hover:bg-teal-700 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-[#C85A48] hover:bg-red-800 text-white font-bold py-3 px-4 rounded-lg transition-all duration-300 shadow-lg active:scale-95"
            >
                Continue
            </button>
        </div>
      </div>
    </div>
  );
};

// From components/MubarakMohannaScreen.tsx
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-[#C85A48] mb-2 font-['Amiri']">Mubarak Mohanna</h1>
                <p className="text-lg">Aap 25 Levels paar kari chuka cho</p>
            </div>

            <button
                onClick={() => {
                    playSound('click');
                    window.location.href = 'https://rzp.io/rzp/103levels';
                }}
                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 103 Levels now
            </button>
        </div>
    );
};

// From components/AdsenseAd.tsx
declare global {
  interface Window {
    adsbygoogle: any[];
  }
}
const AdsenseAd: React.FC = () => {
  const adContainerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const adContainer = adContainerRef.current;
    if (!adContainer) return;
    adContainer.innerHTML = ''; 
    const ins = document.createElement('ins');
    ins.className = 'adsbygoogle';
    ins.style.display = 'block';
    ins.style.width = '100%';
    ins.setAttribute('data-ad-client', 'ca-pub-1678247058695040');
    ins.setAttribute('data-ad-slot', '9843279854');
    ins.setAttribute('data-ad-format', 'auto');
    ins.setAttribute('data-full-width-responsive', 'true');
    adContainer.appendChild(ins);
    const observer = new ResizeObserver(entries => {
      if (entries[0].contentRect.width > 0) {
        try {
          (window.adsbygoogle = window.adsbygoogle || []).push({});
        } catch (e) {
          console.error('Adsense error:', e);
        }
        observer.disconnect();
      }
    });
    observer.observe(adContainer);
    return () => {
      observer.disconnect();
    };
  }, []);

  return (
    <div
      ref={adContainerRef}
      className="w-full flex justify-center my-2 flex-shrink-0 min-h-[90px] bg-[#EFE5D8]"
      aria-hidden="true"
    ></div>
  );
};

// From components/SplashScreen.tsx
const FeatureCard: React.FC<{ icon: string; title: string; description: string }> = ({ icon, title, description }) => (
    <div className="text-center">
        <span className="text-3xl">{icon}</span>
        <h3 className="font-bold text-sm mt-1 text-[#C85A48]">{title}</h3>
        <p className="text-xs text-gray-700">{description}</p>
    </div>
);
const SplashScreen: React.FC<{ onStart: () => void }> = ({ onStart }) => {
    return (
        <div className="flex-grow flex flex-col h-full justify-between items-center text-center animate-fade-in p-4 gap-2">
            <div className="w-full">
                <h1 className="text-4xl font-bold text-[#4A2E2C] font-['Amiri'] tracking-wide">4 Picture 1 Rivayat</h1>
                <p className="text-lg mt-1 text-[#C85A48]">Chalo 103 Rivayat Seekhye</p>
            </div>
            <div className="w-full max-w-md text-left p-3 bg-[#EFE5D8] rounded-lg shadow-inner">
                <h2 className="text-lg font-bold mb-2 text-center">How to Play</h2>
                <ol className="list-decimal list-inside space-y-1 text-gray-800 text-center text-sm">
                    <li>Look at the 4 pictures for clues.</li>
                    <li>Guess the Rivayat (story) they represent.</li>
                    <li>Use the letters below to spell the answer.</li>
                </ol>
            </div>
             <div className="w-full max-w-md">
                <h2 className="text-lg font-bold mb-2 text-center">Features</h2>
                 <div className="grid grid-cols-2 gap-4">
                    <FeatureCard icon="❤️" title="3 Lives" description="3 chances per level. Solve on your first try with all 3 to earn a Perfect Level!" />
                    <FeatureCard icon="💡" title="Hints" description="Get a written clue" />
                    <FeatureCard icon="👥" title="Ask Friends" description="Share for help" />
                    <FeatureCard icon="🔑" title="Reveal" description="Unlock the answer" />
                 </div>
            </div>
            <button
                onClick={() => { playSound('click'); onStart(); }}
                className="w-full max-w-sm bg-[#C85A48] hover:bg-red-800 text-white font-bold py-3 px-4 rounded-lg transition-transform duration-300 shadow-lg active:scale-95 hover:scale-105"
            >
                Start مع التوفيق
            </button>
        </div>
    );
};

// From components/EndScreen.tsx
const EndScreen: React.FC<{ stats: PlayerStats; onPlayAgain: () => void; }> = ({ stats, onPlayAgain }) => {
    const trophyAchievement = ACHIEVEMENTS.find(a => a.id === 'ustaad');
    
    const handleShare = async () => {
        playSound('click');
        const timeString = formatSecondsToTime(stats.totalPlayTimeSeconds || 0);
        const link = window.location.href;
        const message = `Alhamdullilah! I have completed all ${TOTAL_LEVEL_COUNT} levels in 4 Picture 1 Rivayat. My total play time was ${timeString}. You should play too! ${link}`;
        try {
            if (navigator.share) {
                await navigator.share({ title: '4 Picture 1 Rivayat Completed!', text: message });
            } else {
                alert('Sharing not supported on this device.');
            }
        } catch (error) {
            console.error('Failed to share:', error);
        }
    };
    
    return (
         <div className="flex-grow flex flex-col h-full justify-center items-center text-center animate-fade-in p-4 gap-6">
            <div>
                <span className="text-8xl">{trophyAchievement ? trophyAchievement.icon : '🏆'}</span>
                <h1 className="text-4xl font-bold text-[#C85A48] mt-4">Mubarak!</h1>
                <p className="text-lg text-gray-700 mt-2">{`You have completed all ${TOTAL_LEVEL_COUNT} Rivayaat.`}</p>
            </div>
            <div className="grid grid-cols-2 gap-2 w-full max-w-xs">
                 <StatCard label="Activities Solved" value={stats.completedLevelIds.length} />
                 <StatCard label="Perfect Levels" value={stats.levelsCompletedWithFullStars || 0} />
                 <StatCard label="Play Time" value={formatSecondsToTime(stats.totalPlayTimeSeconds || 0)} />
                 <StatCard label="Hints Used" value={stats.totalHintsUsed} />
            </div>
            <div className="w-full max-w-sm flex flex-col gap-3 mt-4">
                 <button onClick={handleShare} className="w-full bg-[#5A8C8C] hover:bg-teal-700 text-white font-bold py-3 px-4 rounded-lg transition-all duration-300 shadow-md active:scale-95 flex items-center justify-center gap-2">
                    <ShareIcon />
                    <span>Share Your Accomplishment</span>
                 </button>
                 <button onClick={onPlayAgain} className="w-full bg-[#C85A48] hover:bg-red-800 text-white font-bold py-3 px-4 rounded-lg transition-all duration-300 shadow-lg active:scale-95">
                    Play Again
                 </button>
            </div>
        </div>
    );
};

// From App.tsx
type Screen = 'splash' | 'level_select' | 'playing' | 'profile' | 'unlock' | 'end_screen';

const App: React.FC = () => {
  const [screen, setScreen] = useState<Screen>('splash');
  const [currentLevel, setCurrentLevel] = useState<GameLevel | null>(null);
  const { stats, completeLevel, useHint, useAnswerReveal, newlyUnlocked, clearNewlyUnlocked, addPlayTime, unlockFullGame } = usePlayerStats();
  const [achievementQueue, setAchievementQueue] = useState<Achievement[]>([]);
  const playTimeIntervalRef = useRef<number | null>(null);

  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const shouldUnlock = urlParams.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 > 25 && !stats.hasUnlockedFullGame;
                const highestUnlockedLevel = stats.completedLevelIds.length + 2;
                if (!isBeyondPaywall && nextLevel.id < highestUnlockedLevel) {
                    preloadImages(nextLevel.images).catch(err => {
                        console.warn("Failed to preload next level images:", err);
                    });
                }
          }
      }
  }, [currentLevel, stats.completedLevelIds, stats.hasUnlockedFullGame]);


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

  useEffect(() => {
    if (screen === 'splash') {
        const savedStateRaw = localStorage.getItem(GAME_STATE_KEY);
        if (savedStateRaw) {
          try {
            const { levelId } = JSON.parse(savedStateRaw);
            const levelToLoad = LEVELS.find(l => l.id === levelId);
            const highestUnlockedLevel = stats.completedLevelIds.length + 1;
            const isPastPaywall = levelToLoad && levelToLoad.id > 25 && !stats.hasUnlockedFullGame;
    
            if (levelToLoad && levelToLoad.id <= highestUnlockedLevel && !isPastPaywall) {
              setCurrentLevel(levelToLoad);
              setScreen('playing');
            } else {
              localStorage.removeItem(GAME_STATE_KEY);
            }
          } catch (e) {
            console.error("Failed to parse saved game state:", e);
            localStorage.removeItem(GAME_STATE_KEY);
          }
        }
    }
  }, [screen, stats.completedLevelIds.length, stats.hasUnlockedFullGame]);
  
  const handleLevelSelect = (level: GameLevel) => {
    playSound('click');
    setCurrentLevel(level);
    setScreen('playing');
  };
  
  const handleBackToMenu = () => {
    playSound('click');
    setCurrentLevel(null);
    setScreen('level_select');
    localStorage.removeItem(GAME_STATE_KEY);
  };

  const handleLevelComplete = (livesRemaining: number, isFirstAttempt: boolean) => {
    if (currentLevel) {
      completeLevel(currentLevel.id, livesRemaining, isFirstAttempt);
      localStorage.removeItem(GAME_STATE_KEY);
      
      if ((stats.completedLevelIds.length + 1) >= TOTAL_LEVEL_COUNT) {
          setScreen('end_screen');
          return;
      }

      if (currentLevel.id === 25 && !stats.hasUnlockedFullGame) {
        setScreen('unlock');
        return;
      }
      
      const nextLevel = LEVELS.find(level => level.id === currentLevel.id + 1);
      const highestUnlockedLevel = stats.completedLevelIds.length + 2; 

      if (nextLevel && nextLevel.id <= highestUnlockedLevel && nextLevel.answer !== "قادم") {
        setCurrentLevel(nextLevel);
      } else {
        handleBackToMenu();
      }
    }
  };
  
  const handleAskUs = () => {
    playSound('click');
    const phoneNumber = '917304017253';
    const message = "Salam Jameel. Ek query che";
    const whatsappUrl = `https://wa.me/${phoneNumber}?text=${encodeURIComponent(message)}`;
    window.open(whatsappUrl, '_blank');
  };

  const renderScreen = () => {
    switch(screen) {
      case 'splash':
        return <SplashScreen onStart={() => setScreen('level_select')} />;
      case 'end_screen':
        return <EndScreen stats={stats} onPlayAgain={handleBackToMenu} />;
      case 'unlock':
        return <MubarakMohannaScreen 
          onBack={handleBackToMenu}
        />;
      case 'profile':
        return <ProfileScreen stats={stats} onClose={() => setScreen('level_select')} />;
      case 'playing':
        return currentLevel ? (
          <div className="flex-grow flex flex-col animate-fade-in">
            <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">
                    <FullScreenToggle />
                    <button onClick={handleAskUs} aria-label="Ask Us" className="px-3 py-1 text-sm font-bold text-[#C85A48] border-2 border-[#C85A48] rounded-lg hover:bg-[#C85A48] hover:text-[#F8F0E3] transition-colors duration-200 active:scale-95">
                        Ask Us
                    </button>
                </div>
            </header>
            <main className="flex-grow flex flex-col relative">
              <GameBoard 
                key={currentLevel.id} 
                level={currentLevel} 
                onLevelComplete={handleLevelComplete}
                onHintUsed={useHint}
                onAnswerRevealed={useAnswerReveal}
              />
            </main>
          </div>
        ) : null;
      case 'level_select':
      default:
        return (
          <LevelSelect 
            levels={LEVELS} 
            onSelectLevel={handleLevelSelect} 
            playerStats={stats}
            onShowProfile={() => setScreen('profile')}
          />
        );
    }
  }

  return (
    <div className="max-w-sm mx-auto min-h-screen bg-[#F8F0E3] text-[#4A2E2C] flex flex-col px-3 pt-2 pb-3 shadow-2xl overflow-hidden">
      {renderScreen()}
      {(screen === 'level_select' || screen === 'profile') && <AdsenseAd />}
      {achievementQueue.length > 0 && (
          <AchievementModal
              achievement={achievementQueue[0]}
              stats={stats}
              onDismiss={() => setAchievementQueue(q => q.slice(1))}
          />
      )}
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);