(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,15149,85929,24550,50288,88093,e=>{"use strict";var a=e.i(99901),t=e.i(95849);let o={"United States":"US","United Kingdom":"GB",China:"CN",India:"IN",Brazil:"BR",Russia:"RU",Japan:"JP",Germany:"DE",France:"FR",Italy:"IT",Spain:"ES",Canada:"CA",Australia:"AU",Mexico:"MX","South Korea":"KR",Netherlands:"NL",Turkey:"TR","Saudi Arabia":"SA",Argentina:"AR","South Africa":"ZA",Indonesia:"ID",Thailand:"TH",Nigeria:"NG",Egypt:"EG",Poland:"PL",Ukraine:"UA",Malaysia:"MY",Philippines:"PH",Vietnam:"VN",Bangladesh:"BD",Pakistan:"PK",Iran:"IR",Iraq:"IQ",Israel:"IL",Chile:"CL",Colombia:"CO",Peru:"PE",Venezuela:"VE",Ecuador:"EC",Bolivia:"BO",Paraguay:"PY",Uruguay:"UY",Guyana:"GY",Suriname:"SR",Ethiopia:"ET",Kenya:"KE",Tanzania:"TZ",Uganda:"UG",Rwanda:"RW",Burundi:"BI",Somalia:"SO",Sudan:"SD","South Sudan":"SS",Chad:"TD","Central African Republic":"CF",Cameroon:"CM",Ghana:"GH","Ivory Coast":"CI",Senegal:"SN",Mali:"ML","Burkina Faso":"BF",Niger:"NE",Guinea:"GN","Sierra Leone":"SL",Liberia:"LR",Benin:"BJ",Togo:"TG",Gabon:"GA","Republic of the Congo":"CG","DR Congo":"CD",Angola:"AO",Zambia:"ZM",Zimbabwe:"ZW",Botswana:"BW",Namibia:"NA",Mozambique:"MZ",Madagascar:"MG",Mauritius:"MU",Seychelles:"SC",Comoros:"KM",Malawi:"MW",Swaziland:"SZ",Eswatini:"SZ",Lesotho:"LS",Algeria:"DZ",Morocco:"MA",Mauritania:"MR",Tunisia:"TN",Libya:"LY",Norway:"NO",Sweden:"SE",Finland:"FI",Denmark:"DK",Iceland:"IS",Switzerland:"CH",Austria:"AT",Belgium:"BE",Luxembourg:"LU",Portugal:"PT",Greece:"GR",Cyprus:"CY",Malta:"MT",Ireland:"IE","Czech Republic":"CZ",Slovakia:"SK",Hungary:"HU",Slovenia:"SI",Croatia:"HR","Bosnia and Herzegovina":"BA",Serbia:"RS",Montenegro:"ME","North Macedonia":"MK",Albania:"AL",Bulgaria:"BG",Romania:"RO",Moldova:"MD",Belarus:"BY",Lithuania:"LT",Latvia:"LV",Estonia:"EE",Georgia:"GE",Armenia:"AM",Azerbaijan:"AZ",Kazakhstan:"KZ",Kyrgyzstan:"KG",Tajikistan:"TJ",Turkmenistan:"TM",Uzbekistan:"UZ",Afghanistan:"AF",Mongolia:"MN","North Korea":"KP",Myanmar:"MM",Laos:"LA",Cambodia:"KH","Sri Lanka":"LK",Maldives:"MV",Bhutan:"BT",Nepal:"NP",Syria:"SY",Lebanon:"LB",Jordan:"JO",Kuwait:"KW",Qatar:"QA","United Arab Emirates":"AE",Oman:"OM",Yemen:"YE",Bahrain:"BH","New Zealand":"NZ","Papua New Guinea":"PG",Fiji:"FJ","Solomon Islands":"SB",Vanuatu:"VU",Samoa:"WS",Tonga:"TO",Kiribati:"KI",Tuvalu:"TV",Nauru:"NR",Palau:"PW","Marshall Islands":"MH",Micronesia:"FM",Cuba:"CU",Haiti:"HT","Dominican Republic":"DO",Jamaica:"JM","Trinidad and Tobago":"TT",Barbados:"BB",Bahamas:"BS",Belize:"BZ","Costa Rica":"CR",Guatemala:"GT",Honduras:"HN","El Salvador":"SV",Nicaragua:"NI",Panama:"PA",Grenada:"GD","Saint Vincent and the Grenadines":"VC","Saint Lucia":"LC",Dominica:"DM","Antigua and Barbuda":"AG","Saint Kitts and Nevis":"KN",Monaco:"MC","San Marino":"SM","Vatican City":"VA",Liechtenstein:"LI",Andorra:"AD","Guinea-Bissau":"GW","Cape Verde":"CV","Sao Tome and Principe":"ST","Equatorial Guinea":"GQ",Djibouti:"DJ",Eritrea:"ER",Gambia:"GM",Brunei:"BN","Timor-Leste":"TL","East Timor":"TL",Palestine:"PS",Kosovo:"XK",Singapore:"SG"};function r(e){if(o[e])return o[e];let a=e.toLowerCase();return a.includes("united states")||a.includes("usa")?"US":a.includes("united kingdom")||a.includes("uk")?"GB":a.includes("south korea")?"KR":a.includes("north korea")?"KP":a.includes("south africa")?"ZA":a.includes("ivory coast")?"CI":a.includes("dr congo")||a.includes("democratic republic")?"CD":a.includes("central african")?"CF":a.includes("bosnia")?"BA":a.includes("czech")?"CZ":a.includes("north macedonia")||"macedonia"===a||a.includes("republic of macedonia")||a.includes("macedonia (fyrom)")?"MK":e.toUpperCase().replace(/[^A-Z]/g,"").slice(0,2)||"XX"}function n(e){return 2!==e.length?"🏳️":String.fromCodePoint(...e.toUpperCase().split("").map(e=>127462+e.charCodeAt(0)-65))}e.i(5208);var i=e.i(12074),s=e.i(84148),l=e.i(65298);e.i(20125);var c=e.i(71768),d=e.i(61584);class g{gameMode;static VERSION=12;static cache={};static clearCache(){Object.keys(this.cache).forEach(e=>delete this.cache[e]),console.info("[CSVRankingsLoader] Cache cleared")}rankings;countries;loaded;constructor(e){this.gameMode=e,this.rankings={},this.countries=[],this.loaded=!1}async load(){if(this.loaded)return;let e=this.gameMode,a=g.cache[e];if(a&&a.version===g.VERSION){this.countries=a.countries,this.loaded=!0;return}if("footy-clubs"===this.gameMode){if(!d.supabase)throw Error("Supabase is not configured — Footy Clubs requires a live connection");let a=await (0,c.loadClubModeData)(d.supabase);if(!a||0===a.countries.length)throw Error("Failed to load Footy Clubs data from Supabase");this.countries=a.countries,(0,t.setSupabaseCategories)(this.gameMode,a.categories),(0,t.setSupabaseRankCaps)(this.gameMode,a.rankCaps),this.loaded=!0,g.cache[e]={version:g.VERSION,countries:this.countries};return}let o="world"===this.gameMode?"/data/rankings2.csv":"special"===this.gameMode?"/data/rankingsGH3.csv":"voyage"===this.gameMode?"/data/rankings_voyage.csv":"atlas"===this.gameMode?"/data/rankingsAtlas.csv":"usa"===this.gameMode?"/data/rankingsUSA.csv":"canada"===this.gameMode?"/data/rankings_canada.csv":"europe"===this.gameMode?"/data/rankings_europe.csv":"sports"===this.gameMode?"/data/rankings_sports.csv":"empires"===this.gameMode?"/data/rankings_empires.csv":"world-cup"===this.gameMode?"/data/rankings_world_cup.csv":"world-cup-ko"===this.gameMode?"/data/rankings_world_cup_2.csv":"/data/rankings.csv";if(d.supabase)try{let a=await Promise.race([(0,c.loadGameModeData)(this.gameMode,d.supabase),new Promise(e=>setTimeout(()=>e(null),1500))]);if(a&&a.countries.length>0){console.log(`[CSVRankingsLoader] Loaded ${this.gameMode} from Supabase (${a.countries.length} countries)`),this.countries=a.countries,"empires"===this.gameMode&&(this.countries=this.countries.map(e=>({...e,flag:(0,l.getEmpireFlagPath)(e.name)||e.flag,emoji:(0,l.getEmpireEmoji)(e.name)}))),(0,t.setSupabaseCategories)(this.gameMode,a.categories),(0,t.setSupabaseRankCaps)(this.gameMode,a.rankCaps),this.loaded=!0,g.cache[e]={version:g.VERSION,countries:this.countries};return}}catch(e){console.warn(`[CSVRankingsLoader] Supabase failed for ${this.gameMode}, falling back to CSV:`,e)}try{console.log(`[CSVRankingsLoader] Fetching ${o}`);let a=await fetch(o,{cache:"no-cache"});if(!a.ok){let e=await a.text().catch(()=>"Unknown error");throw Error(`Failed to fetch ${o}: ${a.status} ${a.statusText} - ${e}`)}let t=await a.text();if(console.log(`[CSVRankingsLoader] Successfully fetched ${o}, length: ${t.length}`),!t||t.length<100)throw Error(`Invalid CSV data received for ${o} - too short (${t.length} chars)`);this.parse(t),this.loaded=!0,g.cache[e]={version:g.VERSION,countries:this.countries},console.log(`[CSVRankingsLoader] Successfully parsed ${this.countries.length} countries`)}catch(e){throw console.error("[CSVRankingsLoader] CSV load failed:",e),e}}getCountries(){return 0===this.countries.length&&this.loaded&&console.warn("[CSVRankingsLoader] Returning empty countries array - CSV parsing may have failed"),this.countries}parseEurope(e){let a=e.trim().split(/\r?\n/);if(a.length<2)return;let t=a[0].split(",").map(e=>e.trim()).slice(1),o={Population:"population","Cold Temperature":"cold_temperature","Small Size":"small_size","UNESCO Sites":"unesco_sites","Average Height (Men)":"average_height","GDP Per Capita":"gdp_per_capita","Southernmost Capital":"southernmost_capital","Champions League Wins":"champions_league","UCL Goals":"champions_league"};Object.values(o).forEach(e=>this.rankings[e]={});for(let e=1;e<a.length;e++){let r=a[e].trim();if(!r)continue;let n=r.split(","),i=n[0]?.trim();if(i)for(let e=0;e<t.length;e++){let a=o[t[e]];if(!a)continue;let r=parseInt(n[e+1]?.trim(),10);if(isNaN(r))continue;let s=Math.min(r,100);i in this.rankings[a]&&!(s<this.rankings[a][i])||(this.rankings[a][i]=s)}}let i=new Set;Object.values(this.rankings).forEach(e=>Object.keys(e).forEach(e=>i.add(e))),this.countries=Array.from(i).sort((e,a)=>e.localeCompare(a)).map(e=>{let a=r(e),t=n(a);return{name:e,flag:`/flags/${a.toLowerCase()}.png`,emoji:t,rankings:Object.fromEntries(Object.entries(this.rankings).map(([a,t])=>[a,t[e]??101]))}}),console.log(`[CSVRankingsLoader] Europe: parsed ${this.countries.length} countries`)}parse(e){if("europe"===this.gameMode)return void this.parseEurope(e);let a=e.trim().split(/\r?\n/);if(!a.length)return;let t=a[0].split(",").map(e=>e.trim());console.log("[CSVRankingsLoader] Parsing CSV with headers:",t);let o={world:{Population:"population",Football:"football","Small Size":"small_size",Corruption:"corruption","Forest Cover":"forestCover",Basketball:"basketball",Pollution:"pollution",Cuisine:"cuisine"},special:{Military:"military","Worst Passport":"worst_passport","Small Size":"small_size",HDI:"hdi",Biodiversity:"biodiversity","Highest Elevation":"highest_elevation",Rugby:"rugby",Coastline:"coastline"},voyage:{"Hot Temperature":"hot_temperature","Seafood Consumption":"seafood_consumption",Cycling:"cycling","Low Population":"low_population","Fertility Rate":"fertility_rate","Oil Production":"oil_production","GDP Per Capita":"gdp_per_capita","Natural Disaster Risk":"natural_disaster_risk"},atlas:{"Population of Capital":"population_of_capital","Olympic Medals":"olympic_medals","Most Rain":"most_rain","Tallest Skyscraper":"tallest_skyscraper","Obesity Rate":"obesity_rate","Median Age":"median_age","Worst Internet":"worst_internet","Most Languages":"most_languages"},usa:{Population:"population","Hot Temperature":"hot_temp","Cold Temperature":"cold_temp","Crime Rate":"crime_rate",Farming:"farming","Public School Rank":"public_school_rank","Order of Statehood":"order_of_statehood","Pro Sports Championships":"pro_sports_championships"},canada:{"NHL Players":"nhl_players","Low Population":"low_population","Most Snowfall":"most_snowfall",Elevation:"elevation",Moose:"moose","Farmland Area":"farmland_area","Forest Cover":"forest_cover","Oil Production":"oil_production"},europe:{Population:"population","Cold Temperature":"cold_temperature","Small Size":"small_size","UNESCO Sites":"unesco_sites","Average Height (Men)":"average_height","GDP Per Capita":"gdp_per_capita","Southernmost Capital":"southernmost_capital","Champions League Wins":"champions_league","UCL Goals":"champions_league"},sports:{Football:"football",Basketball:"basketball",Rugby:"rugby",Tennis:"tennis",MMA:"mma","Cricket (T20)":"cricket_t20","Ice Hockey":"ice_hockey",Baseball:"baseball"},empires:{"Years of Existence":"emp_years_existence","Peak Land Area":"emp_peak_land_area","Population at Peak":"emp_population_at_peak","Capital Elevation":"emp_capital_elevation","Distance to Rome":"emp_distance_to_rome","Shortest Lifespan":"emp_shortest_lifespan","Modern Countries Covered":"emp_modern_countries","Year Founded":"emp_year_founded"},"world-cup":{"FIFA Ranks Best":"wc_fifa_rank_best","FIFA Ranks Worst":"wc_fifa_rank_worst","World Cup Goals":"wc_goals_all_time","Distance From Final":"wc_distance_from_final","Yellow + Red Cards":"wc_yellow_red_cards","Oldest Players":"wc_oldest_player","Youngest Players":"wc_youngest_player","Leading International Scorer":"wc_leading_scorer"},"world-cup-ko":{"FIFA Ranks Best":"wc2_fifa_rank_best","FIFA Ranks Worst":"wc2_fifa_rank_worst","Average Temperature":"wc2_avg_temperature","Largest Stadium":"wc2_largest_stadium","Smallest Stadium":"wc2_smallest_stadium","Oldest Team":"wc2_oldest_team","Newest Team":"wc2_newest_team","Stadium Elevation":"wc2_stadium_elevation"}}[this.gameMode]??{Population:"population",Football:"football","Small Size":"small_size",Crime:"crime","Crime Rate":"crime",Tourism:"tourism",Coffee:"coffee","Coffee Production":"coffee",GDP:"gdp","Natural Gas":"gas"};console.log(`[CSVRankingsLoader] Using header map for ${this.gameMode}:`,o),Object.values(o).forEach(e=>this.rankings[e]={});for(let e=1;e<a.length;e++){let r=a[e].trim();if(!r||r.startsWith("Wikipedia"))continue;let n=r.split(",");for(let e=0;e<t.length;e++){let a=o[t[e]];if(!a)continue;let r=(n[e]||"").trim();if(!r)continue;let i=r.match(/^(\d+)\.\s*(.+)$/);if(!i)continue;let s=Number.parseInt(i[1],10);s>100&&(s=100);let l=i[2];l in this.rankings[a]&&!(s<this.rankings[a][l])||(this.rankings[a][l]=s)}}let c=new Set;if(Object.values(this.rankings).forEach(e=>Object.keys(e).forEach(e=>c.add(e))),console.log(`[CSVRankingsLoader] Found ${c.size} unique countries`),this.countries=Array.from(c).sort((e,a)=>e.localeCompare(a)).map(e=>{let a=r(e),t=n(a),o=`/flags/${a.toLowerCase()}.png`;if("empires"===this.gameMode)t=(0,l.getEmpireEmoji)(e),o=(0,l.getEmpireFlagPath)(e)||"";else if("usa"===this.gameMode){a="US",t="🇺🇸",o="/flags/us.png";let r=i.US_STATES.find(a=>a.name===e);r&&(t=r.emoji,o=r.flag)}else if("canada"===this.gameMode){let a=s.CANADA_PROVINCES.find(a=>a.name===e);a?(t=a.emoji,o=a.flag):(t="🍁",o="/flags/ca.png")}return{name:e,flag:o,emoji:t,rankings:Object.fromEntries(Object.entries(this.rankings).map(([a,t])=>{let o=t[e];return void 0===o?[a,101]:[a,o]}))}}),console.log(`[CSVRankingsLoader] Created ${this.countries.length} country objects`),this.countries.length>0){let e=this.countries[0];console.log(`[CSVRankingsLoader] Sample country ${e.name} rankings:`,e.rankings)}{let e={};Object.entries(this.rankings).forEach(([a,t])=>{e[a]=Object.keys(t).length});let a=Object.entries(e).filter(([,e])=>0===e).map(([e])=>e);a.length&&console.warn("[CSVRankingsLoader] Categories with zero parsed entries:",a),"special"===this.gameMode&&e.small_size&&e.small_size<50&&console.warn("[CSVRankingsLoader] small_size coverage looks low (",e.small_size,'countries). Verify CSV header "Small Size" present and mapped.'),console.log("[CSVRankingsLoader] Category coverage:",e)}}}var m=e.i(73261),u=e.i(98355);class h{static STORAGE_KEY_DAILY="geohunter-daily-leaderboard";static MAX_ENTRIES=500;static getDailyLeaderboard(){let e=window.localStorage.getItem(this.STORAGE_KEY_DAILY);if(!e)return[];try{let a=JSON.parse(e);if(!Array.isArray(a))return[];return a.filter(e=>!!(e&&e.username&&Number.isFinite(e.score))).map(e=>({...e,gameMode:"daily",score:Math.max(8,Math.floor(e.score))})).sort((e,a)=>e.score-a.score).slice(0,this.MAX_ENTRIES)}catch(e){return console.error("[LeaderboardManager] Failed to parse daily leaderboard:",e),[]}}static addDailyScore(e){let a=this.getDailyLeaderboard(),t={...e,gameMode:"daily",timestamp:Date.now(),score:Math.max(8,Math.floor(e.score))};a.push(t),a.sort((e,a)=>e.score-a.score),window.localStorage.setItem(this.STORAGE_KEY_DAILY,JSON.stringify(a.slice(0,this.MAX_ENTRIES)))}static getTodaysDailyLeaderboard(){let e=(0,u.getEasternDateString)();return this.getDailyLeaderboard().filter(a=>a.challengeDate===e).sort((e,a)=>e.score-a.score).slice(0,100)}static getUserDailyRank(e,a){let t=this.getDailyLeaderboard().filter(e=>e.challengeDate===a).sort((e,a)=>e.score-a.score).findIndex(a=>a.username===e);return t>=0?t+1:null}static getUserBestDailyScore(e){let a=this.getDailyLeaderboard().filter(a=>a.username===e);return 0===a.length?null:a.reduce((e,a)=>a.score<e.score?a:e)}static cleanupOldDailyEntries(){let e=new Date((0,u.getEasternNow)().getTime()-2592e6),a=(0,u.getEasternDateStringFrom)(e),t=this.getDailyLeaderboard().filter(e=>e.challengeDate>=a);window.localStorage.setItem(this.STORAGE_KEY_DAILY,JSON.stringify(t))}}let p="geohunter_daily_data",y={population:{name:"Population",icon:"👥",description:"Countries ranked by the highest total population.",goal:"Rank #1 has the largest population on Earth. Aim for mega-population nations; higher rank numbers mean fewer people."},football:{name:"Football",icon:"⚽",description:"FIFA Men’s World Rankings for national football teams.",goal:"Rank #1 is the top FIFA-ranked national side. The lower the number, the stronger the team."},small_size:{name:"Small Size",icon:"🏝️",description:"Countries ranked by the smallest total land mass.",goal:"Rank #1 is the tiniest country by land area. Microstates sit at the top; larger territories fall further down."},large_size:{name:"Large Size",icon:"🌍",description:"Countries ranked by the largest land mass.",goal:"Rank #1 covers the most land. Choose sprawling giants; smaller nations sit further down the list."},crime:{name:"Crime",icon:"🚨",description:"Crime Index rankings showing overall safety versus crime.",goal:"Rank #1 signals the highest crime levels (least safe). Pick places known for elevated crime; safer countries rank lower."},corruption:{name:"Corruption",icon:"🏛️",description:"Transparency International's Corruption Perceptions Index.",goal:"Rank #1 is the most corrupt government with the highest perceived corruption. Cleaner, less corrupt countries appear with higher rank numbers."},tourism:{name:"Tourism",icon:"🗺️",description:"International tourist arrivals by country.",goal:"Rank #1 welcomes the most international visitors. Choose iconic travel hotspots for low rank numbers."},gdp:{name:"GDP",icon:"💰",description:"Gross domestic product – total economic output.",goal:"Rank #1 has the biggest economy by total GDP. Economic powerhouses sit near the top."},gdp_per_capita:{name:"GDP Per Capita",icon:"💸",description:"Gross domestic product per capita.",goal:"Rank #1 has the highest income per person. Wealthy, high-standard-of-living nations take the top spots."},coffee:{name:"Coffee",icon:"☕",description:"Countries ranked by highest coffee production.",goal:"Rank #1 produces the most coffee beans. Coffee-exporting giants dominate the low ranks."},cocoa_production:{name:"Cocoa Production",icon:"🍫",description:"Countries ranked by highest cocoa production.",goal:"Rank #1 grows the most cocoa beans. Cocoa powerhouses sit near the top."},natural_gas:{name:"Natural Gas",icon:"💨",description:"Countries ranked by proven natural gas reserves.",goal:"Rank #1 holds the largest natural gas reserves. Energy giants dominate the top spots."},gas:{name:"Natural Gas",icon:"💨",description:"Countries ranked by proven natural gas reserves.",goal:"Rank #1 holds the largest natural gas reserves. Energy giants dominate the top spots."},oil_production:{name:"Oil Production",icon:"🛢️",description:"Daily crude oil production in barrels.",goal:"Rank #1 extracts the most oil per day. Petrostates land near the top; countries without oil fall further down."},gold_production:{name:"Gold Production",icon:"🏆",description:"Countries ranked by highest gold production.",goal:"Rank #1 mines the most gold each year. Major gold producers sit near the top."},diamond_production:{name:"Diamond Production",icon:"💎",description:"Countries ranked by highest diamond production.",goal:"Rank #1 produces the most diamonds. Countries with large diamond industries appear with lower ranks."},wine_production:{name:"Wine Production",icon:"🍷",description:"Countries ranked by highest wine production.",goal:"Rank #1 makes the most wine each year. Classic wine regions dominate the top spots."},cheese_export:{name:"Cheese Export",icon:"🧀",description:"Countries ranked by highest cheese export value.",goal:"Rank #1 ships the most cheese abroad. Dairy export giants hold the best ranks."},beer_consumption_per_capita:{name:"Beer Consumption",icon:"🍺",description:"Beer consumption per person each year.",goal:"Rank #1 drinks the most beer per person. Beer-loving nations sit at the top."},alcohol:{name:"Alcohol Consumption",icon:"🍻",description:"Alcohol consumption per person each year.",goal:"Rank #1 drinks the most alcohol per person each year. Higher ranks indicate heavier drinking populations."},hot_temperature:{name:"Hottest Climates",icon:"🔥",description:"Countries ranked by the hottest average yearly temperatures.",goal:"Rank #1 has the hottest average climate. Expect desert and equatorial nations near the top."},cold_temperature:{name:"Coldest Climates",icon:"🥶",description:"Countries ranked by the coldest average yearly temperatures.",goal:"Rank #1 is the coldest on average. Polar and high-latitude countries occupy the top spots."},low_life_expectancy:{name:"Low Life Expectancy",icon:"💀",description:"Countries ranked by the lowest life expectancy.",goal:"Rank #1 has the shortest life expectancy, usually due to health and living-condition challenges. Longer-lived nations rank lower."},forest_cover:{name:"Forest Cover",icon:"🌲",description:"Share of land mass covered by forests.",goal:"Rank #1 has the highest percentage of land covered by forest. Lower ranks indicate higher forest coverage."},forestCover:{name:"Forest Cover",icon:"🌲",description:"Share of land mass covered by forests."},biodiversity:{name:"Biodiversity",icon:"🦋",description:"Most biodiverse countries, rich in unique species.",goal:"Rank #1 teems with the most species. Tropical, megadiverse nations dominate the top ranks."},endangered_species:{name:"Endangered Species",icon:"🐾",description:"Countries with the most endangered species.",goal:"Rank #1 has the most endangered species. Biodiversity hotspots under pressure sit near the top."},volcanoes:{name:"Volcanoes",icon:"🌋",description:"Countries with the most Holocene volcanoes.",goal:"Rank #1 has the most recorded Holocene volcanoes. Volcanic belts dominate the low ranks."},natural_disaster_risk:{name:"Natural Disaster Risk",icon:"🌪️",description:"Countries facing the highest natural disaster risk.",goal:"Rank #1 has the highest risk of natural disasters. Lower numbers represent countries that are more prone to natural disasters."},college_degree:{name:"College Degree %",icon:"🎓",description:"Share of adults with college degrees.",goal:"Rank #1 has the highest share of adults with college degrees. Lower ranks mean more graduates."},number_of_islands:{name:"Number of Islands",icon:"🏝️",description:"Countries ranked by total number of islands.",goal:"Rank #1 has the most islands on Earth. Lower ranks mean more islands."},number_of_muslims:{name:"Number of Muslims",icon:"🕌",description:"Countries ranked by largest Muslim populations.",goal:"Rank #1 has the largest Muslim population. Lower ranks mean higher Muslim populations."},high_life_expectancy:{name:"High Life Expectancy",icon:"👵",description:"Countries ranked by longest life expectancy.",goal:"Rank #1 lives the longest. Lower ranks mean longer lifespans."},protected_land_percentage:{name:"Protected Land %",icon:"🌿",description:"Share of land protected for nature.",goal:"Rank #1 protects the highest share of land for nature. Lower ranks mean more protection."},horses:{name:"Horse Population",icon:"🐴",description:"Countries ranked by horse population.",goal:"Rank #1 has the biggest horse population. Lower ranks mean more horses."},tallest_skyscraper:{name:"Tallest Skyscraper",icon:"🏙️",description:"Countries with the tallest skyscrapers.",goal:"Rank #1 boasts the world’s tallest skyscraper. Lower ranks mean higher skylines."},tallest_height_men:{name:"Tallest Height (Men)",icon:"📏",description:"Average male height by country.",goal:"Rank #1 has the tallest average male height. Lower ranks mean taller statures."},obesity:{name:"Obesity Rate",icon:"🍔",description:"Countries ranked by obesity prevalence.",goal:"Rank #1 has the highest obesity rate. Lower ranks represent nations with more obesity."},beef_consumption:{name:"Beef Consumption",icon:"🥩",description:"Per-capita beef consumption.",goal:"Rank #1 eats the most beef per person. Lower ranks mean more meat consumption."},number_of_refugees:{name:"Number of Refugees",icon:"💔",description:"Refugee population hosted by each country.",goal:"Rank #1 hosts the most refugees. Lower ranks mean more refugees hosted."},pollution:{name:"Pollution",icon:"🏭",description:"Fine particulate (PM2.5) pollution in the air.",goal:"Rank #1 suffers the worst air pollution. Lower numbers have higher amounts of PM2.5 pollution in the air."},co2_emissions:{name:"CO₂ Emissions",icon:"🌫️",description:"Total fossil fuel CO₂ emissions.",goal:"Rank #1 releases the most CO₂ each year. Industrial powers and energy producers dominate the top."},hdi:{name:"Human Development Index",icon:"📊",description:"UN Human Development Index scores.",goal:"Rank #1 scores highest on the UN’s HDI (best life expectancy, education, and income). Lower ranks indicate lower development."},education:{name:"Education",icon:"🎓",description:"UN Education Index scores.",goal:"Rank #1 has the strongest education outcomes. Think top-performing school systems; weaker systems rank lower."},military:{name:"Military Strength",icon:"⚔️",description:"Global Firepower military strength index.",goal:"Rank #1 fields the most powerful military. Countries with less capacity sit further down the list."},best_passport:{name:"Best Passport",icon:"📘",description:"Passports with the most visa-free destinations.",goal:"Rank #1 passport offers the most visa-free travel. Greater travel freedom means a lower rank number."},worst_passport:{name:"Worst Passport",icon:"📕",description:"Passports with the least visa-free destinations.",goal:"Rank #1 has the least travel freedom. Countries with more restrictions sit at the top; better passports rank lower (higher numbers)."},airports:{name:"Airports",icon:"✈️",description:"Countries ranked by number of airports.",goal:"Rank #1 has the most airports. Aviation-heavy countries dominate the low ranks."},mma:{name:"Mixed Martial Arts",icon:"🥊",description:"Global mixed martial arts rankings.",goal:"Rank #1 is the nation with the highest MMA ranking. Lower ranks mean stronger fight scenes."},gender_equality_index:{name:"Gender Equality",icon:"⚖️",description:"Gender Equality Index scores.",goal:"Rank #1 has the highest gender equality. Lower ranks mean smaller gender gaps."},most_languages:{name:"Most Languages",icon:"🗣️",description:"Countries ranked by number of living languages.",goal:"Rank #1 has the largest number of languages spoken. Linguistically diverse nations stay near the top."},cuisine:{name:"Cuisine",icon:"🍽️",description:"TasteAtlas rankings of the best cuisines.",goal:"Rank #1 is the most celebrated cuisine. Think foodie favorites; less famous food scenes rank lower."},public_holidays:{name:"Public Holidays",icon:"📅",description:"Number of public holidays per year.",goal:"Rank #1 enjoys the most public holidays. Lower ranks mean more days off."},road_quality:{name:"Road Quality",icon:"🛣️",description:"Quality of roads and infrastructure.",goal:"Rank #1 has the smoothest, best-rated roads. Lower ranks mean smoother rides."},olympic_medals:{name:"Olympic Medals",icon:"🏅",description:"Total Olympic medal count (Summer + Winter).",goal:"Rank #1 has earned the most Olympic medals overall. Sporting powerhouses dominate low ranks."},rugby:{name:"Rugby",icon:"🏉",description:"Men’s World Rugby rankings.",goal:"Rank #1 is the top men’s national rugby team. Traditional rugby nations occupy the best ranks."},basketball:{name:"Basketball",icon:"🏀",description:"FIBA Men’s world rankings.",goal:"Rank #1 leads the FIBA rankings. Basketball powers with strong national teams sit near the top."},ice_hockey:{name:"Ice Hockey",icon:"🏒",description:"IIHF Men’s world rankings.",goal:"Rank #1 is the strongest national ice hockey team. Traditional hockey nations take the best ranks."},coastline:{name:"Coastline Length",icon:"🏖️",description:"Countries ranked by longest coastline length.",goal:"Rank #1 has the longest coastline. Maritime nations with sprawling shores sit near the top."},lakes:{name:"Lakes",icon:"🏞️",description:"Countries with the most lakes.",goal:"Rank #1 boasts the greatest number of lakes. Countries with many lakes rank lower numbers."},highest_elevation:{name:"Highest Elevation",icon:"🏔️",description:"Countries ranked by highest elevation point.",goal:"Rank #1 contains the highest peak on earth. Think Mount Everest or the Andean peaks for low ranks."},lowest_elevation:{name:"Lowest Elevation",icon:"⛰️",description:"Countries ranked by lowest elevation point.",goal:"Rank #1 sits the farthest below sea level or at the lowest average height. Low-lying nations appear at the top."},beer_production:{name:"Beer Production",icon:"🍺",description:"Countries ranked by total beer production volume.",goal:"Rank #1 brews the most beer overall. Major brewing nations land near the top."},mcdonalds_locations:{name:"McDonald's Locations",icon:"🍟",description:"Countries ranked by number of McDonald’s restaurants.",goal:"Rank #1 has the most McDonald’s restaurants. Countries saturated with the golden arches score lower rank numbers."},crypto_ownership:{name:"Crypto Ownership",icon:"₿",description:"Percentage of the population owning cryptocurrency.",goal:"Rank #1 has the highest share of people owning crypto. Widespread adoption pushes countries toward the top."},chess:{name:"Chess",icon:"♟️",description:"FIDE men's national chess rankings.",goal:"Rank #1 is the strongest national chess federation. Elite chess nations sit near the top."},vegetarianism:{name:"Vegetarianism",icon:"🥗",description:"Countries ranked by share of vegetarians.",goal:"Rank #1 has the highest vegetarian population. Lower ranks mean more vegetarians."},tea_consumption:{name:"Tea Consumption",icon:"🍵",description:"Tea consumption per person.",goal:"Rank #1 drinks the most tea per capita. Lower ranks mean larger tea drinkers."},world_cup_wins:{name:"World Cup Wins",icon:"🏆",description:"FIFA World Cup titles by country.",goal:"Rank #1 holds the most FIFA World Cup championships. Lower ranks mean more titles."},cricket:{name:"Cricket",icon:"🏏",description:"ICC cricket rankings.",goal:"Rank #1 dominates the cricket world. Lower ranks mean stronger cricket nations."},whaling:{name:"Whaling",icon:"🐋",description:"Countries ranked by whales hunted.",goal:"Rank #1 hunts the most whales. Lower ranks mean more whales caught."},pandas:{name:"Panda Population",icon:"🐼",description:"Countries with the largest panda populations.",goal:"Rank #1 has the most pandas. Lower ranks mean more pandas."},number_of_billionaires:{name:"Number of Billionaires",icon:"💰",description:"Countries ranked by billionaire counts.",goal:"Rank #1 has the most billionaires. Lower ranks mean more billionaires."},baseball:{name:"Baseball",icon:"⚾",description:"World Baseball Softball Confederation rankings.",goal:"Rank #1 is the highest-ranked baseball nation. Lower ranks represent stronger baseball nations."},coral_reef_area:{name:"Coral Reef Area",icon:"🐠",description:"Countries ranked by coral reef coverage.",goal:"Rank #1 has the largest coral reef area. Lower ranks mean more reef coverage."},nuclear_power_reactors:{name:"Nuclear Reactors",icon:"☢️",description:"Countries ranked by active nuclear reactors.",goal:"Rank #1 operates the most nuclear reactors. Lower ranks mean higher reactor counts."},rice_export:{name:"Rice Export",icon:"🍚",description:"Countries ranked by rice exports.",goal:"Rank #1 exports the most rice. Lower ranks mean larger exports."},olive_oil_production:{name:"Olive Oil Production",icon:"🫒",description:"Countries ranked by olive oil output.",goal:"Rank #1 produces the most olive oil. Lower ranks mean more output."},banana_export:{name:"Banana Export",icon:"🍌",description:"Countries ranked by banana exports.",goal:"Rank #1 exports the most bananas. Lower ranks mean higher exports."},winter_olympic_medals:{name:"Winter Olympic Medals",icon:"🥌",description:"Total Winter Olympic medals.",goal:"Rank #1 has the most Winter Olympic medals. Lower ranks mean more medals."},earthquakes:{name:"Earthquakes",icon:"🌎",description:"Countries ranked by annual earthquake counts.",goal:"Rank #1 experiences the most earthquakes annually. Lower ranks mean fewer quakes."},median_age:{name:"Median Age",icon:"🧓",description:"Countries ranked by median age.",goal:"Rank #1 has the oldest population. Lower ranks mean older nations."},guns_per_100_people:{name:"Guns per 100 People",icon:"🔫",description:"Countries ranked by guns owned per capita.",goal:"Rank #1 owns the most guns per person. Lower ranks mean more firearms."},seafood_consumption:{name:"Seafood Consumption",icon:"🦞",description:"Seafood consumption per capita.",goal:"Rank #1 eats the most seafood per person. Lower numbers mean larger appetites for seafood."},cycling:{name:"Cycling",icon:"🚴",description:"UCI World Cycling Rankings.",goal:"Rank #1 is the nation with the highest rank in competitive cycling. Lower ranks mean stronger riders and better results."},low_population:{name:"Low Population",icon:"👤",description:"Countries ranked by the smallest population.",goal:"Rank #1 has the smallest population. Lower ranks mean smaller populations."},fertility_rate:{name:"Fertility Rate",icon:"🍼",description:"Countries ranked by average births per woman.",goal:"Rank #1 has the highest fertility rate. Lower ranks mean more children per family."},population_of_capital:{name:"Population of Capital",icon:"🏛️",description:"Countries ranked by capital city population (including metro area).",goal:"Rank #1 has the largest capital city. Lower ranks mean bigger capitals."},most_rain:{name:"Most Rain",icon:"🌧️",description:"Countries ranked by highest average annual precipitation.",goal:"Rank #1 receives the most rainfall. Lower ranks mean wetter climates."},worst_internet:{name:"Worst Internet",icon:"🛜",description:"Countries ranked by slowest internet speeds.",goal:"Rank #1 has the slowest internet connections. Lower ranks mean slower speeds."},obesity_rate:{name:"Obesity Rate",icon:"🍔",description:"Percentage of adults with obesity.",goal:"Rank #1 has the highest obesity rate. Lower ranks mean more obesity."},most_horses:{name:"Most Horses",icon:"🐴",description:"Countries ranked by horse population.",goal:"Rank #1 has the most horses. Lower ranks mean larger horse populations."},maritime_area:{name:"Maritime Area",icon:"🌊",description:"Countries ranked by maritime territory (territorial waters + EEZ).",goal:"Rank #1 has the largest maritime area. Lower ranks mean more ocean territory."},cigarette_smoking:{name:"Cigarette Smoking",icon:"🚬",description:"Countries ranked by cigarette consumption per capita.",goal:"Rank #1 smokes the most cigarettes per person. Lower ranks mean higher smoking rates."},railroad_length:{name:"Railroad Length",icon:"🚂",description:"Countries ranked by total railroad track length.",goal:"Rank #1 has the most extensive railroad network. Lower ranks mean longer rail systems."},capybaras:{name:"Capybaras",icon:"🦫",description:"Countries with the largest capybara populations.",goal:"Rank #1 has the most capybaras. Lower ranks mean more capybaras."},cherry_production:{name:"Cherry Production",icon:"🍒",description:"Countries ranked by cherry production.",goal:"Rank #1 produces the most cherries. Lower ranks mean higher production."},marriage_rate:{name:"Marriage Rate",icon:"💒",description:"Countries ranked by marriage rates per capita.",goal:"Rank #1 has the highest marriage rate. Lower ranks mean more marriages."},space_station_visitors:{name:"Space Station Visitors",icon:"🚀",description:"Countries ranked by number of astronauts sent to space stations.",goal:"Rank #1 has sent the most astronauts to space. Lower ranks mean more visitors."},camels:{name:"Camels",icon:"🐪",description:"Countries with the largest camel populations.",goal:"Rank #1 has the most camels. Lower ranks mean more camels."},lions:{name:"Lions",icon:"🦁",description:"Countries with the largest lion populations.",goal:"Rank #1 has the most lions. Lower ranks mean more lions."},rare_earth_reserves:{name:"Rare Earth Reserves",icon:"⚗️",description:"Countries ranked by rare earth mineral reserves.",goal:"Rank #1 has the largest rare earth reserves. Lower ranks mean more reserves."},miss_world_titles:{name:"Miss World Titles",icon:"👸",description:"Countries ranked by Miss World pageant wins.",goal:"Rank #1 has won the most Miss World titles. Lower ranks mean more titles."},redhead_percentage:{name:"Redhead Percentage",icon:"👩‍🦰",description:"Countries ranked by percentage of natural redheads.",goal:"Rank #1 has the highest percentage of redheads. Lower ranks mean more redheads."},shark_attacks:{name:"Shark Attacks",icon:"🦈",description:"Countries ranked by number of shark attacks.",goal:"Rank #1 has the most shark attacks. Lower ranks mean more attacks."},ai_capacity:{name:"AI Capacity",icon:"🤖",description:"Countries ranked by artificial intelligence development capacity.",goal:"Rank #1 leads in AI development. Lower ranks mean stronger AI capacity."},cobalt_production:{name:"Cobalt Production",icon:"🔋",description:"Countries ranked by cobalt mining production.",goal:"Rank #1 produces the most cobalt. Lower ranks mean higher production."},cashew_production:{name:"Cashew Production",icon:"🥜",description:"Countries ranked by cashew nut production.",goal:"Rank #1 produces the most cashews. Lower ranks mean higher production."},aluminum_production:{name:"Aluminum Production",icon:"🪙",description:"Countries ranked by aluminum production.",goal:"Rank #1 produces the most aluminum. Lower ranks mean higher production."},copper_production:{name:"Copper Production",icon:"🪙",description:"Countries ranked by copper mining production.",goal:"Rank #1 produces the most copper. Lower ranks mean higher production."},iron_production:{name:"Iron Production",icon:"⚙️",description:"Countries ranked by iron ore production.",goal:"Rank #1 produces the most iron. Lower ranks mean higher production."},nickel_production:{name:"Nickel Production",icon:"🪙",description:"Countries ranked by nickel production.",goal:"Rank #1 produces the most nickel. Lower ranks mean higher production."},silver_production:{name:"Silver Production",icon:"🥈",description:"Countries ranked by silver mining production.",goal:"Rank #1 produces the most silver. Lower ranks mean higher production."},tin_production:{name:"Tin Production",icon:"🪙",description:"Countries ranked by tin production.",goal:"Rank #1 produces the most tin. Lower ranks mean higher production."},zinc_production:{name:"Zinc Production",icon:"🪙",description:"Countries ranked by zinc production.",goal:"Rank #1 produces the most zinc. Lower ranks mean higher production."},f1:{name:"Formula 1",icon:"🏎️",description:"Countries ranked by Formula 1 racing success.",goal:"Rank #1 dominates in F1 racing. Lower ranks mean more racing success."},bald_men:{name:"Bald Men",icon:"👨‍🦲",description:"Countries ranked by percentage of bald men.",goal:"Rank #1 has the highest percentage of bald men. Lower ranks mean more baldness."},elephants:{name:"Elephants",icon:"🐘",description:"Countries with the largest elephant populations.",goal:"Rank #1 has the most elephants. Lower ranks mean more elephants."},hippos:{name:"Hippos",icon:"🦛",description:"Countries with the largest hippopotamus populations.",goal:"Rank #1 has the most hippos. Lower ranks mean more hippos."},cotton_production:{name:"Cotton Production",icon:"🧵",description:"Countries ranked by cotton production.",goal:"Rank #1 produces the most cotton. Lower ranks mean higher production."},curling:{name:"Curling",icon:"🥌",description:"World Curling Federation rankings.",goal:"Rank #1 is the strongest curling nation. Lower ranks mean better curling."},electric_car_use:{name:"Electric Car Use",icon:"🔌",description:"Countries ranked by electric vehicle adoption.",goal:"Rank #1 has the highest EV adoption rate. Lower ranks mean more electric cars."},table_tennis:{name:"Table Tennis",icon:"🏓",description:"ITTF world rankings for table tennis.",goal:"Rank #1 dominates international table tennis. Lower ranks mean stronger players."},incarceration_rate:{name:"Incarceration Rate",icon:"⛓️",description:"Countries ranked by incarceration rate per capita.",goal:"Rank #1 has the highest prison population per capita. Lower ranks mean more people in prison."},least_rain:{name:"Least Rain",icon:"☀️",description:"Countries ranked by lowest average annual precipitation.",goal:"Rank #1 receives the least rainfall. Lower ranks mean drier climates."},donkeys:{name:"Donkeys",icon:"🫏",description:"Countries with the largest donkey populations.",goal:"Rank #1 has the most donkeys. Lower ranks mean more donkeys."},low_clean_water_access:{name:"Low Clean Water Access",icon:"💧",description:"Countries ranked by lowest access to clean drinking water.",goal:"Rank #1 has the worst access to clean water. Lower ranks mean less water access."},motor_vehicles:{name:"Motor Vehicles",icon:"🚗",description:"Vehicles per 1,0",goal:"Rank #1 has the most motor vehicles. Lower ranks mean more cars."},average_iq:{name:"Average IQ",icon:"🧠",description:"Countries ranked by average IQ scores.",goal:"Rank #1 has the highest average IQ. Lower ranks mean higher scores."},golf_courses:{name:"Golf Courses",icon:"⛳",description:"Countries ranked by number of golf courses.",goal:"Rank #1 has the most golf courses. Lower ranks mean more courses."},most_indians:{name:"Most Indians",icon:"🇮🇳",description:"Countries ranked by Indian diaspora population.",goal:"Rank #1 has the largest Indian population outside India. Lower ranks mean more Indians."},land_border_length:{name:"Land Border Length",icon:"🗺️",description:"Countries ranked by total land border length.",goal:"Rank #1 has the longest land borders. Lower ranks mean more border length."},goats:{name:"Goats",icon:"🐐",description:"Countries with the largest goat populations.",goal:"Rank #1 has the most goats. Lower ranks mean more goats."},dairy_production:{name:"Dairy Production",icon:"🥛",description:"Countries ranked by dairy production volume.",goal:"Rank #1 produces the most dairy products. Lower ranks mean higher production."},renewable_electricity:{name:"Renewable Electricity",icon:"⚡",description:"Countries ranked by percentage of renewable electricity generation.",goal:"Rank #1 generates the most renewable electricity. Lower ranks mean more renewables."},hindu_percentage:{name:"Hindu Percentage",icon:"🕉️",description:"Countries ranked by percentage of Hindu population.",goal:"Rank #1 has the highest percentage of Hindus. Lower ranks mean more Hindus."},least_english:{name:"Least English",icon:"🗣️",description:"Countries ranked by lowest English proficiency.",goal:"Rank #1 has the lowest English proficiency. Lower ranks mean less English spoken."},unemployment:{name:"Unemployment",icon:"📉",description:"Countries ranked by unemployment rate.",goal:"Rank #1 has the highest unemployment rate. Lower ranks mean more unemployment."},low_immigrant:{name:"Low Immigrant Percentage",icon:"👤",description:"Countries ranked by lowest immigrant percentage.",goal:"Rank #1 has the fewest immigrants as percentage of population. Lower ranks mean fewer immigrants."},world_heritage_sites:{name:"World Heritage Sites",icon:"🏛️",description:"Countries ranked by UNESCO World Heritage Sites.",goal:"Rank #1 has the most UNESCO World Heritage Sites. Lower ranks mean more sites."},most_immigrants:{name:"Most Immigrants",icon:"🌍",description:"Countries ranked by total immigrant population.",goal:"Rank #1 has the most immigrants. Lower ranks mean more immigrants."}};function f(e,a={}){let t=y[e.toLowerCase()]||y[e]||{},o=a.nameOverride||t.name||e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),r=a.iconOverride||t.icon||(a.isWild?"🃏":"📊"),n=a.descriptionOverride||t.description||`Ranking performance for ${o}.`;return{id:e,name:o,icon:r,description:n,goal:t.goal||"Rank #1 sits at the top of this list. Lower numbers mean the country fits this category better.",examples:t.examples||[]}}e.s(["getCategoryMetadata",()=>f],85929);var k=e.i(45168),w=e.i(92603);let C=null,_={crime_rate:"crime",coastline_length:"coastline",military_strength:"military",best_education:"education",college_degrees:"college_degree",cricket__t20:"cricket",tallest_height__men:"tallest_height_men",coffee_production:"coffee",beer_consumption:"beer_consumption_per_capita"},b={macedonia:"North Macedonia","republic of macedonia":"North Macedonia","macedonia (fyrom)":"North Macedonia",fyrom:"North Macedonia","former yugoslav republic of macedonia":"North Macedonia"};function S(e){let a=e.trim().split(/\r?\n/);if(!a.length)return{categoryOrder:[],headerNamePerCategory:{},rankingsPerCategory:{},maxRankPerCategory:{}};let t=a[0].split(",").map(e=>e.trim()).filter(Boolean),o=[],r={},n={},i={},s={},l=new Set,c=[];t.forEach(e=>{let a=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");if(!a)throw Error(`Invalid CSV header (empty after slugify): "${e}"`);let t=_[a]??a;if(c.push({header:e,id:t}),l.has(t)){let e=c.filter(e=>e.id===t).map(e=>`"${e.header}"`).join(", ");throw Error(`Duplicate/Colliding category IDs after normalization: ${t}. Headers: ${e}. Fix by renaming a header or adding an alias in daily-dynamic-loader.ts.`)}l.add(t),o.push(t),r[t]=e,n[t]=[],i[t]=0,s[t]=new Set});let d=/^(\d+)\.\s*(.+)$/;for(let e=1;e<a.length;e++){let r=a[e];if(!r||r.startsWith("Wikipedia")||r.startsWith("(LINK)"))continue;let l=r.split(",");for(let e=0;e<t.length;e++){let a=(l[e]||"").trim();if(!a)continue;let t=a.match(d);if(!t)continue;let r=parseInt(t[1],10),c=function(e){let a=e.trim();if(!a)return a;let t=a.replace(/\s+/g," ");return b[t.toLowerCase()]??t}(t[2]),g=o[e];r>i[g]&&(i[g]=r);let m=s[g];m.has(c)||(m.add(c),n[g].push({country:c,rank:r}))}}return{categoryOrder:o,headerNamePerCategory:r,rankingsPerCategory:n,maxRankPerCategory:i}}async function M(e,a){e.replace(/^\//,"");let t=await fetch(e,{cache:"force-cache"});if(!t.ok)throw Error(`Failed to fetch ${e}: ${t.status} ${t.statusText}`);return t.text()}async function v(){return null}let R=null;async function A(e){if(R)return R;let a=function(){try{let e,a=localStorage.getItem(p);if(!a)return null;let t=JSON.parse(a);if(e=Date.now()-t.timestamp,"1.3"!==t.version||!(e<864e5)||!t.data||!t.dataHash)return localStorage.removeItem(p),null;return t.data}catch(e){return console.warn("Failed to load cached daily data:",e),localStorage.removeItem(p),null}}();if(a)return R=a,a;let t=await v();if(t)return R=t,t;try{let[a,t]=await Promise.all([M("/data/gh_daily_ranks.csv",e),M("/data/gh_daily_wild.csv",e)]),i=S(a),s=S(t),l=new Set,c={},d=[];function o(e,a){for(let t of e.categoryOrder){let o=e.headerNamePerCategory[t],r={population:"👥",football:"⚽",small_size:"🏝️",crime:"🚨",tourism:"✈️",gdp:"💰",natural_gas:"⛽",forest_cover:"🌳",corruption:"🕵️",basketball:"🏀",co2_emissions:"💨",hdi:"📊",biodiversity:"🦜",cuisine:"🍲",pollution:"🏭",gdp_per_capita:"💵",oil_production:"🛢️",olympic_medals:"🥇",coastline:"🌊",military:"🪖",best_passport:"🛂",worst_passport:"🚫",most_languages:"🗣️",crypto_ownership:"₿",education:"🎓",airports:"🛫",highest_elevation:"⛰️",rugby:"🏉",lowest_elevation:"🕳️",large_size:"🗺️",natural_disaster_risk:"🌪️",alcohol_consumption:"🍺",hot_temperature:"🌡️",cold_temperature:"❄️",low_life_expectancy:"⚰️",mma:"🥊",gender_equality_index:"⚖️",fertility_rate:"👶",cycling:"🚴",public_holidays:"🎉",road_quality:"🛣️",seafood_consumption:"🦞",college_degree:"🎓",number_of_islands:"🏝️",low_population:"🤷‍♂️",median_age:"🧓",guns_per_100_people:"🔫",number_of_muslims:"🕌",high_life_expectancy:"👵",protected_land_percentage:"🛡️",horses:"🐴",tallest_skyscraper:"🏙️",tallest_height_men:"📏",tallest_height:"📏",arable_land:"🚜",obesity:"🍔",obesity_rate:"🍔",beef_consumption:"🥩",number_of_refugees:"💔",crime_rate:"🚨",coastline_length:"🌊",military_strength:"🪖",best_education:"🎓",most_airports:"🛫",college_degrees:"🎓",most_islands:"🏝️",most_horses:"🐴",cricket_t20:"🏏",table_tennis:"🏓",maritime_area:"🌊",cigarette_smoking:"🚬",incarceration_rate:"⛓️",most_rain:"🌧️",least_rain:"☀️",donkeys:"🫏",population_of_capital:"🏛️",low_clean_water_access:"💧",motor_vehicles:"🚗",railroad_length:"🚂",average_iq:"🧠",golf_courses:"⛳",most_indians:"🇮🇳",land_border_length:"🗺️",goats:"🐐",worst_internet:"🛜",dairy_production:"🥛",renewable_electricity:"⚡",hindu_percentage:"🕉️",least_english:"🗣️",unemployment:"📉",low_immigrant_percentage:"👤",low_immigrant:"👤",world_heritage_sites:"🏛️",most_immigrants:"🌍",coffee:"☕",coffee_production:"☕",ice_hockey:"🏒",diamond_production:"💎",volcanoes:"🌋",cheese_export:"🧀",endangered_species:"🦏",wine_production:"🍷",gold_production:"🥇",lakes:"🏞️",beer_consumption:"🍺",beer_consumption_per_capita:"🍺",cocoa_production:"🍫",mcdonalds_locations:"🍔",chess:"♟️",vegetarianism:"🥗",tea_consumption:"🍵",world_cup_wins:"🏆",cricket:"🏏",whaling:"🐋",pandas:"🐼",number_of_billionaires:"💵",baseball:"⚾",coral_reef_area:"🐠",nuclear_power_reactors:"☢️",rice_export:"🍚",olive_oil_production:"🫒",banana_export:"🍌",winter_olympic_medals:"🥌",earthquakes:"🫨",capybaras:"🦫",cherry_production:"🍒",marriage_rate:"💒",space_station_visitors:"🚀",camels:"🐪",lions:"🦁",rare_earth_reserves:"⚗️",miss_world_titles:"👸",redhead_percentage:"👩‍🦰",shark_attacks:"🦈",ai_capacity:"🤖",cobalt_production:"🔋",cashew_production:"🥜",aluminum_production:"🪙",copper_production:"🪙",iron_production:"⚙️",nickel_production:"🪙",silver_production:"🥈",tin_production:"🪙",zinc_production:"🪙",f1:"🏎️",bald_men:"👨‍🦲",elephants:"🐘",hippos:"🦛",cotton_production:"🧵",curling:"🥌",electric_car_use:"🔌"}[t]||(a?"🃏":"📊"),n=f(t,{isWild:a,nameOverride:o,iconOverride:r});for(let o of(d.push({id:t,name:n.name,icon:n.icon,description:n.description,maxRank:e.maxRankPerCategory[t]||100,isWild:a}),c[t]={},e.rankingsPerCategory[t]))l.add(o.country),c[t][o.country]=o.rank}}o(i,!1),o(s,!0);try{let e=function(){if(C)return C;let e=k.default.env.SUPABASE_URL||"https://fxyarvoootmvlrveblfx.supabase.co",a=k.default.env.SUPABASE_SERVICE_ROLE||k.default.env.SUPABASE_SERVICE_ROLE_KEY;if(!e||!a)throw Error("Supabase service credentials are not configured");return C=(0,w.createClient)(e,a,{auth:{persistSession:!1}})}();if(e){let a=d.map(e=>e.id),{data:t}=await e.from("categories").select("id, emoji").in("id",a);if(t?.length){let e={};for(let a of t)a.emoji&&(e[a.id]=a.emoji);for(let a of d)e[a.id]&&(a.icon=e[a.id])}}}catch{}let g={countries:Array.from(l).sort((e,a)=>e.localeCompare(a,"en",{sensitivity:"base"})).map(e=>{let a=r(e);return{name:e,flag:`/flags/${a.toLowerCase()}.png`,emoji:n(a),rankings:Object.fromEntries(d.map(a=>[a.id,c[a.id][e]??(a.isWild?Math.max(50,(a.maxRank||0)+1):(a.maxRank||0)+1)]))}}),normalCategories:d.filter(e=>!e.isWild).sort((e,a)=>e.id.localeCompare(a.id)),wildCategories:d.filter(e=>e.isWild).sort((e,a)=>e.id.localeCompare(a.id))};R=g;try{let e={version:"1.3",timestamp:Date.now(),data:g,dataHash:function(e){let a=JSON.stringify({countriesCount:e.countries.length,normalCategoriesCount:e.normalCategories.length,wildCategoriesCount:e.wildCategories.length,firstCountryName:e.countries[0]?.name||"",timestamp:new Date().toDateString()}),t=0;for(let e=0;e<a.length;e++)t=(t<<5)-t+a.charCodeAt(e),t&=t;return t.toString(36)}(g)};localStorage.setItem(p,JSON.stringify(e))}catch(e){console.warn("Failed to cache daily data:",e);try{localStorage.removeItem(p)}catch{}}return g}catch(e){throw console.error("Failed loading dynamic daily data:",e),e}}var D=e.i(43360);class I{static DAILY_COUNTRY_COUNT=9;static SKIP_RANK_THRESHOLD=100;static MAX_RANK_FRACTION=.8;static sanitizeAssignment(e,a){let t=new Map(e.map(e=>[e.id,e.name]));return a.map(e=>({categoryId:e.categoryId,categoryName:t.get(e.categoryId)??e.categoryId,countryName:e.country.name,rank:Math.round(e.rank)}))}static calculateDifficultyFromMapping(e,a,t){if(!a.length)return null;let o=new Map(e.map(e=>[e.id,e])),r=a.reduce((e,a)=>{let t=o.get(a.categoryId),r=t?.maxRank??I.SKIP_RANK_THRESHOLD;return e+Math.min(a.rank,r)/r},0)/a.length,n=e.reduce((e,a)=>e+(a.maxRank??I.SKIP_RANK_THRESHOLD),0),i=.7*r+.3*(null!==t&&n>0?t/n:r);e.some(e=>e.isWild)&&(i+=.05);let s=Math.round(100*(i=Math.min(1,Math.max(0,i)))),l="Moderate";return l=s<20?"Very Easy":s<35?"Easy":s<55?"Moderate":s<75?"Challenging":s<90?"Hard":"Expert",{score:s,label:l}}static computeOptimalAssignment(e,a,t){let o=t?e.filter(e=>e.name!==t):[...e],r=Math.min(o.length,a.length);if(0===r)return{mapping:[],bestScore:0};let n=[];for(let e=0;e<r;e++){let t=o[e],i=[];for(let e=0;e<r;e++){let o=a[e],r=o.maxRank??I.SKIP_RANK_THRESHOLD,n=t.rankings?.[o.id];if(null!=n){let e=n>r;i.push(e?r+1:Math.min(Math.round(n),r))}else i.push(r+1)}n.push(i)}let i=(0,D.hungarianAlgorithm)(n),s=[],l=0;for(let e=0;e<r;e++){let t=i[e];if(void 0!==t&&t>=0&&t<a.length){let r=o[e],i=a[t],c=n[e][t];s.push({categoryId:i.id,country:r,rank:c}),l+=c}}let c=new Map(o.map((e,a)=>[e.name,a]));return s.sort((e,a)=>(c.get(e.country.name)??999)-(c.get(a.country.name)??999)),{mapping:s,bestScore:l}}static reorderForGreedyOptimal(e,a,t){let o=e.length,r=new Map;for(let e of a)r.set(e.country.name,{categoryId:e.categoryId,rank:e.rank});let n=new Map;for(let e of a)n.set(e.categoryId,e.country.name);let i=new Map;for(let a of e)i.set(a.name,new Set);let s=new Map(t.map((e,a)=>[e.id,a]));for(let a of e){let e=r.get(a.name);if(!e)continue;let o=s.get(e.categoryId)??1/0;for(let r of t){if(r.id===e.categoryId)continue;let t=a.rankings?.[r.id];if(null!=t&&(t<e.rank||t===e.rank&&(s.get(r.id)??1/0)<o)){let e=n.get(r.id);e&&e!==a.name&&i.get(a.name).add(e)}}}let l=new Map,c=new Map;for(let a of e)l.set(a.name,i.get(a.name).size),c.set(a.name,[]);for(let[e,a]of i)for(let t of a)c.get(t).push(e);let d=[];for(let[e,a]of l)0===a&&d.push(e);let g=[];for(;d.length>0;){let e=d.shift();for(let a of(g.push(e),c.get(e)||[])){let e=l.get(a)-1;l.set(a,e),0===e&&d.push(a)}}if(g.length<o)for(let a of e)g.includes(a.name)||g.push(a.name);let m=new Map(e.map(e=>[e.name,e]));return g.map(e=>m.get(e))}static computeGreedyAssignment(e,a,t){return this.computeOptimalAssignment(e,a,t)}static deriveSolutionSnapshot(e){let a=e.categories??[],t=e.countries??[],o=t.map(e=>({name:e.name,flag:e.flag,emoji:e.emoji})),r=a.map(e=>({id:e.id,name:e.name,icon:e.icon})),n=[];if(Array.isArray(e.optimalAssignment)&&e.optimalAssignment.length>0)n=e.optimalAssignment.map(e=>({categoryId:e.categoryId,categoryName:e.categoryName??a.find(a=>a.id===e.categoryId)?.name??e.categoryId,countryName:e.countryName,rank:Math.round(e.rank)}));else if(t.length&&a.length){let{mapping:o}=I.computeGreedyAssignment(t,a,e.skipCountry?.name??null);n=I.sanitizeAssignment(a,o)}let i="number"==typeof e.targetScore&&Number.isFinite(e.targetScore)?Math.round(e.targetScore):null;(null===i||i<=0)&&n.length&&(i=n.reduce((e,a)=>e+a.rank,0));let s=e.difficulty&&"number"==typeof e.difficulty.score?{score:Math.round(e.difficulty.score),label:e.difficulty.label}:null;return s||(s=I.calculateDifficultyFromMapping(a,n,i)??null),{targetScore:i,optimalAssignment:n,countryManifest:o,categoryManifest:r,difficulty:s}}static generateDailySeed(e){let a;a="string"==typeof e?e:e instanceof Date?(0,u.getEasternDateStringFrom)(e):(0,u.getEasternDateString)();let t=0;for(let e=0;e<a.length;e++)t=(t<<5)-t+a.charCodeAt(e)&0x7fffffff;let[o,r,n]=a.split("-"),i=Number(o),s=Number(r),l=Number(n),c=[31,i%4==0&&(i%100!=0||i%400==0)?29:28,31,30,31,30,31,31,30,31,30,31],d=l;for(let e=0;e<s-1;e++)d+=c[e];return Math.abs(t=(t=t+1e3*i+100*s+l&0x7fffffff)+7919*d&0x7fffffff)}static seededRandom(e){let a=e;return()=>(a=(9301*a+49297)%233280)/233280}static async generateStrategicDailyChallenge(e){let a=e?.date??(0,u.getEasternDateString)(),o=t.gameModes.find(e=>"world"===e.id);if(!o)throw Error("World game mode configuration is missing");let r=this.generateDailySeed(a),n=this.seededRandom(r),i=await A(e?.csvBaseUrl);return this.buildChallengeFromData({random:n,mode:o,dynamicData:i,seed:r,dateStr:a})}static buildChallengeFromData(e){let{random:a,mode:t,dynamicData:o,seed:r,dateStr:n}=e;I.DAILY_COUNTRY_COUNT;let i=I.SKIP_RANK_THRESHOLD,s=e=>{let t=[...e];for(let e=t.length-1;e>0;e--){let o=Math.floor(a()*(e+1));[t[e],t[o]]=[t[o],t[e]]}return t};if(o.normalCategories.length<7||o.wildCategories.length<1)throw Error("Dynamic daily data is incomplete (requires ≥7 normal and ≥1 wild categories)");if(o.countries.length<I.DAILY_COUNTRY_COUNT)throw Error("Dynamic daily data is missing required countries");let l=s(o.normalCategories),c=s(o.wildCategories),d=s(o.countries),g=e=>{let t=e.map(e=>e.id),o=d.map(e=>{let a,o,r,n;return{country:e,...(o=(a=t.map(a=>e.rankings[a]??999)).filter(e=>e<=40).length,r=a.reduce((e,a)=>e+a,0),n=Math.min(...a),{ranks:a,goodCount:o,score:r,bestRank:n})}}),r=a=>e.every(e=>{let t=e.maxRank||i;return a.some(a=>(a.rankings[e.id]??t+50)<=t)}),n=new Map(e.map(e=>[e.id,e])),s=o.slice().sort((e,a)=>e.score!==a.score?e.score-a.score:e.country.name.localeCompare(a.country.name)),l=[],c=new Set,g=[...s];for(;l.length<I.DAILY_COUNTRY_COUNT&&g.length>0;){let e=g.map((e,t)=>1/(t+1)+.5*a()),t=e.reduce((e,a)=>e+a,0),o=a()*t,r=0;for(let a=0;a<g.length;a++)if((o-=e[a])<=0){r=a;break}let n=g[r];c.has(n.country.name)||(l.push(n.country),c.add(n.country.name)),g.splice(r,1)}if(l.length<I.DAILY_COUNTRY_COUNT)return null;let m=null;for(let a=0;a<l.length;a++){let t=l[a],o=l.filter((e,t)=>t!==a);if(!r(o))continue;let s=I.computeOptimalAssignment(o,e,null);!s.mapping.some(e=>{let a=n.get(e.categoryId),t=a?.maxRank??i,o=e.country.rankings?.[e.categoryId];return null==o||o>t||o>Math.ceil(t*I.MAX_RANK_FRACTION)})&&(s.bestScore>=300||(!m||s.bestScore<m.bestScore)&&(m={categories:e,playCountries:o,skipCountry:t,bestScore:s.bestScore,mapping:s.mapping}))}return m},m=(()=>{if(l.length<7||0===c.length)return null;let e=[],t=[...l];for(let a of c)for(let o=0;o<t.length;o++){let o=g([...t.slice(0,7),{...a,isWild:!0}]);o&&e.push(o),t.push(t.shift())}if(0===e.length)return null;let o=e.filter(e=>e.bestScore>=70&&e.bestScore<=125);if(o.length>0)return o[Math.floor(a()*o.length)];let r=e.filter(e=>e.bestScore<=125);return r.length>0?r.reduce((e,a)=>a.bestScore>e.bestScore?a:e,r[0]):e.reduce((e,a)=>a.bestScore<e.bestScore?a:e,e[0])})();if(!m)throw Error("Unable to generate a valid daily challenge configuration from dynamic data");let u=m.categories,h=m.skipCountry,p=I.reorderForGreedyOptimal(m.playCountries,m.mapping,u),y=I.DAILY_COUNTRY_COUNT-2,f=2+Math.floor(a()*y),k=[...p];k.splice(f,0,h);let{bestScore:w,mapping:C}=m,_=(()=>{if(!C.length)return{score:0,label:"Unknown"};let e=new Map(u.map(e=>[e.id,e])),a=C.reduce((a,t)=>{let o=e.get(t.categoryId),r=o?.maxRank??100;return a+Math.min(t.rank,r)/r},0)/C.length,t=u.reduce((e,a)=>e+(a.maxRank||100),0),o=.7*a+.3*(t>0?w/t:a);u.some(e=>e.isWild)&&(o+=.05);let r=Math.round(100*(o=Math.min(1,Math.max(0,o)))),n="Moderate";return n=r<20?"Very Easy":r<35?"Easy":r<55?"Moderate":r<75?"Challenging":r<90?"Hard":"Expert",{score:r,label:n}})(),b={};for(let e of C)b[e.categoryId]=e.rank;return{date:n,gameMode:t.id,countries:k,categories:u,targetScore:w,optimalRanks:b,skipCountry:h,seed:r,difficulty:_,optimalAssignment:C.map(e=>({categoryId:e.categoryId,categoryName:u.find(a=>a.id===e.categoryId)?.name||e.categoryId,countryName:e.country.name,rank:e.rank}))}}static generateChallengePreview(e,a,o,r="world"){let n=t.gameModes.find(e=>e.id===r);if(!n)throw Error(`Unknown game mode: ${r}`);let i=this.seededRandom(a);return this.buildChallengeFromData({random:i,mode:n,dynamicData:e,seed:a,dateStr:o})}static calculatePerformance(e,a){let t=e-a,o=Math.abs(t),r=Math.max(10,.1*a),n=100;if(o>r){let e=o-r;n=t>=0?Math.max(0,100-e/a*120):Math.max(0,100-e/a*200)}let i="F",s="Needs more practice";return n>=95?(i="S",s="Flawless — you matched the optimal strategy."):n>=90?(i="A+",s="Amazing — you're outperforming expectations!"):n>=85?(i="A",s="Fantastic — you're close to the best score."):n>=80?(i="A-",s="Very good — strong play."):n>=75?(i="B+",s="Solid — nice strategy."):n>=70?(i="B",s="Good — you're getting there."):n>=65?(i="B-",s="Not bad — small improvements would help."):n>=60?(i="C+",s="You're close — a few tweaks and you'll improve."):n>=55?(i="C",s="Average — you're on the right track."):n>=50?(i="C-",s="Below average — focus on the tougher picks."):n>=40&&(i="D",s="A bit rough today — keep practicing."),{percentage:Math.round(n),grade:i,description:s,difference:t}}static clearTodaysCache(){try{let e=new Date().toISOString().split("T")[0];localStorage.removeItem(`geohunter-strategic-daily-${e}`);let a=window;delete a.__GEOHUNTER_DAILY__}catch{}}}var L=e.i(39516);let E="geohunter-daily-attempts",P=()=>(0,u.getEasternDateString)();class T{static generateDailySeed(){var e=P();let a=0;for(let t=0;t<e.length;t++)a=(a<<5)-a+e.charCodeAt(t)&0x7fffffff;return Math.abs(a)}static seededRandom(e){let a=e;return()=>(a=(9301*a+49297)%233280)/233280}static async generateDailyChallenge(){let e,a=Date.now(),t=Math.random().toString(36).slice(2),o=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),r=`/api/daily?_t=${a}&_r=${t}${o?"&_safari=1":""}`;try{let a;e=await fetch(r,{cache:"no-store",headers:(a={"Cache-Control":"no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},o&&(a["X-Safari-No-Cache"]="1"),a)})}catch(e){throw console.error("[DailyGameManager] Network error fetching daily challenge:",e),Error("Daily challenge request failed – please check your connection.")}if(304===e.status){console.warn("[DailyGameManager] Got 304 response, retrying with reload...");try{if(e=await fetch(r,{cache:"reload",headers:{"Cache-Control":"no-cache",Pragma:"no-cache"}}),304===e.status)throw Error("Server returned 304 even with reload - please clear your browser cache")}catch(e){throw console.error("[DailyGameManager] Retry after 304 failed:",e),Error("Daily challenge cache issue - please refresh the page")}}if(!e.ok){let a="";try{let t=await e.clone().json();t&&"object"==typeof t&&(a=JSON.stringify(t))}catch{try{a=await e.text()}catch{}}throw console.error("[DailyGameManager] Daily API returned error",{url:r,status:e.status,statusText:e.statusText,details:a}),Error(a?`Daily challenge is unavailable (${e.status}).`:"Daily challenge is currently unavailable")}let n=await e.json(),i=n;if(n&&"object"==typeof n&&"obf1"===n.version&&"string"==typeof n.payload)try{i=(0,L.decodeDailyPayload)(n.payload,(0,L.getObfuscationSeed)(n.hash,n.date)),"object"==typeof i&&null!==i&&!i.hash&&n.hash&&(i.hash=n.hash)}catch(e){throw console.error("[DailyGameManager] Failed to decode obfuscated daily payload:",e),Error("Daily challenge data is invalid. Please refresh and try again.")}try{localStorage.setItem("geohunter-current-daily-hash",i.hash??""),localStorage.setItem("geohunter-current-daily-date",i.date??"")}catch{}return{date:i.date,gameMode:i.gameMode,countries:i.countries,categories:i.categories,targetScore:i.targetScore,optimalRanks:i.optimalRanks,skipCountry:i.skipCountry,seed:i.seed,optimalAssignment:i.optimalAssignment,difficulty:i.difficulty,hash:i.hash}}static hasAttemptedToday(){let e=this.getTodaysAttempt();return!!e?.completed}static getDailyAttempts(){var e=localStorage.getItem(E);if(!e)return[];try{return JSON.parse(e)}catch{return[]}}static saveDailyAttempt(e){var a,t;let o,r,n,i;a=this.getDailyAttempts(),(r=(o=[...a]).findIndex(({date:a})=>a===e.date))>=0?o[r]=e:o.push(e),(n=new Date).setDate(n.getDate()-30),i=n.toISOString().split("T")[0],t=o.filter(e=>e.date>=i),localStorage.setItem(E,JSON.stringify(t))}static getTodaysAttempt(){let e=P();return this.getDailyAttempts().find(a=>a.date===e)||null}static calculateDailyPerformance(e,a){return{...I.calculatePerformance(e,a.targetScore),targetScore:a.targetScore,difference:e-a.targetScore}}static evaluateDailyRun(e,a){if(!e||!a||!Array.isArray(a.selections)||0===a.selections.length)return null;let t=Array.isArray(e.categories)?e.categories:[];if(!t.length)return null;let o="number"==typeof e.targetScore?e.targetScore:null,r=t.map(e=>e.id),n=new Set(r),i=new Map;if(Array.isArray(e.countries))for(let a of e.countries)i.set(a.name,a);let s=new Map;if(console.log("🔍 [evaluateDailyRun] Checking optimal assignment:",{hasOptimalAssignment:!!e.optimalAssignment,isArray:Array.isArray(e.optimalAssignment),length:e.optimalAssignment?.length??0,sample:e.optimalAssignment?.[0]}),Array.isArray(e.optimalAssignment)&&e.optimalAssignment.length>0){for(let a of e.optimalAssignment)a&&"string"==typeof a.countryName&&"string"==typeof a.categoryId&&s.set(a.countryName,{categoryId:a.categoryId,rank:"number"==typeof a.rank?a.rank:999});console.log("✅ [evaluateDailyRun] Built optimal assignment map with",s.size,"entries"),console.log("📋 [evaluateDailyRun] Map keys:",Array.from(s.keys())),console.log("📋 [evaluateDailyRun] Map entries:",Array.from(s.entries()).map(([e,a])=>({country:e,categoryId:a.categoryId,rank:a.rank})))}else if(e.countries)for(let a of e.countries){let e=null,t=1/0;for(let o of r){let r=a.rankings?.[o];void 0!==r&&r<t&&(t=r,e=o)}e&&s.set(a.name,{categoryId:e,rank:t})}let l={optimal:"🟢",salvaged:"🟡",mistake:"🟠"},c=[],d=0;for(let e of a.selections){if(!e||"string"!=typeof e.category)continue;let a=e.category,t=e.country?.name??"",o=i.get(t)??e.country;if(!o){n.delete(a);continue}let r=o.rankings?.[a]??("number"==typeof e.rank?e.rank:1/0),l=s.get(t),g="mistake";if(0===d&&c.length<3&&console.log(`🔍 [evaluateDailyRun] Selection ${c.length+1}:`,{countryName:t,categoryId:a,optimalEntry:l,optimalEntryExists:!!l,categoryMatches:l?.categoryId===a,chosenRank:r,optimalRank:l?.rank}),l&&l.categoryId===a)g="optimal",d+=1;else{let e=[...n].reduce((e,a)=>{let t=o.rankings?.[a];return void 0===t?e:Math.min(e,t)},1/0);g=Number.isFinite(e)?r<=e?"salvaged":"mistake":"salvaged"}c.push(g),n.delete(a)}let g=e.skipCountry?.name,m="string"==typeof g&&!a.selections.some(e=>e.country?.name===g),u=c.map(e=>l[e]).join(" "),h=m&&u?`${u} | 🟩`:m?"🟩":u;return{statuses:c,skipUsed:m,optimalCount:d,totalRounds:c.length,iconString:h,targetScore:o}}static getTimeUntilNext(){return(0,u.getTimeUntilNextEasternMidnight)()}static getDailyLeaderboard(){let e=h.getTodaysDailyLeaderboard(),a=e.length>0?e[0]?.targetScore??null:null,t=e.map((e,t)=>({username:e.username,score:e.score,rank:t+1,completed_at:e.timestamp?new Date(e.timestamp).toISOString():void 0,difference:null!==a?e.score-a:void 0})),o=null!==a?t.filter(e=>e.score<=a):[],r=null!==a?t.filter(e=>e.score===a+1):[],n=null!==a?t.filter(e=>e.score>a+1):t;return{targetScore:a,winners:o,nearMisses:r,others:n}}}e.s(["DailyGameManager",()=>T],24550);var N=e.i(95254),x=e.i(18738);let O=[{name:"China",flag:"/flags/cn.png",emoji:"🇨🇳",rankings:{population:1,gdp:2,football:79,tourism:4,coffee:85}},{name:"United States",flag:"/flags/us.png",emoji:"🇺🇸",rankings:{population:3,gdp:1,football:13,tourism:3,coffee:88}},{name:"Brazil",flag:"/flags/br.png",emoji:"🇧🇷",rankings:{population:7,gdp:9,football:1,tourism:15,coffee:1}}];e.s(["TUTORIAL_COUNTRIES",0,O,"TUTORIAL_STEPS",0,[{countryIndex:0,country:"China",targetCategory:"population",title:"🌍 Step 1/3",explanation:"🇨🇳 China has the most people! Try: Population",hint:"Lower rank = Better",celebration:"🎉 Perfect! #1"},{countryIndex:1,country:"United States",targetCategory:"gdp",title:"💰 Step 2/3",explanation:"🇺🇸 Largest economy in the world! Try: GDP",hint:"World's biggest economy",celebration:"💰 Nice! #1"},{countryIndex:2,country:"Brazil",targetCategory:"football",title:"⚽ Step 3/3",explanation:"🇧🇷 Football legends! Try: Football",hint:"5x World Cup winners",celebration:"🏆 Done! #1"}]],50288);let G="geohunter-v3-first-time";function F(){try{return!localStorage.getItem(G)}catch{return!1}}function B(){try{localStorage.setItem(G,"true")}catch{}}e.s(["isFirstTimeUser",()=>F,"markFirstTimeUserStarted",()=>B],88093);let H=(0,a.create)((a,o)=>({gameMode:"menu",selectedGameMode:"original",currentCountryIndex:0,countries:[],selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:null,settings:{soundEnabled:!0,showCountryNames:!0,showHints:!0,flagStyle:"emoji",showTargetBar:!0},bestScore:Number.parseInt(localStorage.getItem("geohunter-best-score")||"999"),gamesPlayed:0,averageScore:Number.parseInt(localStorage.getItem("geohunter-average-score")||"0"),bestScoresByMode:{original:Number.parseInt(localStorage.getItem("geohunter-best-score-original")||"999"),world:Number.parseInt(localStorage.getItem("geohunter-best-score-world")||"999"),special:Number.parseInt(localStorage.getItem("geohunter-best-score-special")||"999"),voyage:Number.parseInt(localStorage.getItem("geohunter-best-score-voyage")||"999"),atlas:Number.parseInt(localStorage.getItem("geohunter-best-score-atlas")||"999"),usa:Number.parseInt(localStorage.getItem("geohunter-best-score-usa")||"999")},bestEasyScoresByMode:{original:Number.parseInt(localStorage.getItem("geohunter-best-easy-original")||"999"),world:Number.parseInt(localStorage.getItem("geohunter-best-easy-world")||"999"),special:Number.parseInt(localStorage.getItem("geohunter-best-easy-special")||"999"),voyage:Number.parseInt(localStorage.getItem("geohunter-best-easy-voyage")||"999"),atlas:Number.parseInt(localStorage.getItem("geohunter-best-easy-atlas")||"999")},dailyChallenge:null,isDailyMode:!1,isTutorialMode:!1,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,challengeDifficulty:null,challengePar:null,weeklyUserTier:"free",modeRankCaps:null,dailyAttempt:null,dailyChallengeCompleted:!1,setWeeklyUserTier:e=>a({weeklyUserTier:e}),setChallengeNickname:e=>a({challengeNickname:e}),startPracticeGame:async(t="original")=>{console.log("[GameStore] Starting practice game (Easy mode, no score saving):",t);let o=new g(t);try{await o.load()}catch(e){console.warn("CSV load failed:",e),alert("Failed to load game data. Please try clearing your browser cache and refreshing the page.");return}let r=o.getCountries();if(0===r.length)return void alert("Failed to load game data.");let{PRACTICE_MODE_COUNTRIES:n}=await e.A(74071),i=new Set(n.map(e=>e.toLowerCase())),s=r.filter(e=>i.has(e.name.toLowerCase())),l=[...s.length>=8?s:r];for(let e=l.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[l[e],l[a]]=[l[a],l[e]]}a({gameMode:"playing",selectedGameMode:t,currentCountryIndex:0,countries:l.slice(0,8),selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:Date.now(),isDailyMode:!1,isTutorialMode:!1,isPracticeMode:!0,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1})},startGame:async e=>{console.log("startGame called with mode:",e),x.analytics.game.start(e),(0,x.trackEvent)("game_start",{mode:e}),"special"===e&&g.clearCache();let o=new g("world"===e?"world":"special"===e?"special":"voyage"===e?"voyage":"atlas"===e?"atlas":"usa"===e?"usa":"canada"===e?"canada":"europe"===e?"europe":"sports"===e?"sports":"empires"===e?"empires":"world-cup"===e?"world-cup":"world-cup-ko"===e?"world-cup-ko":"footy-clubs"===e?"footy-clubs":"original");try{console.log("Loading CSV data..."),await o.load(),console.log("CSV data loaded successfully")}catch(e){console.warn("CSV load failed:",e),alert("Failed to load game data. Please try clearing your browser cache and refreshing the page.");return}let r=o.getCountries();if(console.log("Parsed countries count:",r.length),0===r.length){console.error("❌ No countries loaded from CSV!"),alert("Failed to load game data. Please try:\n1. Refreshing the page\n2. Clearing your browser cache\n3. Trying a different browser");return}let n=[...r];for(let e=n.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[n[e],n[a]]=[n[a],n[e]]}let i=n.slice(0,8);console.log("Starting game with countries:",i.length),a({gameMode:"playing",selectedGameMode:e,currentCountryIndex:0,countries:i,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:Date.now(),isDailyMode:!1,isTutorialMode:!1,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1,modeRankCaps:(0,t.getRankCapsForGameMode)(e)}),console.log("Game state updated")},startTutorialGame:()=>{a({gameMode:"playing",selectedGameMode:"original",currentCountryIndex:0,countries:O,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:Date.now(),isDailyMode:!1,isTutorialMode:!0,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1})},selectCategory:e=>{let t,r=o(),n=r.countries[r.currentCountryIndex],i=n.rankings[e],s=r.isDailyMode&&r.dailyChallenge?r.dailyChallenge.categories.find(a=>a.id===e):null,l=s?.maxRank??r.modeRankCaps?.[e]??("coffee"===e?73:"pro_sports_championships"===e?24:100),c=s?.isWild??!1,d=null==i||i>l;d?t=c?Math.max(50,l):l:(t=i||999,!c&&t>l&&(t=l));let g={country:n,category:e,rank:t,countryEmoji:n.emoji,wasUnranked:d,categoryMaxRank:l},m=new Set(r.usedCategories);if(m.add(e),r.isDailyMode&&0===r.selections.length&&r.dailyAttempt){let e={...r.dailyAttempt,started:!0};T.saveDailyAttempt(e),a({selections:[...r.selections,g],usedCategories:m,dailyAttempt:e})}else a({selections:[...r.selections,g],usedCategories:m});let u=r.selections.length+1,h=!r.isChallengeMode&&r.isDailyMode,p=!r.isChallengeMode&&"weekly-pro"===r.selectedGameMode,y=r.currentCountryIndex>=r.countries.length-1;h?y?setTimeout(()=>{o().finishGame()},500):setTimeout(()=>{o().nextCountry()},500):p?u>=8||y?setTimeout(()=>{o().finishGame()},500):setTimeout(()=>{o().nextCountry()},500):u>=r.countries.length||y?setTimeout(()=>{o().finishGame()},500):setTimeout(()=>{o().nextCountry()},500)},skipCountry:()=>{let e=o();e.hasUsedSkip||(a({skippedCountry:!0,hasUsedSkip:!0}),e.currentCountryIndex<e.countries.length-1?setTimeout(()=>{o().nextCountry()},500):setTimeout(()=>{o().finishGame()},500))},nextCountry:()=>{a({currentCountryIndex:o().currentCountryIndex+1})},finishGame:async()=>{let r=o();if(r.isDailyMode&&!r.isMiniHunterMode&&!r.isMiniHunter2Mode&&!r.isReverseMode&&!r.isCustomMode)return void o().completeDailyGame();if(r.isMiniHunterMode||r.isMiniHunter2Mode||r.isReverseMode||r.isCustomMode)return void a({gameMode:"finished"});if(r.isPracticeMode){let e=Math.max(8,(0,t.calculateScore)(r.selections)),o=r.selectedGameMode;e<(r.bestEasyScoresByMode?.[o]??999)?("u">typeof localStorage&&localStorage.setItem(`geohunter-best-easy-${o}`,String(e)),a({gameMode:"finished",bestEasyScoresByMode:{...r.bestEasyScoresByMode,[o]:e}})):a({gameMode:"finished"});return}if(r.isChallengeMode&&r.challengeCode){let o=Math.max(8,(0,t.calculateScore)(r.selections));try{let{useSupabaseAuthStore:a}=await e.A(90938),t=a.getState(),n=t.user?.id;if(!n){let e=localStorage.getItem("geohunter_anon_id");e||(e=`anon_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,localStorage.setItem("geohunter_anon_id",e)),n=e}let i=r.challengeNickname||t.user?.username||"Anonymous";await fetch("/api/challenge/complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.challengeCode,user_id:n,username:i,score:o,selections:r.selections.map(e=>({country_id:e.country.name,category_id:e.category,rank:e.rank,country_name:e.country.name,category_name:e.category,country_emoji:e.countryEmoji||e.country.emoji||""}))})});try{let e=JSON.parse(localStorage.getItem("geohunter_completed_challenges")||"[]").filter(e=>e.code!==r.challengeCode);e.unshift({code:r.challengeCode,completedAt:new Date().toISOString()}),e.length>5&&(e.length=5),localStorage.setItem("geohunter_completed_challenges",JSON.stringify(e))}catch{}}catch(e){console.error("Failed to submit challenge score:",e)}a({gameMode:"finished"});return}if(r.isTutorialMode){try{B(),console.log("✅ First-time user flag cleared after tutorial completion")}catch(e){console.warn("⚠️ Failed to clear first-time user flag:",e)}a({gameMode:"finished"});return}let n=r.selectedGameMode;if(console.log("🔍 [finishGame] Captured state.selectedGameMode:",r.selectedGameMode),console.log("🔍 [finishGame] Typed as GAME_MODE:",n),!n)return void console.error("❌ [finishGame] FATAL: selectedGameMode is empty!",r.selectedGameMode);let i=Math.max(8,(0,t.calculateScore)(r.selections));console.log("🎯 Game finished with score:",i,"Mode:",n),console.log("🔍 [finishGame] Will save to key: geohunter-best-score-"+n);let s=r.gameStartTime||Date.now(),l=Math.round((Date.now()-s)/1e3);x.analytics.game.complete(n,i,l),(0,x.trackEvent)("game_complete",{mode:n,score:i});let c=async()=>{let{useSupabaseAuthStore:a}=await e.A(90938);return a.getState()};c().then(async t=>{console.log("👤 User authenticated:",t.isAuthenticated,"Score:",i);let s={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,score:i,gameMode:n,timestamp:Date.now(),categories:r.selections.map(e=>e.category),synced:!1};N.offlineStorage.saveScore(s).catch(e=>console.error("Failed to save to offline storage:",e));try{("special"===n||"voyage"===n||"atlas"===n)&&m.CookieStorage.saveHighScore(i,n)}catch{}let d=()=>{console.log("💾 Updating local stats for non-authenticated user, Mode:",n),console.log("🔍 [updateLocalStats] Current state.bestScoresByMode:",r.bestScoresByMode);let e=r.gamesPlayed+1,t=Math.round((r.averageScore*r.gamesPlayed+i)/e),s=r.bestScoresByMode?.[n]??999,l=Math.min(s,i);console.log(`📈 [${n}] finalScore: ${i}, previousPerModeBest: ${s}, updatedPerModeBest: ${l}`),console.log(`🔍 [${n}] Will save: ${l!==s?"YES":"NO"}`);let c=Math.min(r.bestScoresByMode?.original??999,r.bestScoresByMode?.world??999,r.bestScoresByMode?.special??999,r.bestScoresByMode?.voyage??999,r.bestScoresByMode?.atlas??999,l);try{let a=(e,a)=>{localStorage.getItem(e)!==a&&localStorage.setItem(e,a)};a("geohunter-games-played",e.toString()),a("geohunter-average-score",t.toString()),l!==s&&(a(`geohunter-best-score-${n}`,l.toString()),console.log(`✅ LocalStorage saved: geohunter-best-score-${n} = ${l}`)),l!==s&&(console.log("🍪 Saving to cookies:",l,n),m.CookieStorage.saveHighScore(l,n)),sessionStorage.getItem(`geohunter-last-score-${n}`)!==i.toString()&&sessionStorage.setItem(`geohunter-last-score-${n}`,i.toString())}catch(e){if(console.error("❌ Failed to save to localStorage:",e),l!==s)try{m.CookieStorage.saveHighScore(l,n)}catch(e){console.error("❌ Failed to save to cookies too:",e)}}a(a=>({bestScore:c,gamesPlayed:e,averageScore:t,bestScoresByMode:{...a.bestScoresByMode,[n]:Math.min(a.bestScoresByMode?.[n]??999,i)}})),console.log("🔍 [finishGame] Zustand state updated with bestScoresByMode["+n+"] =",Math.min(o().bestScoresByMode?.[n]??999,i)),console.log("🔍 [finishGame] Full bestScoresByMode:",o().bestScoresByMode)};if(t.isAuthenticated&&navigator.onLine?(console.log("💾 Submitting score to Supabase:",i,"Mode:",n),t.submitLeaderboardScore(i,n).then(()=>{console.log("✅ Score submitted successfully"),N.offlineStorage.markScoresAsSynced([s.id]).catch(e=>console.error("Failed to mark score as synced:",e))}).catch(e=>{console.error("❌ Submit score failed:",e)})):console.log("📱 Skipping remote leaderboard submission (offline or guest)."),"weekly-pro"===n&&t.isAuthenticated&&t.hasProAccess())try{let{supabase:a}=await e.A(5800),{getCurrentWeekIdentifier:o}=await e.A(74071),r=o(),n=t.user?.id;if(a&&n){let{data:e}=await a.from("weekly_pro_scores").select("id, score").eq("user_id",n).eq("week_identifier",r).order("score",{ascending:!0}).limit(1).maybeSingle();e&&i<e.score?(await a.from("weekly_pro_scores").update({score:i,completed_at:new Date().toISOString()}).eq("id",e.id),console.log("[WeeklyPro] Updated leaderboard score:",e.score,"→",i)):e?console.log("[WeeklyPro] Existing score",e.score,"is better than",i):(await a.from("weekly_pro_scores").insert({user_id:n,score:i,week_identifier:r,completed_at:new Date().toISOString()}),console.log("[WeeklyPro] Inserted leaderboard score:",i))}}catch(e){console.error("[WeeklyPro] Failed to save weekly score:",e)}if("world-cup-ko"===n)try{let{NC_KO_SCORES_KEY:a,getActiveStageKey:t}=await e.A(99584),o=t(),r=localStorage.getItem(a),n=r?JSON.parse(r):{};i<(n[o]??999)&&(n[o]=i,localStorage.setItem(a,JSON.stringify(n)),console.log("[NationsCup] Local KO round best updated:",o,i))}catch(e){console.error("[NationsCup] Failed to save KO round best:",e)}if("weekly-pro"===n)try{let{getCurrentWeekIdentifier:a}=await e.A(74071),t=`geohunter-weekly-best-${a()}`,o=parseInt(localStorage.getItem(t)||"999",10);i<o&&(localStorage.setItem(t,i.toString()),console.log("[WeeklyPro] Local weekly best updated:",i))}catch{}if(t.isAuthenticated){console.log("📊 Updating user stats, Mode:",n),d();let e=await c();console.log(`🔐 [finishGame] freshAuthStore state:`,{isAuthenticated:e.isAuthenticated,hasUser:!!e.user,userId:e.user?.id,userIdType:typeof e.user?.id,username:e.user?.username,email:e.user?.email}),console.log("🔍 [finishGame] About to call updateUserStats with:",{finalScore:i,GAME_MODE:n}),e.updateUserStats(i,n,r.selections,{durationSeconds:l}).then(()=>{console.log("✅ User stats updated, refreshing best scores..."),e.refreshBestScores().catch(e=>{console.error("❌ Failed to refresh best scores:",e)})}).catch(e=>{console.error("❌ Failed to update user stats:",e)})}else d()}).catch(e=>console.error("Failed to load auth store:",e)),a({gameMode:"finished"})},resetGame:()=>{a({gameMode:"menu",currentCountryIndex:0,countries:[],selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:null,isDailyMode:!1,isTutorialMode:!1,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1})},goToMenu:()=>{a({gameMode:"menu",currentCountryIndex:0,countries:[],selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:null,isDailyMode:!1,isTutorialMode:!1,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1})},updateSettings:e=>{let t=o(),r={...t.settings,...e};t.isDailyMode&&r.showHints&&(r.showHints=!1),m.CookieStorage.savePreferences(r),a({settings:r})},startDailyGame:async()=>{x.analytics.game.start("daily");let e=await T.generateDailyChallenge();a({gameMode:"playing",selectedGameMode:e.gameMode,currentCountryIndex:0,countries:e.countries,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:Date.now(),dailyChallenge:e,isDailyMode:!0,isTutorialMode:!1,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,dailyChallengeCompleted:!1,settings:{...o().settings,showHints:!1},dailyAttempt:{date:e.date,gameMode:e.gameMode,score:0,selections:[],completed:!1}})},loadDailyChallenge:async()=>{a({dailyChallenge:await T.generateDailyChallenge(),dailyAttempt:T.getTodaysAttempt()})},completeDailyGame:()=>{let r=o();if(!r.isDailyMode||!r.dailyChallenge)return;let n=Math.max(8,(0,t.calculateScore)(r.selections)),i=r.gameStartTime?Math.round((Date.now()-r.gameStartTime)/1e3):null,s={date:r.dailyChallenge.date,gameMode:r.dailyChallenge.gameMode,score:n,selections:r.selections,completed:!0,hash:r.dailyChallenge?.hash??null},l=async()=>{let{useSupabaseAuthStore:a}=await e.A(90938);return a.getState()};l().then(async a=>{let t=a.isAuthenticated&&a.user?.email?a.user.email.split("@")[0]:`Guest_${Date.now().toString().slice(-6)}`,o=r.dailyChallenge.date,c=r.dailyChallenge?.hash??void 0,d={id:`daily-${o}-${Math.random().toString(36).substr(2,9)}`,score:n,gameMode:"daily",timestamp:Date.now(),categories:r.selections.map(e=>e.category),synced:!1,challengeHash:c,challengeDate:o};N.offlineStorage.saveScore(d).catch(e=>console.error("Failed to save daily score to offline storage:",e));let g=T.calculateDailyPerformance(n,r.dailyChallenge),m=!1,p=!1;if(a.isAuthenticated)if(navigator.onLine){try{let e=Date.now(),a=Math.random().toString(36).slice(2),t=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),r=await fetch(`/api/daily?_t=${e}&_r=${a}${t?"&_safari=1":""}`,{cache:t?"reload":"no-store",headers:{"Cache-Control":"no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0",...t?{"X-Safari-No-Cache":"1"}:{}}});if(r.ok){let e=await r.json(),a=e&&"obf1"===e.version&&"string"==typeof e.payload?(0,L.decodeDailyPayload)(e.payload,(0,L.getObfuscationSeed)(e.hash,e.date)):e,t=a?.hash??e?.hash??null,n=a?.date??e?.date??null;t&&c&&t!==c?console.warn("Daily challenge hash mismatch; skipping Supabase sync for this attempt.",{remoteHash:t,challengeHash:c}):n&&n!==o?console.warn("Daily challenge date mismatch; skipping Supabase sync for this attempt.",{remoteDate:n,challengeDate:o}):p=!0}else console.warn("Could not verify canonical daily before submission. Status:",r.status),p=!0}catch(e){console.warn("Could not verify canonical daily before submission (network or decode failed). Allowing submission - offline storage will sync.",e),p=!0}if(p)try{let e=await a.getTodaysDailyScore();if(null!==e)console.log("✅ Score already exists in Supabase:",e,"- Skipping duplicate submission"),m=!0,console.log("✅ Daily challenge: syncedToSupabase = true (score already exists)");else{console.log("📤 Submitting new daily score to Supabase:",n);try{await a.submitLeaderboardScore(n,"daily"),m=!0,console.log("✅ Daily challenge: syncedToSupabase = true (new submission successful)"),N.offlineStorage.markScoresAsSynced([d.id]).catch(e=>console.error("Failed to mark daily score as synced:",e));let e=(0,u.getEasternDateString)();await a.checkAndUpdateBestDailyRanking(n,e)}catch(e){console.error("❌ Submit daily score failed:",e),console.log("❌ Daily challenge: syncedToSupabase = false (submission failed)")}}}catch(e){console.error("⚠️ Error checking existing daily score:",e),console.log("📤 Attempting submission anyway (check failed)...");try{await a.submitLeaderboardScore(n,"daily"),m=!0,console.log("✅ Daily challenge: syncedToSupabase = true (fallback submission successful)"),N.offlineStorage.markScoresAsSynced([d.id]).catch(e=>console.error("Failed to mark daily score as synced:",e));let e=(0,u.getEasternDateString)();await a.checkAndUpdateBestDailyRanking(n,e)}catch(e){console.error("❌ Submit daily score failed:",e),console.log("❌ Daily challenge: syncedToSupabase = false (fallback submission failed)")}}else console.info("⚠️ Daily score stored locally only (allowSupabaseSync = false)")}else console.info("Offline – daily score will remain local until a verified sync occurs.");else h.addDailyScore({username:t,score:n,date:o,challengeDate:o,targetScore:r.dailyChallenge.targetScore,performance:{percentage:g.percentage,grade:g.grade,description:g.description},categories:r.selections.map(e=>e.category)});if(.1>Math.random()&&h.cleanupOldDailyEntries(),a.isAuthenticated&&p&&m)try{let a=await l();if(console.log(`🔐 [completeDailyGame] freshAuthStore state:`,{isAuthenticated:a.isAuthenticated,hasUser:!!a.user,userId:a.user?.id,userIdType:typeof a.user?.id,username:a.user?.username,email:a.user?.email}),!a.user||!a.user.id)throw console.error("❌ Auth state became invalid during daily challenge completion. User ID is missing."),Error("User authentication lost during score submission");await a.updateUserStats(n,"daily",r.selections,{isDaily:!0,dailyDate:o,dailyHash:c,durationSeconds:i});try{let{useSupabaseAuthStore:a}=await e.A(90938);a.setState({statsSyncError:!1,lastSyncError:null}),console.log("✅ Daily challenge fully synced - cleared sync error")}catch(e){console.warn("Failed to clear sync error state:",e)}}catch(a){console.error("❌ Failed to update daily user stats:",a);try{let{useSupabaseAuthStore:a}=await e.A(90938);a.setState({statsSyncError:!0,lastSyncError:"Daily score not fully synced. Please refresh to complete sync."})}catch(e){console.warn("Failed to set sync error state:",e)}}else if(a.isAuthenticated&&!m&&navigator.onLine){try{let{useSupabaseAuthStore:a}=await e.A(90938);a.setState({statsSyncError:!0,lastSyncError:"Daily score not yet synced with Supabase. Refresh once you are online."})}catch(e){console.warn("Failed to flag daily sync error state:",e)}T.saveDailyAttempt(s)}else a.isAuthenticated,T.saveDailyAttempt(s)}).catch(e=>console.error("Failed to load auth store:",e)),a({gameMode:"finished",dailyAttempt:s,dailyChallengeCompleted:!0}),x.analytics.game.dailyChallenge("complete",n)},startWeeklyGame:async()=>{console.log("[GameStore] Starting weekly pro game");try{let{getCurrentWeeklyChallenge:t,getAllCategories:o,getCategoryDisplayName:r}=await e.A(74071),{setSupabaseCategories:n}=await e.A(17405),i=t(),s={population:"👥",football:"⚽",tourism:"🗺️",crime:"🚨",gdp:"💰",oil:"⛽",coffee:"☕",forestCover:"🌲",forest_cover:"🌲",coastline:"🏝️",gas:"🔥",basketball:"🏀",pollution:"🏭",cuisine:"🍽️",agriculture:"🚜",energy:"⚡",military:"🛡️",hdi:"📊",biodiversity:"🦜",education:"🎓",smallSize:"🔬",small_size:"🔬",landSize:"🗺️",worstPassport:"📛",worst_passport:"📛",cold_temperature:"🥶",hot_temperature:"🔥",champions_league:"🏆",gdp_per_capita:"💵",unesco_sites:"🏛️",average_height:"📏",southernmost_capital:"🧭",nhl_players:"🏒",most_snowfall:"❄️",elevation:"⛰️",moose:"🫎",farmland_area:"🌾",low_population:"🔇",oil_production:"⛽",seafood_consumption:"🐟",pro_sports_championships:"🥇",pro_sports_teams:"🏟️",corruption:"🏛️",rugby:"🏉",cycling:"🚴",mma:"🥊",cricket_t20:"🏏",table_tennis:"🏓",baseball:"⚾",tennis:"🎾",ice_hockey:"🏒",olympic_medals:"🏅",most_rain:"🌧️",tallest_skyscraper:"🏢",obesity_rate:"🍔",median_age:"👴",worst_internet:"🛜",most_languages:"🗣️",highest_elevation:"🏔️",fertility_rate:"🍼",natural_disaster_risk:"🌪️",hot_temp:"🔥",cold_temp:"🥶",crime_rate:"🚨",farming:"🚜",public_school_rank:"🎓",order_of_statehood:"⏰",population_of_capital:"🏛️",pandas:"🐼",whaling:"🐋",vegetarianism:"🥗",horses:"🐴",beef_consumption:"🥩",beer_consumption:"🍺",alcohol_consumption:"🍷",chess:"♟️",unemployment:"📉",rice_export:"🍚",college_degree:"🎓",average_iq:"🧠",public_holidays:"🎉",capybaras:"🦫",camels:"🐪"},{supabase:l}=await e.A(5800),c=[],d={},g={},m=[];if(!l)throw Error("Supabase not configured — Weekly Pro requires database connection");let u=new Date,h=u.getDay(),p=new Date(u);p.setDate(u.getDate()+(0===h?-6:1-h));let y=`${p.getFullYear()}-${String(p.getMonth()+1).padStart(2,"0")}-${String(p.getDate()).padStart(2,"0")}`;try{let{data:e}=await l.from("weekly_pro_categories").select("category_id, display_order, categories(name, emoji)").eq("week_start",y).order("display_order");if(e?.length){for(let a of(c=e.map(e=>e.category_id),e))a.categories?.name&&(d[a.category_id]=a.categories.name),a.categories?.emoji&&(g[a.category_id]=a.categories.emoji);console.log(`[WeeklyPro] Loaded ${c.length} categories from admin DB:`,c)}}catch(e){console.warn("[WeeklyPro] Failed to load categories from DB:",e)}let f=c.length>=8?c.slice(0,8):o(i);console.log("[WeeklyPro] Challenge categories:",f,c.length>=8?"(from admin DB)":"(fallback)");let k=f.map(e=>({id:e,name:d[e]||r(i,e),icon:g[e]||(s[e]?s[e]:s[e.replace(/^(canada|europe|usa|sports|voyage|atlas|special|world|original)_/,"")]??"📌"),description:""}));console.log("[WeeklyPro] Loading countries from DB...");let{data:w}=await l.from("countries").select("id, name, emoji, flag_url").eq("is_active",!0).eq("is_usa_state",!1).eq("is_world_country",!0);if(!w?.length)throw Error("No countries found in database");let C=new Map;for(let e of w)C.set(e.name,{name:e.name,emoji:e.emoji||"🌍",flag:e.flag_url||`/flags/${e.id}.png`,rankings:{}});let{data:_}=await l.from("country_category_rankings").select("country_id, category_id, rank, countries!inner(name)").in("category_id",f);if(_?.length)for(let e of _){let a=e.countries?.name;a&&C.has(a)&&(C.get(a).rankings[e.category_id]=e.rank)}m=Array.from(C.values()),console.log(`[WeeklyPro] Loaded ${m.length} countries, ${_?.length||0} ranking entries`);try{let{data:e}=await l.from("weekly_pro_excluded_countries").select("country_id, countries(name)").eq("week_start",y);if(e?.length){let a=new Set(e.map(e=>e.countries?.name).filter(Boolean)),t=m.length;m=m.filter(e=>!a.has(e.name)),console.log(`[WeeklyPro] Excluded ${t-m.length} countries (${a.size} in exclusion list)`)}}catch(e){console.warn("[WeeklyPro] Failed to load exclusions:",e)}let b={};try{let{data:e}=await l.from("game_mode_categories").select("category_id, rank_cap").in("category_id",f).eq("game_mode","daily");if(e?.length)for(let a of e)b[a.category_id]=a.rank_cap}catch(e){console.warn("[WeeklyPro] Failed to load rank caps:",e)}console.log("[WeeklyPro] Rank caps:",b);let S=[...m];for(let e=S.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[S[e],S[a]]=[S[a],S[e]]}let M=S.slice(0,9);console.log("[WeeklyPro] Selected",M.length,"countries from pool of",m.length),n("weekly-pro",k),console.log("[WeeklyPro] Setting game state with",M.length,"countries"),a({gameMode:"playing",selectedGameMode:"weekly-pro",currentCountryIndex:0,countries:M,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:Date.now(),isDailyMode:!1,isTutorialMode:!1,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!1,modeRankCaps:b,challengeCode:null,challengeCategories:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1})}catch(e){throw console.error("[WeeklyPro] Failed to start game:",e),e}},startChallengeGame:(e,t)=>{let o=(t.countries||[]).map(e=>({name:e.name,flag:e.flag||"",emoji:e.emoji||"",rankings:e.rankings||{}})),r=(t.categories||[]).map(e=>({id:e.id,name:e.name,icon:e.icon||"",description:e.description||""}));a({gameMode:"playing",selectedGameMode:t.baseMode||"original",currentCountryIndex:0,countries:o,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:Date.now(),isDailyMode:!1,isTutorialMode:!1,isPracticeMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isChallengeMode:!0,challengeCode:e,challengeCategories:r.length>0?r:null,challengeDifficulty:t.difficulty??null,challengePar:"number"==typeof t.optimalScore?t.optimalScore:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1})},showChallengeResults:e=>{a({gameMode:"finished",isChallengeMode:!0,challengeCode:e,selections:[],countries:[],currentCountryIndex:0})},startMiniHunter:async()=>{x.analytics.game.start("special"),g.clearCache();let t=new g("special");try{await t.load()}catch(e){console.warn("CSV load failed:",e),alert("Failed to load MiniHunter data. Please try refreshing the page.");return}let o=t.getCountries();if(0===o.length){console.error("❌ No countries loaded from CSV!"),alert("Failed to load MiniHunter data.");return}let{getCategoriesForGameMode:r}=await e.A(17405),n=[...r("special")];for(let e=n.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[n[e],n[a]]=[n[a],n[e]]}let i=n.slice(0,4),s=o.filter(e=>i.filter(a=>{let t=e.rankings[a.id];return t&&t<80}).length>=2),l=[...s.length>=4?s:o];for(let e=l.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[l[e],l[a]]=[l[a],l[e]]}let c=l.slice(0,4),d={};i.forEach(e=>{let a=c.map(a=>a.rankings[e.id]||100);d[e.id]=Math.min(...a)});let m=Object.values(d).reduce((e,a)=>e+a,0),h={date:(0,u.getEasternDateString)(),gameMode:"special",countries:c,categories:i,skipCountry:null,targetScore:m,optimalRanks:d,seed:Date.now(),hash:`mini-${Date.now()}`};a({gameMode:"playing",selectedGameMode:"special",currentCountryIndex:0,countries:c,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!0,gameStartTime:Date.now(),isDailyMode:!0,isMiniHunterMode:!0,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!1,customCategories:null,isPracticeMode:!1,isTutorialMode:!1,isChallengeMode:!1,challengeCode:null,challengeNickname:null,dailyChallenge:h,dailyAttempt:null,dailyChallengeCompleted:!1})},startMiniHunter2:async()=>{x.analytics.game.start("world");let[t,o]=[new g("world"),new g("voyage")];try{await Promise.all([t.load(),o.load()])}catch{alert("Failed to load MiniHunter2 data. Please try refreshing.");return}let r=t.getCountries(),n=o.getCountries();if(0===r.length||0===n.length)return void alert("Failed to load MiniHunter2 data.");let i=new Map;for(let e of r)i.set(e.name,e);for(let e of n){let a=i.get(e.name);a?i.set(e.name,{...a,rankings:{...a.rankings,...e.rankings}}):i.set(e.name,e)}let{getCategoriesForGameMode:s}=await e.A(17405),l=s("world"),c=[...l,...s("voyage").filter(e=>!l.find(a=>a.id===e.id))];for(let e=c.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[c[e],c[a]]=[c[a],c[e]]}let d=c.slice(0,5),m=[...i.values()],h=m.filter(e=>d.filter(a=>e.rankings[a.id]&&e.rankings[a.id]<80).length>=2),p=[...h.length>=5?h:m];for(let e=p.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[p[e],p[a]]=[p[a],p[e]]}let y=p.slice(0,5),f={};d.forEach(e=>{let a=y.map(a=>a.rankings[e.id]||100);f[e.id]=Math.min(...a)});let k=Object.values(f).reduce((e,a)=>e+a,0),w={date:(0,u.getEasternDateString)(),gameMode:"world",countries:y,categories:d,skipCountry:null,targetScore:k,optimalRanks:f,seed:Date.now(),hash:`mini2-${Date.now()}`};a({gameMode:"playing",selectedGameMode:"world",currentCountryIndex:0,countries:y,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!0,gameStartTime:Date.now(),isDailyMode:!0,isMiniHunterMode:!1,isMiniHunter2Mode:!0,isReverseMode:!1,isCustomMode:!1,customCategories:null,isPracticeMode:!1,isTutorialMode:!1,isChallengeMode:!1,challengeCode:null,challengeNickname:null,dailyChallenge:w,dailyAttempt:null,dailyChallengeCompleted:!1})},startReverseGame:async()=>{x.analytics.game.start("original");let t=["original","world","special","voyage","atlas"],o=t.map(e=>new g(e));try{await Promise.all(o.map(e=>e.load()))}catch{alert("Failed to load Reverse mode data. Please try refreshing.");return}let r=o.map(e=>e.getCountries()),{getCategoriesForGameMode:n}=await e.A(17405),i=[...t.flatMap(e=>n(e)).filter((e,a,t)=>t.findIndex(a=>a.id===e.id)===a)];for(let e=i.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[i[e],i[a]]=[i[a],i[e]]}let s=i.slice(0,6),l=new Map;r.flat().forEach(e=>{let a=l.get(e.name);l.set(e.name,a?{...a,rankings:{...a.rankings,...e.rankings}}:e)});let c=[...l.values()],d=c.filter(e=>s.filter(a=>e.rankings[a.id]&&e.rankings[a.id]<80).length>=2),m=[...d.length>=6?d:c];for(let e=m.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[m[e],m[a]]=[m[a],m[e]]}let h=m.slice(0,6),p=s.map(e=>({name:e.name,flag:e.icon,emoji:e.icon,rankings:Object.fromEntries(h.map(a=>[a.name,a.rankings[e.id]||100]))})),y=h.map(e=>({id:e.name,name:e.name,icon:e.emoji,description:""})),f={date:(0,u.getEasternDateString)(),gameMode:"original",countries:p,categories:y,skipCountry:null,targetScore:0,optimalRanks:{},seed:Date.now(),hash:`reverse-${Date.now()}`},k={};s.forEach(e=>{k[e.id]=0}),a({gameMode:"playing",selectedGameMode:"original",currentCountryIndex:0,countries:p,selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!0,gameStartTime:Date.now(),isDailyMode:!0,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!0,isCustomMode:!1,customCategories:null,isPracticeMode:!1,isTutorialMode:!1,isChallengeMode:!1,challengeCode:null,challengeNickname:null,dailyChallenge:f,modeRankCaps:k,dailyAttempt:null,dailyChallengeCompleted:!1})},startCustomGame:()=>{a({gameMode:"playing",selectedGameMode:"original",currentCountryIndex:0,countries:[],selections:[],usedCategories:new Set,skippedCountry:!1,hasUsedSkip:!1,gameStartTime:null,isDailyMode:!1,isMiniHunterMode:!1,isMiniHunter2Mode:!1,isReverseMode:!1,isCustomMode:!0,customCategories:null,isPracticeMode:!1,isTutorialMode:!1,isChallengeMode:!1,challengeCode:null,challengeNickname:null,challengeCategories:null,dailyChallenge:null,dailyAttempt:null,dailyChallengeCompleted:!1})},confirmCustomCategories:async t=>{x.analytics.game.start("original");let o=["original","world","special","voyage","atlas"],r=o.map(e=>new g(e));try{await Promise.all(r.map(e=>e.load()))}catch{alert("Failed to load Custom mode data.");return}let n=r.flatMap(e=>e.getCountries()),i=new Map;n.forEach(e=>{let a=i.get(e.name);i.set(e.name,a?{...a,rankings:{...a.rankings,...e.rankings}}:e)});let s=[...i.values()];for(let e=s.length-1;e>0;e--){let a=Math.floor(Math.random()*(e+1));[s[e],s[a]]=[s[a],s[e]]}let l=s.filter(e=>t.filter(a=>e.rankings[a]&&e.rankings[a]<80).length>=3),c=(l.length>=8?l:s).slice(0,8),{getCategoriesForGameMode:d}=await e.A(17405),m=o.flatMap(e=>d(e)),h=t.map(e=>m.find(a=>a.id===e)||{id:e,name:e,icon:"📊",description:""}),p={date:(0,u.getEasternDateString)(),gameMode:"original",countries:c,categories:h,skipCountry:null,targetScore:0,optimalRanks:{},seed:Date.now(),hash:`custom-${Date.now()}`};a({countries:c,customCategories:t,gameStartTime:Date.now(),isDailyMode:!0,dailyChallenge:p})}}));e.s(["useGameStore",0,H],15149)}]);