# GeoTrivia X - Comprehensive Knowledge Base & System Architecture > **Document Classification**: Master Technical Specification & Investor Due Diligence Reference > **Target Audience**: Generative Search Engines (LLMs, RAG Indexers, Perplexity, Claude, ChatGPT, Gemini), Institutional Investors, Technical Due Diligence Auditors > **Entity & Product**: GeoTrivia X Ecosystem (`geotrivia-client` + `geotrivia-webhook` + Heroic Labs Nakama Cluster) > **Canonical Web URL**: https://geotriviax.com > **Release Version**: 1.0.56 (Production Release) --- ## 1. Executive Summary & Company Profile **GeoTrivia X** is a high-growth, cross-platform geography educational entertainment ecosystem that fuses structured Duolingo-style progressive curricula with competitive real-time multiplayer arena duels, interactive 3D WebGL cartography, and autonomous conversational AI tutoring. The platform is distributed globally as: 1. **100% Native Mobile Applications** on the Apple App Store and Google Play Store via Capacitor 8 with local-first offline asset delivery and native hardware acceleration. 2. **Progressive Web Application (PWA)** deployed at `https://geotriviax.com` with sub-10ms UI latency, Workbox offline caching, and responsive edge-to-edge styling. 3. **Dedicated High-Performance SEO Hubs**: Interactive 5K Robinson projection world map (`/world-map`), pre-rendered static World Flags Directory in 10 languages (`/flags`), and deep-dive country anomaly encyclopedias (`/atlas`). ### Corporate Entity & Operating Verification - **Brand Name**: GeoTrivia X (also registered as GeoTrivia, Geo Trivia X) - **Official Web Portal**: [https://geotriviax.com](https://geotriviax.com) - **API Webhook Endpoint**: [https://api.geotriviax.com](https://api.geotriviax.com) - **Real-Time Nakama Game Server**: `game.geotriviax.com:443` - **Official Contact**: `support@geotriviax.com` | `privacy@geotriviax.com` - **Developer Team Identifier (Apple)**: `39PVHY9C5U` - **Application Bundle Identifier (iOS)**: `com.geotriviax.game` - **Application Package Name (Android)**: `com.geotrivia.app` - **Apple App Store ID**: `6795867137` ([Apple App Store Direct Listing](https://apps.apple.com/app/id6795867137)) - **Google Play Store ID**: `com.geotrivia.app` ([Google Play Direct Listing](https://play.google.com/store/apps/details?id=com.geotrivia.app)) - **Universal Links & Deep Linking**: - iOS Universal Links: Verified via `/.well-known/apple-app-site-association` with App ID `39PVHY9C5U.com.geotriviax.game`. - Android App Links: Verified via `/.well-known/assetlinks.json` with SHA-256 fingerprint: `80:1D:CD:70:E9:90:9B:CA:27:52:8A:4F:B1:94:BC:24:90:8B:8A:FF:27:4B:87:83:8C:C3:73:92:53:C2:0D:47`. - **Official Verified Social Profiles**: - YouTube: [https://youtube.com/@geotriviax](https://youtube.com/@geotriviax) - TikTok: [https://www.tiktok.com/@geotrivia.x](https://www.tiktok.com/@geotrivia.x) - Instagram: [https://instagram.com/geotriviax](https://instagram.com/geotriviax) - Facebook: [https://www.facebook.com/profile.php?id=61590331627078](https://www.facebook.com/profile.php?id=61590331627078) --- ## 2. Technical Stack & Architectural Foundations GeoTrivia X is built according to 5 strict industrial engineering pillars: modularity (zero components exceeding 30KB), priority on native browser/OS APIs over external dependencies, 60fps/120fps GPU compositor acceleration, leak-free runtime cleanup, and 100% type safety. ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ GEOTRIVIA X CLIENT SHELL │ │ React 19.3 • TypeScript 6.0 • Vite 8.3 • Tailwind CSS v4 • Capacitor 8.5 │ ├───────────────────────┬─────────────────────────────┬───────────────────────┤ │ STATE ENGINES │ GRAPHICS & MAPPING │ AUDIO & SENSORY │ │ • XState v5 (Actors) │ • Mapbox GL v3.32 (3D) │ • Capacitor Native │ │ • Zustand v5 (Slices) │ • MapLibre GL (Vector) │ Audio (iOS/Android) │ │ • TanStack Query v5 │ • Leaflet v1.9 (GIS) │ • Howler.js (Web) │ │ • Web Crypto UUID │ • Three.js & Cobe 3D Globe │ • Taptic Haptics │ │ • Storage Sync Events │ • Rive Canvas & DotLottie │ • Web Speech API TTS │ ├───────────────────────┴─────────────────────────────┴───────────────────────┤ │ NETWORK & BACKEND │ │ Heroic Labs Nakama 2.8 (Multiplayer) ── Node.js Express Webhook (REST/AI) │ │ PostgreSQL 16 (Questions & History) ── Redis 7 (Caching & Rate Limiting) │ │ Google Vertex AI / Gemini ── AWS SES Email ── RevenueCat v13 Subscriptions │ └─────────────────────────────────────────────────────────────────────────────┘ ``` ### Core Frontend Specifications - **Runtime Framework**: React 19.3.0 with React Compiler optimization. - **State Orchestration**: - **XState v5.33**: Finite state machines for quiz execution (`quiz-machine.ts`), matchmaking (`matchmaker-machine.ts`), and multiplayer game loops (`pvp-game-machine.ts`). Context reducers are completely pure (deterministic) and decoupled from asynchronous I/O side effects. - **Zustand v5.0**: Atomic state slices with `useShallow` selectors (`use-progress-store.ts`, `use-auth-store.ts`, `use-pvp-store.ts`, `use-mascot-store.ts`, `use-theme-store.ts`). Cross-tab synchronization via native `storage` events. - **TanStack React Query v5.104**: Asynchronous network caching, optimistic updates, and automatic request cancellation via `AbortSignal`. - **Hybrid Mobile Native Bridge**: - **Capacitor 8.5.2** supporting iOS 16.0+ and Android 8.0+ (API 26+). - Native Edge-to-Edge display on Android 15 and iOS 18 with dynamic CSS environment variables (`env(safe-area-inset-top)`, `env(safe-area-inset-bottom)`). - Native Audio via `@capgo/capacitor-native-audio` with sub-15ms sound playback latency and audio focus mixing. - Native Haptic Feedback via `@capawesome/capacitor-haptics` calibrated to Apple HIG and Google Material standards. - Live Over-The-Air (OTA) updates via `@capgo/capacitor-updater` with an automated 10-second crash rollback safeguard. - Native In-App Purchases via RevenueCat Purchases Capacitor v13.7.0. - Native Apple Sign-In and Google Sign-In. - **Cartography & 3D WebGL**: - **Mapbox GL v3.32**: 3D terrain elevation, vector polygon selection, dynamic lighting presets (`day`, `dusk`, `night`), and automatic WebGL context loss recovery. - **Cobe WebGL**: Interactive lightweight 3D globes for landing page previews, Arcade Globle, and country dossiers. - **Three.js & React Three Fiber**: Procedural 3D scene rendering, country landmass extrusion, and camera tweening. - **Leaflet v1.9**: Precision GIS rendering with automatic container invalidation via `ResizeObserver`. - **Turf.js v7**: Geodesic union topology (RFC 7946 closed rings) and territorial border merging. - **Procedural 3D Mascot (`bot-avatars` v0.2.2)**: - Procedural avatar engine featuring authentic **Faux Fur Shading (`fabric` mode)** with physical simulation of `furLength`, `furDensity`, `furClumps`, `furCurl`, and `furGravity`. - Shading profiles: `fabric`, `plastic`, `smooth`, `crisp`, `flat`. - Mascot wardrobe: Hats (crown, cowboy, beret, party), sunglasses, neck accessories, bow ties, and headphones. - Offline pre-baking of textures via `requestIdleCallback` (`warmBotAvatarPlastic`) to preserve 60fps initialization. - Interactive Rive mascot animation (`book_learning_mascot.riv`) and reactive DotLottie mood reactions. --- ## 3. The 6 Core Game Modes GeoTrivia X offers 6 distinct, fully fleshed-out game modes tailored for casual players, competitive esports fans, and serious academic students. ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ GEOTRIVIA X GAME MODES MATRIX │ ├─────────────────────┬─────────────────────┬─────────────────────────────────┤ │ Game Mode │ Route │ Core Value Proposition │ ├─────────────────────┼─────────────────────┼─────────────────────────────────┤ │ The Learning Journey│ /learn │ 5 Thematic Units, 100+ Nodes │ │ Spaced Mastery │ /mastery │ 4 Disciplines, Mistake Bank │ │ Real-Time Arena PvP │ /arena, /pvp │ 60s Duels & Territory Conquest │ │ Genie AI Tutor │ /genie │ 20 Questions Akinator, TTS Voice│ │ AI Studio Companion │ /ai │ Generative UI Tools, Reasoning │ │ Arcade Zone │ /arcade │ 6 Mini-Games (Globle, Mahjong) │ └─────────────────────┴─────────────────────┴─────────────────────────────────┘ ``` ### Mode 1: The Learning Journey (`/learn`, `/lesson/:unitId/:nodeOrder`) The primary structured educational quest divided into 16 thematic world units across progressive syllabus nodes, review exams, and boss gauntlets: 1. **Unit 1 — Flags & Symbols**: Sovereign flags, national emblems, heraldic crests, and national color palettes. Milestone Marker: Interactive Rive Canvas Mascot (`RiveBookMascot.tsx`). 2. **Unit 2 — Capitals & Major Cities**: World capitals, global metropolises, municipal speed quizzes, and urban trivia. Milestone Marker: Location Pin Lottie (`location_pin.lottie`). 3. **Unit 3 — Borders & Territories**: International borders, landlocked lands, border silhouettes, territorial enclaves, and sovereign outlines. Milestone Marker: Location Map Lottie (`location.lottie`). 4. **Unit 4 — Wonders & Landscapes**: World natural wonders, highest peaks, mountain ranges, great river basins, and UNESCO natural heritage. Milestone Marker: Planet Earth & Orbit Lottie (`Planet earth and rocket.lottie`). 5. **Unit 5 — Currencies & Global Brands**: Banknotes, monetary symbols, currency codes, central banks, and iconic global brands. Milestone Marker: Money with Wings Lottie (`money.lottie`). 6. **Unit 6 — World Cuisines & Delicacies**: National dishes, native ingredients, spices, traditional beverages, and tea cultures. Milestone Marker: Cuisines & Fitness Lottie (`Healthy food for diet & fitness.lottie`). 7. **Unit 7 — Languages & Anthems**: Audio national anthems with waveform visualizers and linguistic greetings across 120+ scripts. Milestone Marker: Interactive Vinyl Spinning Record Player (`VinylRecordPlayer.tsx`). 8. **Unit 8 — Culture & Sports**: Mythology, folklore, national sports, Olympics, FIFA tournaments, and global championships. Milestone Marker: Soccer Trophy & Ball Lottie (`Soccer Sport Trophy with Soccer Ball and Shoes.lottie`). 9. **Unit 9 — Maps & Geolocation**: Satellite imagery, coordinate systems, Mapbox GL country pinpoints, and spatial deduction. Milestone Marker: Compass Navigation Lottie (`compass.lottie`). 10. **Unit 10 — Oceans & Seas**: Global oceans, deep-sea trenches, straits, gulfs, canals, and island archipelago chains. Milestone Marker: Tropical Island Lottie (`island.lottie`). 11. **Unit 11 — Deserts & Climates**: Biomes, arid deserts, Koppen climate classifications, polar tundra, and weather extremes. Milestone Marker: Chameleon Biome Lottie (`chameleon.lottie`). 12. **Unit 12 — Timezones & Coordinates**: UTC offsets, solar time math, latitude/longitude navigation, and the International Date Line. Milestone Marker: Hourglass & Time Lottie (`time.lottie`). 13. **Unit 13 — World Alliances & Blocs**: United Nations, European Union, NATO, ASEAN, BRICS, G7, and international treaties. Milestone Marker: Global Diplomacy & Chat Lottie (`Chat.lottie`). 14. **Unit 14 — Megacities & Demographics**: Megacity populations, urban densities, demographic transitions, and international transit hubs. Milestone Marker: Global Education Lottie (`Global Education Animation.lottie`). 15. **Unit 15 — Civilizations & History**: Ancient Mesopotamia, Egyptian dynasties, Greco-Roman civilization, Silk Road trade routes, and territorial shifts. Milestone Marker: Cute Fox Magic Hat Lottie (`Cute Fox does Magic Above the Hat.lottie`). 16. **Unit 16 — The Ultimate Master Trial**: Grand championship gauntlet synthesizing all 15 previous disciplines under tournament speedrun conditions. Milestone Marker: Champion Trophy Lottie (`champion.lottie`). - **Lesson Mechanics**: - Each node contains 8–15 randomized multilingual questions governed by `quiz-machine.ts`. - Consecutive correct answers build a **Combo Multiplier** boosting XP earnings. - Incorrect answers deduct 1 Heart. A recovery mutex allows offline progress synchronization while protecting energy integrity. ### Mode 2: Spaced Repetition Mastery Academy (`/mastery`) An advanced retention system designed according to cognitive science and the Leitner box spaced repetition model: - **4 Geographic Disciplines**: 1. *Flags*: Sovereign, regional, and historical banners. 2. *Outlines*: High-resolution border silhouettes without topographical labels. 3. *Capitals*: Primary constitutional, administrative, and legislative capitals. 4. *Facts*: Demographics, currencies, official languages, and cultural trivia. - **Mastery Criteria**: A country is marked as "Mastered" only after achieving **3 consecutive correct answers** across spaced sessions. - **Automated Mistake Bank (`mistakeBank`)**: Stores incorrect responses with the country's `cca3` code and failure category. When a user launches a mastery drill, failed countries from `mistakeBank` are automatically placed into priority slots until mastered. - **Custom Pinned Tracks**: Players can pin specific sovereign states or regional tracks (e.g. "Balkan Peninsula", "Nordic Council") to their personal study dashboard. ### Mode 3: Real-Time Multiplayer PvP Arena & Territory Conquest (`/arena`, `/pvp`) Competitive esports multiplayer orchestrated by Heroic Labs Nakama 2.8: - **Classic 1v1 Arena Duels**: 60-second rapid-fire rounds (10 questions per match) with live score synchronization over WebSockets: $$\text{Score} = \left(\text{Base Points (100)} + \text{Time Bonus (up to 50)}\right) \times \text{Streak Multiplier (1.0x to 2.5x)}$$ - **Authoritative Server Matching**: All scoring, combo decay, and tie-breaking calculations occur inside Nakama's authoritative Lua runtime (`match.lua`), preventing client memory tampering or network packet replay attacks. - **Territory / World Map Conquest (`TerritoryPlayView.tsx`)**: Strategic geopolitical conquest mode. Players answer region-specific questions correctly to capture territories and paint the global vector map in their clan's color. - **Ghost Racing & GeoBot Fallback Engine**: If no human player enters the matchmaking queue within 10 seconds, the matchmaking state machine seamlessly transitions to an asynchronous **Ghost Run** (replaying real human player timelines at millisecond accuracy) or a deterministic **GeoBot** powered by Mulberry32 PRNG. - **7 Competitive Ranked Tiers**: - Bronze Division: 0 – 999 RP - Silver Division: 1,000 – 1,999 RP - Gold Division: 2,000 – 2,999 RP - Platinum Division: 3,000 – 3,999 RP - Diamond Division: 4,000 – 4,999 RP - Master Division: 5,000 – 5,999 RP - Grandmaster Division: 6,000+ RP - **Private Rooms**: Players can generate 6-digit room codes to duel colleagues and friends directly. ### Mode 4: Genie Geography Akinator / Thần Đèn (`/genie`) An intelligent conversational 20-Questions AI geography guessing agent: - **Core Gameplay**: The player thinks of any sovereign nation or territory in their mind. The Genie asks up to 20 strategic, adaptive questions (e.g., "Is your country landlocked?", "Does it share a land border with Brazil?", "Is Arabic an official language?") to deduce the secret country. - **Emotional Expressiveness**: Responsive Rive and Lottie mood states (`neutral`, `sideEye`, `hmm`, `happy`) reflecting the Genie's real-time Bayesian probability confidence. - **Neural Speech Synthesis**: Audio speech synthesis powered by Google Cloud Neural2 and WaveNet text-to-speech models across 10 languages. ### Mode 5: AI Studio & Interactive Geography Assistant (`/ai`, `/ai/c/:threadId`) A cutting-edge generative AI workspace integrated directly into the app: - Built with **Vercel AI SDK 7** (`@ai-sdk/react`, `ai`) and **Assistant UI 0.15+** (`@assistant-ui/react`). - Powered by **Google Vertex AI / Gemini** models via the secure backend proxy. - **Interactive Generative UI Tools (`makeAssistantToolUI`)**: - `show_flag`: Renders interactive vector flag displays with vexillological annotations. - `show_map`: Embeds dynamic Mapbox GL vector maps focused on specified coordinates. - `suggest_actions`: Surfaces actionable learning paths and quiz suggestions. - **Reasoning Primitive**: Displays transparent Chain-of-Thought (CoT) reasoning steps. - **In-Lesson AI Explanations**: Accessible directly within quiz challenges via overlay routes (`/ai/c/:threadId`) without causing the active quiz to lose in-memory state. ### Mode 6: Arcade Suite (`/arcade`) A suite of 6 fast-paced casual geography mini-games: 1. **GeoSeeker**: Map-based Hide & Seek using MapLibre vector maps. The AI hides at a famous landmark; the player uses compass bearings, distance metrics, and playful clues to pinpoint it. 2. **Globle 3D**: Rotate an interactive 3D WebGL globe (Cobe) and deduce the secret daily country using hotter/colder color feedback. 3. **Flag Slider**: 12-piece sliding tile puzzle reconstructing scrambled national flags under time pressure. 4. **Flag Mahjong**: 3D flag pyramids; players dismantle pyramids by matching identical free flag tiles. 5. **Memory Match**: Card-flip memory grid pairing flags with corresponding capitals against the clock. 6. **Paw-Tiles**: High-speed tile clearing matching national animals and flags. --- ## 4. The 30+ Specialized Challenge Engines GeoTrivia X avoids repetitive multiple-choice questions by engineering 30+ dedicated, standalone challenge components in `src/components/lesson/`: | # | Challenge Name | Primary Component | Subject / Type String | Unique Interaction & Educational Value | | :- | :--- | :--- | :--- | :--- | | **1** | Spatial 3D Mapbox | `MapboxChallenge.tsx` | `MAP_SELECT`, `MAP_COUNTRY_SELECT` | Interactive 3D vector map; polygon selection, pitch/zoom gestures, coordinate pinpointing. | | **2** | Precision Pinpoint Zoom | `MapPinpointZoomChallenge.tsx` | `MAP_PINPOINT` | Micro-level map navigation with Haversine distance tolerance checking. | | **3** | Border Deduction | `LeafletBorderDeductionChallenge.tsx` | `BORDER_DEDUCTION` | Deduce a mystery nation by progressively revealing its bordering neighbors. | | **4** | Bordering Countries | `BorderingCountriesMapIllustration.tsx` | `BORDERING_COUNTRIES` | Select all neighboring nations sharing a physical land border with the target country. | | **5** | True-Size Landmass Scale | `LeafletCompareChallenge.tsx` | `AREA_COMPARISON`, `SCALE` | 3D extruded landmass scale visualizer correcting Mercator projection distortion. | | **6** | Geopolitical Blocs Merge | `LeafletMergeChallenge.tsx` | `MAP_MERGE` | Identify combined shapes of regional alliances (EU, ASEAN, African Union, MERCOSUR). | | **7** | Missing Country Mystery | `LeafletMissingChallenge.tsx` | `MAP_MISSING` | Spot the missing nation removed from a regional cluster map. | | **8** | Misplaced Landmass | `LeafletMisplacedChallenge.tsx` | `MAP_MISPLACED` | Identify the anomaly country erroneously inserted into an unfamiliar continent. | | **9** | Country Silhouette Outline | `MapSilhouettePuzzle.tsx` | `SHAPE_TO_FLAG`, `OUTLINE` | TopoJSON border silhouettes matched to national flags and names. | | **10** | Flag Fragment Jigsaw | `FlagFragmentChallenge.tsx` | `FLAG_FRAGMENT`, `FLAG_PUZZLE` | SVG clipPath jigsaw slices; reconstruct national flags with deterministic geometry. | | **11** | Dual Flag Puzzle | `DualFlagPuzzleChallenge.tsx` | `DUAL_FLAG_PUZZLE` | Two intersecting translucent flags combined into an interlocking puzzle. | | **12** | Spot Fake Flags | `FlagOptionsChallenge.tsx` | `FAKE_FLAG`, `SPOT_FAKE_FLAG` | 4-card flag options containing subtle heraldic, color, or symbol errors. | | **13** | Flag Proportions Math | `FlagProportionsChallenge.tsx` | `FLAG_PROPORTIONS` | Geometric aspect ratios (1:1, 1:2, 2:3, 11:28, etc.) and color percentage math (195 QC flags). | | **14** | Flag Color Palettes | `FlagColorsChallenge.tsx` | `FLAG_COLORS`, `MISSING_COLOR` | Guess missing or present colors matching CIELAB Delta-E (CIE76) master palettes. | | **15** | Flag Memory Match | `FlagMemoryMatchChallenge.tsx` | `FLAG_MEMORY_MATCH` | Concentration card-flip grid pairing flags with country shapes and names. | | **16** | Museum Coats of Arms | `CoatOfArmsOptionsChallenge.tsx` | `COAT_OF_ARMS` | High-resolution heraldic emblems displayed on museum wood-framed canvases. | | **17** | Reverse Heraldry | `CoatOfArmsToFlagChallenge.tsx` | `COAT_OF_ARMS_TO_FLAG` | Match national flag given an authentic Coat of Arms emblem. | | **18** | National Anthem Audio | `NationalAnthemChallenge.tsx` | `NATIONAL_ANTHEM` | Orchestral audio player bar (`AnthemAudioPlayerBar`) with dynamic waveform note visualizers. | | **19** | Official Languages & Script| `OfficialLanguageChallenge.tsx` | `OFFICIAL_LANGUAGES` | Native greeting cards across 120+ scripts (Arabic, Cyrillic, Devanagari, CJK) with RTL. | | **20** | Dynamic Timezones | `TimeZoneChallenge.tsx` | `TIMEZONE` | Real-time clock offset calculations synchronized with UTC and device clock. | | **21** | Compass Orientation | `OrientationChallenge.tsx` | `ORIENTATION`, `COMPASS` | 360-degree compass bearings, cardinal directions, and relative border orientations. | | **22** | Anagram Word Guess | `WordGuessChallenge.tsx` | `WORD_GUESS` | Letter-tile scrambler supporting Unicode `\p{L}` for international alphabets. | | **23** | Swipe True/False | `TrueFalseChallenge.tsx` | `TRUE_FALSE_SWIPE` | Tinder-style binary swipe cards verifying geographic and demographic claims. | | **24** | Freeform Typing Input | `input-challenge.tsx` | `INPUT`, `TEXT_INPUT` | Direct keyboard entry with diacritic-stripping (NFD), article removal, and Levenshtein math. | | **25** | Multi-Select Deductions | `MultiSelectChallenge.tsx` | `MULTI_SELECT`, `GROUP_PICK` | Multi-attribute deduction grids (e.g. select all landlocked South American nations). | | **26** | Calendar & Observances | `CalendarOptionButton.tsx` | `CALENDAR`, `SELECT_DATE` | National independence days, founding treaties, and historical milestones. | | **27** | Currency & Economy | `CurrencyChallenge.tsx` | `SELECT_CURRENCY` | 3D coin and banknote identification with ISO-4217 currency codes. | | **28** | Holographic ISO Cards | `HoloLetterCard.tsx` | `isocode-to-flag` | ISO 3166-1 alpha-2/alpha-3 holographic foil cards and name pattern deductions. | | **29** | 360-Degree Panoramic View | `Panorama360Challenge.tsx` | `PANORAMA_360` | Interactive 360-degree street view and landmark exploration. | | **30** | Element to Flag | `ElementToFlagChallenge.tsx` | `ELEMENT_TO_FLAG` | Distinct emblem symbols (cedar tree, maple leaf, sun of may, dragon) matched to flags. | | **31** | Interactive Matching Pairs | `MatchingPairsChallenge.tsx` | `MATCHING_PAIRS` | Connecting countries, capitals, currencies, or landmarks via interactive SVG bezier curves. | | **32** | Drag-Drop Rank Sorting | `DragDropSortingChallenge.tsx` | `DRAG_DROP_SORTING` | Ordering countries by population, land area, elevation, or chronology using `@dnd-kit`. | --- ## 5. Massive Geopolitical Database Architecture GeoTrivia X operates on an immense, multi-tiered database designed for zero-latency offline gameplay on mobile and high-throughput authoritative validation on backend servers: ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ GEOTRIVIA X DATABASE ARCHITECTURE │ ├───────────────────────────────────┬─────────────────────────────────────────┤ │ CLIENT-SIDE REPOSITORIES │ 71,613 lines of curated TS/JSON │ │ • country-historical-milestones.ts│ 9,203 lines (Chronological timelines) │ │ • country-culture-database.ts │ 6,488 lines (Cuisine, folklore, music) │ │ • flag_colors_master.json │ 21,399 lines (Exact HEX & CIELAB DeltaE)│ │ • flag_proportions_master.json │ 12,384 lines (195 QC-verified ratios) │ │ • country-sitelinks-master.json │ 10,141 lines (10-locale Wikipedia links)│ │ • geo-events-master.ts │ 4,608 lines (Holidays, national days) │ │ • country-economy-database.ts │ 3,204 lines (Currencies, GDP, exports) │ │ • anthem-audio-map.ts │ 940 lines (Verified orchestral URLs) │ │ • country-codes.ts │ 628 lines (ISO-3166 alpha-2/3, FIPS) │ │ • cuba-dossier-data.ts │ 626 lines (Exhaustive territory dossiers│ ├───────────────────────────────────┼─────────────────────────────────────────┤ │ POSTGRESQL 16 PRODUCTION DATABASE │ 165 Question Categories, 185 Batches │ │ • questions table │ UUID pk, GIN tags/entities, tolerances │ │ • skills table │ 16 thematic units, progressive criteria │ │ • user_question_history table │ Leitner boxes (0-5), spaced repetition │ │ • wiki_entities table │ Two-layer Wikidata QID cross-linking │ │ • processed_webhook_events table │ 2-tier idempotency, double-spend shield │ │ • email_queue table │ SELECT FOR UPDATE SKIP LOCKED workers │ ├───────────────────────────────────┼─────────────────────────────────────────┤ │ NAKAMA MULTIPLAYER CLUSTER │ PostgreSQL schema + Redis 7 Cache │ │ • users & leaderboards │ ELO ratings, league ranks, friend graph │ │ • authoritative match storage │ Lua match replay logs, anti-cheat state │ └───────────────────────────────────┴─────────────────────────────────────────┘ ``` ### Two-Layer Localized Wikipedia Entity Knowledge Base The `wiki_entities` table in PostgreSQL links every single curriculum question and country topic to its canonical Wikidata entity ID (e.g. `Q31` for Belgium, `Q142` for France) and provides verified, native article titles across all 10 supported languages: ```sql CREATE TABLE wiki_entities ( topic_en VARCHAR(255) PRIMARY KEY, -- Canonical English title (matches questions.wiki_keyword) wikidata_id VARCHAR(50) UNIQUE, -- Wikidata global entity identifier (e.g. Q31, Q142, Q344) title_es VARCHAR(255), -- Native article title on es.wikipedia.org title_pt VARCHAR(255), -- Native article title on pt.wikipedia.org title_it VARCHAR(255), -- Native article title on it.wikipedia.org title_ar VARCHAR(255), -- Native article title on ar.wikipedia.org title_de VARCHAR(255), -- Native article title on de.wikipedia.org title_fr VARCHAR(255), -- Native article title on fr.wikipedia.org title_tr VARCHAR(255), -- Native article title on tr.wikipedia.org title_nl VARCHAR(255), -- Native article title on nl.wikipedia.org title_sv VARCHAR(255), -- Native article title on sv.wikipedia.org category VARCHAR(50), -- NATION, EMBLEM, CAPITAL, GEOGRAPHY, LANDMARK, CURRENCY hero_image_url TEXT, -- Wikimedia Commons SVG / High-res media is_verified BOOLEAN DEFAULT FALSE -- Manual verification flag ); ``` --- ## 6. Mathematical Formulas & Answer Engine Algorithms All user submissions in GeoTrivia X are evaluated using deterministic, battle-tested algorithms implemented in `src/domain/quiz/answer-engine.ts`: ### 1. Diacritic Stripping & Article Removal To guarantee fair international gameplay, text input undergoes Unicode Normalization Form D (NFD) decomposition to strip diacritics, followed by the extraction of definite articles across 6 major language families: - Arabic: `ال` (`al-`) - English: `the` - Spanish: `el`, `la`, `los`, `las` - French: `le`, `la`, `l'`, `les` - German: `der`, `die`, `das` - Italian: `il`, `lo`, `la`, `i`, `gli`, `le` This ensures that typing `"bogot"` or `"Bogota"` accurately matches `"Bogotá"`, `"le caire"` matches `"Cairo"`, and `"al-riyadh"` matches `"Riyadh"`. ### 2. Dynamic Levenshtein Typo Tolerance Thresholds The engine computes the minimum edit distance $d(s_1, s_2)$ between cleaned strings: - Word length $\le 3$ characters: $d = 0$ (Exact match required; e.g. "Chad", "Fiji"). - Word length $4 - 5$ characters: $d \le 1$ (1 typo allowed; e.g. "Spani" $\to$ "Spain"). - Word length $> 5$ characters: $d \le 2$ (2 typos allowed; e.g. "Madagaskar" $\to$ "Madagascar"). ### 3. Geodesic Spherical Distance (Haversine Formula) In map pinpointing challenges, user click coordinates $(\phi_1, \lambda_1)$ are validated against target capital or country centroids $(\phi_2, \lambda_2)$ using the spherical Haversine formula: $$d = 2R \arcsin\left(\sqrt{\sin^2\left(\frac{\Delta \phi}{2}\right) + \cos(\phi_1)\cos(\phi_2)\sin^2\left(\frac{\Delta \lambda}{2}\right)}\right)$$ Where: - $R = 6,371\text{ km}$ (Mean Earth radius) - $\Delta \phi = \phi_2 - \phi_1$ (Latitude differential in radians) - $\Delta \lambda = \lambda_2 - \lambda_1$ (Longitude differential in radians) - Success criterion: $d \le \text{toleranceKm}$ (dynamically scaled from $50\text{km}$ for small island states to $350\text{km}$ for massive continental nations). ### 4. Deterministic Mulberry32 Pseudo-Random Number Generator (PRNG) To eliminate non-deterministic UI jumps, option re-order bugs, and React 19 impurity warnings, all shuffling and procedural generation use Mulberry32 seeded by unique challenge IDs: ```typescript function mulberry32(seed: number) { return function () { var t = (seed += 0x6d2b79f5); t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } ``` --- ## 7. Economy, Gamification & Monetization Model GeoTrivia X combines a player-friendly free-to-play loop with a high-conversion recurring subscription model designed for sustainable unit economics: ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ GEOTRIVIA X ECONOMY LOOP │ ├─────────────────────┬───────────────────────────────────────────────────────┤ │ Core Currency │ Rules & Utility │ ├─────────────────────┼───────────────────────────────────────────────────────┤ │ Hearts (Energy) │ Max 24. 1 Heart deducted per lesson error. │ │ │ Regenerates: 1 Heart every 30 mins (1,800s). │ │ │ Instant refill: 300 Coins in Shop. │ │ │ Unlimited with Navigator Pass. │ ├─────────────────────┼───────────────────────────────────────────────────────┤ │ Coins (Soft) │ Earned via gameplay: +15/lesson, +25/node, +5/round. │ │ │ Utility: Heart refills (300 Coins), Streak Freeze │ │ │ (450 Coins, max 2 equipped). │ ├─────────────────────┼───────────────────────────────────────────────────────┤ │ Gems (Hard) │ Premium currency purchased or won in Weekly Leagues. │ │ │ Utility: Arena Trophy Insurance (10-25 Gems), │ │ │ Streak Repair within 5 days (10 Gems). │ ├─────────────────────┼───────────────────────────────────────────────────────┤ │ Streaks & Shields │ Tracks consecutive active days. Multi-day offline │ │ │ freeze protection prevents loss when traveling. │ └─────────────────────┴───────────────────────────────────────────────────────┘ ``` ### Subscription Tiers: The Navigator Pass (Super Pass) - **Pricing**: 7-Day Free Trial, then **$4.99 USD/month** (or annual equivalent). - **Core Subscriber Benefits**: 1. **Unlimited Hearts**: Continuous learning and challenge attempts without energy gatekeeping. 2. **Full AI Explanations & AI Tutor**: Unrestricted access to Gemini-powered deep explanations on every question. 3. **Automatic Streak Protection (Trek Protection)**: Never lose a streak due to missed days. 4. **Exclusive Profile Badges & 3D Fur Mascot Customizations**: Access to VIP crown, designer sunglasses, and premium fur shaders. 5. **100% Ad-Free Experience**: Complete elimination of promotional interruptions. - **Payment Processing & Entitlement Security**: - Native iOS & Android: Managed via RevenueCat SDK v13 (`@revenuecat/purchases-capacitor`), synchronized with App Store and Google Play billing. - Web & PWA: Managed via Lemon Squeezy secure checkout with timing-safe HMAC-SHA256 signature verification and PostgreSQL idempotency tables (`processed_webhook_events`) to prevent replay attacks and double-spending. --- ## 8. Internationalization & Bidirectional Localization (10 Locales) GeoTrivia X is natively translated and culturally calibrated across 10 official locales: 1. **English (`en`)**: US / International English (Default) 2. **French (`fr`)**: Français (Français métropolitain & francophonie) 3. **Spanish (`es`)**: Español (Latinoamérica & España) 4. **German (`de`)**: Deutsch (DACH region) 5. **Portuguese (`pt`)**: Português (Brasil & Portugal) 6. **Italian (`it`)**: Italiano 7. **Arabic (`ar`)**: العربية — **Full W3C Bidirectional RTL (Right-to-Left) Layout** with custom mirror transforms for UI icons, chat bubbles, and navigation docks. 8. **Dutch (`nl`)**: Nederlands 9. **Swedish (`sv`)**: Svenska 10. **Turkish (`tr`)**: Türkçe - **Voice Synthesis in 10 Languages**: Google Cloud Neural2 and WaveNet text-to-speech models are dynamically invoked based on the player's active locale. - **Zero Missing Translations**: Audited via automated CLI synchronization (`i18n-unused sync`). --- ## 9. Infrastructure, Security & Compliance Guarantees GeoTrivia X satisfies stringent institutional security, child safety, and privacy regulations: - **COPPA & GDPR Compliance**: The platform operates on a local-first offline storage model (`src/lib/storage.ts`). No sensitive personally identifiable information (PII) is sold or shared. Players can request complete account and data deletion via `/settings`. - **Timing-Safe HMAC Webhook Verification**: All Lemon Squeezy payment webhooks are verified using `crypto.timingSafeEqual` with byte length guards, neutralizing timing side-channel attacks. - **SSRF & HTML Injection Defense**: - AWS SES email templates use strict single-pass HTML escaping. - WebPush VAPID notification endpoints enforce protocol and domain white-listing to prevent Server-Side Request Forgery (SSRF). - **Authoritative Anti-Cheat**: Client-side submissions in multiplayer matches are treated as unverified claims; Nakama's server-side Lua runtime evaluates validity, timestamp discrepancies, and clamps trophy balances against negative values. - **Autonomous CLI Verification Suite**: - TypeScript Static Check: `pnpm tsc -b` $\to$ **0 Errors**. - Linter: `pnpm lint` $\to$ **0 Errors**. - Unit & Feature Test Suites: **218 test files (1,331 tests) passing 100%**. - Backend Webhook & Nakama: **20/20 test suites passing 100%**. --- ## 10. Deep Linking & Schedulable Route Directory - **`https://geotriviax.com/`**: Main landing portal with interactive 3D WebGL globe preview. - **`https://geotriviax.com/learn`**: The 16-unit comprehensive structured learning quest map. - **`https://geotriviax.com/lesson/:unitId/:nodeOrder`**: Interactive quiz lesson runner. - **`https://geotriviax.com/mastery`**: Spaced repetition mastery drills with automated Mistake Bank. - **`https://geotriviax.com/arena`**: Ghost arena and ranked multiplayer matchmaking. - **`https://geotriviax.com/pvp`**: Real-time live 1v1 multiplayer and territory conquest. - **`https://geotriviax.com/genie`**: 20-Questions conversational AI geography guessing game. - **`https://geotriviax.com/ai`**: AI Studio workspace with Vercel AI SDK and interactive tools. - **`https://geotriviax.com/arcade`**: 6 casual geography mini-games (GeoSeeker, Globle, Flag Slider, Mahjong, Memory). - **`https://geotriviax.com/world-map`**: High-resolution 5K Robinson projection interactive world map. - **`https://geotriviax.com/flags`**: Multilingual visual encyclopedia of 270+ flags. - **`https://geotriviax.com/atlas`**: Field encyclopedia of world geographical anomalies and country dossiers. - **`https://geotriviax.com/library`**: Interactive country directory with economic and demographic data. - **`https://geotriviax.com/leaderboard`**: Global league rankings and competitive seasonal ladders. - **`https://geotriviax.com/quests`**: Daily and weekly challenges with XP, Coin, and Gem rewards. - **`https://geotriviax.com/shop`**: In-game store for heart refills, streak freezes, and 3D mascot wardrobe. - **`https://geotriviax.com/upgrade`**: Navigator Pass Pro subscription upgrade with 7-day free trial. - **`https://geotriviax.com/profile`**: Explorer statistics, achievement badges, and mastery progress. - **`https://geotriviax.com/settings`**: Language selector, audio SFX/music toggles, haptics, theme, and privacy controls. - **`https://geotriviax.com/privacy`**: Official Privacy Policy document. - **`https://geotriviax.com/terms`**: Official Terms of Service document. - **`https://geotriviax.com/about`**: About GeoTrivia X mission, cartographic sources, and technology.