<!DOCTYPE html>

<html lang="vi">

<head>

  <meta charset="UTF-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

  <title>Finn's Fantasy Quest — 4 Worlds English Adventure</title>

  <style>

    :root {

      --bg-deep: #0b192c;

      --card-glass: rgba(16, 35, 62, 0.86);

      --accent-gold: #ffd166;

      --accent-cyan: #4cc9f0;

      --accent-mint: #06d6a0;

      --accent-coral: #ff595e;

      --accent-purple: #b5179e;

      --text-main: #ffffff;

      --text-soft: #cfe3ff;

      --radius-lg: 24px;

      --radius-md: 16px;

      --shadow-pop: 0 10px 25px rgba(0, 0, 0, 0.35);

    }

 

    * {

      box-sizing: border-box;

      -webkit-tap-highlight-color: transparent;

      user-select: none;

    }

 

    html, body {

      margin: 0;

      padding: 0;

      width: 100%;

      height: 100dvh;

      overflow: hidden;

      font-family: "Trebuchet MS", "Segoe UI", system-ui, sans-serif;

      background: radial-gradient(circle at 20% 15%, #1d4e89 0%, #0d2542 55%, #071324 100%);

      color: var(--text-main);

      touch-action: manipulation;

    }

 

    /* App Shell */

    .app-shell {

      position: relative;

      width: 100%;

      height: 100dvh;

      display: flex;

      flex-direction: column;

      padding: 12px 16px 14px;

      gap: 10px;

    }

 

    /* Top HUD */

    .hud {

      display: flex;

      align-items: center;

      justify-content: space-between;

      gap: 10px;

      background: rgba(9, 22, 41, 0.78);

      backdrop-filter: blur(10px);

      border: 2px solid rgba(255, 255, 255, 0.14);

      border-radius: 999px;

      padding: 8px 14px;

      box-shadow: var(--shadow-pop);

      z-index: 20;

      flex-shrink: 0;

    }

 

    .hud-group {

      display: flex;

      align-items: center;

      gap: 8px;

      flex-wrap: wrap;

    }

 

    .pill {

      display: inline-flex;

      align-items: center;

      gap: 6px;

      background: rgba(255, 255, 255, 0.1);

      border: 1.5px solid rgba(255, 255, 255, 0.16);

      padding: 6px 12px;

      border-radius: 999px;

      font-weight: 800;

      font-size: 0.95rem;

    }

 

    .hp-bar-wrap {

      display: flex;

      align-items: center;

      gap: 6px;

      background: rgba(0, 0, 0, 0.28);

      padding: 4px 10px;

      border-radius: 999px;

    }

 

    .hp-track {

      width: 90px;

      height: 12px;

      background: rgba(255, 255, 255, 0.16);

      border-radius: 999px;

      overflow: hidden;

    }

 

    .hp-fill {

      height: 100%;

      width: 100%;

      background: linear-gradient(90deg, #ff595e, #ffca3a, #8ac926);

      transition: width 0.25s ease;

    }

 

    .btn {

      border: none;

      border-radius: 18px;

      padding: 12px 18px;

      font-size: 1rem;

      font-weight: 800;

      color: #fff;

      cursor: pointer;

      display: inline-flex;

      align-items: center;

      justify-content: center;

      gap: 8px;

      min-height: 48px;

      box-shadow: 0 5px 0 rgba(0, 0, 0, 0.35);

      transition: transform 0.1s ease, filter 0.15s ease;

    }

 

    .btn:active {

      transform: translateY(3px);

      box-shadow: 0 2px 0 rgba(0, 0, 0, 0.35);

    }

 

    .btn-sm {

      min-height: 38px;

      padding: 6px 12px;

      font-size: 0.88rem;

      border-radius: 999px;

    }

 

    .btn-gold { background: linear-gradient(180deg, #ffd166, #f4a261); color: #1b263b; }

    .btn-cyan { background: linear-gradient(180deg, #4cc9f0, #3a86ff); }

    .btn-mint { background: linear-gradient(180deg, #06d6a0, #1b9aaa); color: #06282b; }

    .btn-coral { background: linear-gradient(180deg, #ff595e, #d90429); }

    .btn-purple { background: linear-gradient(180deg, #c77dff, #7209b7); }

 

    /* Views */

    .view {

      display: none;

      flex: 1;

      min-height: 0;

      position: relative;

      border-radius: var(--radius-lg);

      overflow: hidden;

    }

 

    .view.active {

      display: flex;

      flex-direction: column;

    }

 

    /* World Map View */

    .map-stage {

      position: relative;

      flex: 1;

      min-height: 0;

      border-radius: var(--radius-lg);

      background:

        radial-gradient(circle at 75% 22%, rgba(255, 209, 102, 0.22), transparent 32%),

        radial-gradient(circle at 20% 80%, rgba(76, 201, 240, 0.25), transparent 40%),

        linear-gradient(180deg, #16425b 0%, #0f344d 55%, #0a2239 100%);

      border: 2px solid rgba(255, 255, 255, 0.16);

      box-shadow: var(--shadow-pop);

      overflow: hidden;

    }

 

    .sea-wave {

      position: absolute;

      inset: 0;

      background-image: radial-gradient(rgba(255,255,255,0.08) 2px, transparent 2px);

      background-size: 36px 36px;

      animation: driftSea 14s linear infinite;

      pointer-events: none;

    }

 

    @keyframes driftSea {

      from { transform: translate(0, 0); }

      to { transform: translate(36px, 36px); }

    }

 

    .path-svg {

      position: absolute;

      inset: 0;

      width: 100%;

      height: 100%;

      pointer-events: none;

      z-index: 2;

    }

 

    .world-node {

      position: absolute;

      transform: translate(-50%, -50%);

      z-index: 5;

      width: clamp(125px, 21vw, 175px);

      padding: 12px 10px;

      border-radius: 24px;

      background: rgba(14, 33, 58, 0.92);

      border: 3px solid var(--accent-cyan);

      box-shadow: 0 10px 22px rgba(0, 0, 0, 0.45);

      text-align: center;

      cursor: pointer;

      transition: transform 0.16s ease, box-shadow 0.16s ease;

    }

 

    .world-node:hover {

      transform: translate(-50%, -54%) scale(1.03);

    }

 

    .world-node:active {

      transform: translate(-50%, -48%) scale(0.98);

    }

 

    .world-node.locked {

      filter: grayscale(0.75) brightness(0.68);

      border-color: rgba(255, 255, 255, 0.25);

    }

 

    .world-icon {

      font-size: clamp(2rem, 4.5vw, 3rem);

      line-height: 1.1;

      display: block;

      margin-bottom: 4px;

    }

 

    .world-title {

      font-size: 0.95rem;

      font-weight: 900;

      color: var(--accent-gold);

    }

 

    .world-skill {

      font-size: 0.78rem;

      color: var(--text-soft);

      margin-top: 2px;

    }

 

    .world-stars {

      margin-top: 5px;

      font-size: 0.85rem;

      color: #ffd166;

    }

 

    /* Finn Companion on Map */

    .finn-avatar {

      position: absolute;

      left: 16%;

      top: 72%;

      transform: translate(-50%, -50%);

      z-index: 8;

      display: flex;

      flex-direction: column;

      align-items: center;

      cursor: pointer;

      transition: left 0.55s cubic-bezier(0.22, 1, 0.36, 1), top 0.55s cubic-bezier(0.22, 1, 0.36, 1);

    }

 

    .finn-body {

      width: 68px;

      height: 68px;

      border-radius: 50%;

      background: linear-gradient(160deg, #ffe66d, #ff9f1c);

      border: 4px solid #ffffff;

      box-shadow: 0 8px 18px rgba(0, 0, 0, 0.45);

      display: flex;

      align-items: center;

      justify-content: center;

      font-size: 2.1rem;

      animation: finnBounce 2.2s ease-in-out infinite;

    }

 

    @keyframes finnBounce {

      0%, 100% { transform: translateY(0); }

      50% { transform: translateY(-6px); }

    }

 

    .finn-tag {

      margin-top: 4px;

      background: #06d6a0;

      color: #06282b;

      font-weight: 900;

      font-size: 0.75rem;

      padding: 2px 9px;

      border-radius: 999px;

      box-shadow: 0 3px 8px rgba(0,0,0,0.3);

    }

 

    /* Bottom Finn Dialogue & Touch Controls */

    .map-footer {

      display: grid;

      grid-template-columns: 1fr auto;

      gap: 12px;

      align-items: center;

      background: var(--card-glass);

      border: 2px solid rgba(255, 255, 255, 0.14);

      border-radius: var(--radius-md);

      padding: 10px 14px;

      z-index: 15;

    }

 

    .dialogue-box {

      display: flex;

      align-items: center;

      gap: 12px;

      min-width: 0;

    }

 

    .dialogue-text {

      font-size: 0.95rem;

      line-height: 1.35;

      color: #fff;

    }

 

    .dialogue-text strong {

      color: var(--accent-gold);

    }

 

    .dpad {

      display: grid;

      grid-template-columns: repeat(3, 42px);

      grid-template-rows: repeat(2, 40px);

      gap: 4px;

    }

 

    .dpad button {

      border: none;

      border-radius: 10px;

      background: rgba(255, 255, 255, 0.16);

      color: #fff;

      font-weight: 900;

      font-size: 1rem;

      cursor: pointer;

    }

 

    .dpad button:active {

      background: var(--accent-cyan);

      color: #071324;

    }

 

    /* Level Arena */

    .arena {

      flex: 1;

      min-height: 0;

      display: flex;

      flex-direction: column;

      background: var(--card-glass);

      border: 2px solid rgba(255, 255, 255, 0.16);

      border-radius: var(--radius-lg);

      padding: 12px;

      gap: 10px;

      box-shadow: var(--shadow-pop);

    }

 

    .arena-top {

      display: flex;

      flex-wrap: wrap;

      align-items: center;

      justify-content: space-between;

      gap: 8px;

      background: rgba(0, 0, 0, 0.25);

      padding: 10px 14px;

      border-radius: var(--radius-md);

    }

 

    .prompt-banner {

      display: flex;

      align-items: center;

      justify-content: center;

      gap: 12px;

      background: linear-gradient(90deg, rgba(76, 201, 240, 0.22), rgba(255, 209, 102, 0.22));

      border: 2px solid rgba(255, 255, 255, 0.2);

      border-radius: var(--radius-md);

      padding: 10px 16px;

      text-align: center;

      flex-shrink: 0;

    }

 

    .prompt-vi {

      font-size: clamp(1.1rem, 2.4vw, 1.45rem);

      font-weight: 900;

      color: var(--accent-gold);

    }

 

    /* Bubble Pop Playfield */

    .bubble-field {

      position: relative;

      flex: 1;

      min-height: 220px;

      border-radius: var(--radius-md);

      background:

        radial-gradient(circle at 50% 100%, rgba(6, 214, 160, 0.18), transparent 55%),

        linear-gradient(180deg, rgba(13, 59, 102, 0.65) 0%, rgba(7, 30, 56, 0.9) 100%);

      border: 2px solid rgba(76, 201, 240, 0.35);

      overflow: hidden;

    }

 

    .bubble {

      position: absolute;

      width: clamp(86px, 15vw, 116px);

      height: clamp(86px, 15vw, 116px);

      border-radius: 50%;

      border: 3px solid rgba(255, 255, 255, 0.72);

      background: radial-gradient(circle at 30% 28%, rgba(255, 255, 255, 0.65), rgba(76, 201, 240, 0.35) 55%, rgba(58, 134, 255, 0.55) 100%);

      box-shadow: inset 0 -8px 16px rgba(0, 0, 0, 0.25), 0 8px 18px rgba(0, 0, 0, 0.35);

      display: flex;

      align-items: center;

      justify-content: center;

      text-align: center;

      padding: 8px;

      font-weight: 900;

      font-size: clamp(0.95rem, 2vw, 1.2rem);

      color: #ffffff;

      text-shadow: 0 2px 6px rgba(0, 0, 0, 0.65);

      cursor: pointer;

      transform: translate(-50%, -50%);

      transition: transform 0.08s ease;

    }

 

    .bubble:active {

      transform: translate(-50%, -50%) scale(1.12);

    }

 

    .bubble.trap {

      background: radial-gradient(circle at 30% 28%, rgba(255, 210, 210, 0.6), rgba(255, 89, 94, 0.45) 60%, rgba(160, 10, 40, 0.7) 100%);

      border-color: #ff9ebb;

    }

 

    /* Other 3 Skills Activity Cards */

    .activity-card {

      flex: 1;

      min-height: 0;

      display: flex;

      flex-direction: column;

      justify-content: center;

      align-items: center;

      gap: 14px;

      padding: 16px;

      border-radius: var(--radius-md);

      background: rgba(8, 22, 42, 0.65);

      border: 2px solid rgba(255, 255, 255, 0.14);

      overflow-y: auto;

    }

 

    .choice-grid {

      display: grid;

      grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));

      gap: 12px;

      width: 100%;

      max-width: 720px;

    }

 

    .tile-btn {

      min-height: 64px;

      border-radius: 18px;

      border: 2px solid rgba(255, 255, 255, 0.24);

      background: rgba(255, 255, 255, 0.12);

      color: #fff;

      font-size: 1.05rem;

      font-weight: 800;

      padding: 12px 14px;

      cursor: pointer;

      transition: transform 0.1s ease, background 0.15s ease;

    }

 

    .tile-btn:active {

      transform: scale(0.97);

    }

 

    .tile-btn.picked {

      background: linear-gradient(180deg, #06d6a0, #1b9aaa);

      color: #052226;

      border-color: #b8fff0;

    }

 

    /* Modals (Shop & End Screen) */

    .modal-backdrop {

      position: fixed;

      inset: 0;

      background: rgba(4, 12, 24, 0.78);

      backdrop-filter: blur(6px);

      display: none;

      align-items: center;

      justify-content: center;

      padding: 16px;

      z-index: 50;

    }

 

    .modal-backdrop.open {

      display: flex;

    }

 

    .modal-card {

      width: 100%;

      max-width: 560px;

      max-height: 88dvh;

      overflow-y: auto;

      background: #102644;

      border: 2px solid rgba(255, 255, 255, 0.22);

      border-radius: var(--radius-lg);

      padding: 20px;

      box-shadow: var(--shadow-pop);

    }

 

    .shop-grid {

      display: grid;

      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));

      gap: 12px;

      margin: 14px 0;

    }

 

    .shop-item {

      background: rgba(255, 255, 255, 0.08);

      border: 2px solid rgba(255, 255, 255, 0.16);

      border-radius: 18px;

      padding: 12px;

      text-align: center;

      display: flex;

      flex-direction: column;

      align-items: center;

      gap: 8px;

    }

 

    .toast {

      position: fixed;

      bottom: 84px;

      left: 50%;

      transform: translateX(-50%) translateY(20px);

      background: rgba(10, 25, 47, 0.95);

      border: 2px solid var(--accent-gold);

      color: #fff;

      padding: 10px 18px;

      border-radius: 999px;

      font-weight: 800;

      opacity: 0;

      pointer-events: none;

      transition: opacity 0.2s ease, transform 0.2s ease;

      z-index: 60;

      text-align: center;

      max-width: 90vw;

    }

 

    .toast.show {

      opacity: 1;

      transform: translateX(-50%) translateY(0);

    }

  </style>

</head>

<body>

  <div class="app-shell">

    <!-- TOP HUD -->

    <header class="hud">

      <div class="hud-group">

        <button id="btnHome" class="btn btn-cyan btn-sm" style="display:none;" onclick="goToMap()">🗺️ Bản đồ</button>

        <div class="hp-bar-wrap" title="Thanh năng lượng của Finn">

          <span>❤️</span>

          <div class="hp-track"><div id="hpFill" class="hp-fill"></div></div>

          <span id="hpText">100</span>

        </div>

        <div class="pill">🪙 <span id="hudCoins">0</span></div>

        <div class="pill">⭐ <span id="hudStars">0</span></div>

      </div>

 

      <div class="hud-group">

        <button class="btn btn-gold btn-sm" onclick="openShop()">🎒 Trang phục & Vật phẩm</button>

        <button class="btn btn-purple btn-sm" onclick="toggleSound()" id="btnSound">🔊 Tiếng: Bật</button>

      </div>

    </header>

 

    <!-- VIEW 1: WORLD MAP -->

    <section id="viewMap" class="view active">

      <div class="map-stage" id="mapStage">

        <div class="sea-wave"></div>

        <svg class="path-svg" viewBox="0 0 1000 600" preserveAspectRatio="none">

          <path d="M 180 430 Q 320 260 410 190 T 680 220 T 830 430"

                fill="none" stroke="rgba(255,209,102,0.55)" stroke-width="8" stroke-dasharray="14 12" />

        </svg>

 

        <!-- 4 World Nodes -->

        <div class="world-node" id="node-listening" style="left: 18%; top: 34%;" onclick="selectWorld('listening')">

          <span class="world-icon">🏝️</span>

          <div class="world-title">Ocean of Sounds</div>

          <div class="world-skill">Listening • Bubble Pop</div>

          <div class="world-stars" id="stars-listening">☆☆☆</div>

        </div>

 

        <div class="world-node locked" id="node-speaking" style="left: 43%; top: 24%;" onclick="selectWorld('speaking')">

          <span class="world-icon">🌲</span>

          <div class="world-title">Magic Forest</div>

          <div class="world-skill">Speaking • Hội thoại</div>

          <div class="world-stars" id="stars-speaking">🔒 Mở khóa</div>

        </div>

 

        <div class="world-node locked" id="node-reading" style="left: 68%; top: 28%;" onclick="selectWorld('reading')">

          <span class="world-icon">🏰</span>

          <div class="world-title">Mystery Castle</div>

          <div class="world-skill">Reading • Mật thư</div>

          <div class="world-stars" id="stars-reading">🔒 Mở khóa</div>

        </div>

 

        <div class="world-node locked" id="node-writing" style="left: 82%; top: 64%;" onclick="selectWorld('writing')">

          <span class="world-icon">🌋</span>

          <div class="world-title">Dragon Mountain</div>

          <div class="world-skill">Writing • Thần chú</div>

          <div class="world-stars" id="stars-writing">🔒 Mở khóa</div>

        </div>

 

        <!-- Finn Companion -->

        <div class="finn-avatar" id="finnAvatar" onclick="petFinn()">

          <div class="finn-body" id="finnOutfitIcon">🧭</div>

          <div class="finn-tag">Finn</div>

        </div>

      </div>

 

      <div class="map-footer">

        <div class="dialogue-box">

          <div style="font-size:2rem;">💬</div>

          <div class="dialogue-text" id="finnDialogue">

            <strong>Finn:</strong> Chào nhà thám hiểm! Chạm vào <strong>Ocean of Sounds</strong> để bắt đầu hành trình tìm kho báu tiếng Anh nhé!

          </div>

        </div>

        <div class="dpad" aria-label="Điều khiển Finn">

          <div></div>

          <button onclick="moveFinn(0, -35)">▲</button>

          <div></div>

          <button onclick="moveFinn(-35, 0)">◀</button>

          <button onclick="moveFinn(0, 35)">▼</button>

          <button onclick="moveFinn(35, 0)">▶</button>

        </div>

      </div>

    </section>

 

    <!-- VIEW 2: LEVEL ARENA -->

    <section id="viewGame" class="view">

      <div class="arena">

        <div class="arena-top">

          <div class="hud-group">

            <span class="pill" id="gameMission">🎯 Nhiệm vụ: 0/5</span>

            <span class="pill" id="gameTimer">⏱️ 45s</span>

            <span class="pill" id="gameScore">⚡ 0 điểm</span>

            <span class="pill" id="gameCombo">🔥 x1</span>

          </div>

          <div id="gameHearts" style="font-size:1.3rem;">❤️❤️❤️</div>

        </div>

 

        <div class="prompt-banner">

          <button class="btn btn-gold btn-sm" id="btnSpeakPrompt" onclick="replayCurrentAudio()">🔊 Nghe lại</button>

          <div>

            <div id="promptSub" style="font-size:0.82rem; color:var(--text-soft);">Chạm đúng bong bóng có nghĩa:</div>

            <div id="promptMain" class="prompt-vi">Quả táo</div>

          </div>

        </div>

 

        <!-- Bubble Pop Field (Listening) -->

        <div id="bubbleField" class="bubble-field" style="display:none;"></div>

 

        <!-- Interactive Activity Card (Speaking / Reading / Writing) -->

        <div id="activityCard" class="activity-card" style="display:none;"></div>

      </div>

    </section>

  </div>

 

  <!-- SHOP MODAL -->

  <div id="shopModal" class="modal-backdrop" onclick="closeModalBackdrop(event, 'shopModal')">

    <div class="modal-card">

      <div style="display:flex; justify-content:space-between; align-items:center;">

        <h2 style="margin:0; color:var(--accent-gold);">🎒 Trang phục & Vật phẩm</h2>

        <button class="btn btn-coral btn-sm" onclick="closeModal('shopModal')">✕</button>

      </div>

      <p style="color:var(--text-soft); margin:6px 0 0;">Dùng xu thu thập được để trang bị cho Finn và tăng sức mạnh phiêu lưu.</p>

      <div class="shop-grid" id="shopGrid"></div>

    </div>

  </div>

 

  <!-- RESULT MODAL -->

  <div id="resultModal" class="modal-backdrop">

    <div class="modal-card" style="text-align:center;">

      <div id="resultBadge" style="font-size:3rem;">🏆</div>

      <h2 id="resultTitle" style="margin:8px 0; color:var(--accent-gold);">Hoàn thành màn chơi!</h2>

      <p id="resultDesc" style="color:var(--text-soft); margin-bottom:16px;"></p>

      <div style="display:flex; gap:10px; justify-content:center; flex-wrap:wrap;">

        <button class="btn btn-mint" onclick="replayCurrentWorld()">🔁 Chơi lại</button>

        <button class="btn btn-cyan" onclick="goToMap()">🗺️ Về bản đồ</button>

      </div>

    </div>

  </div>

 

  <div id="toast" class="toast"></div>

 

  <script>

    const STORAGE_KEY = "finn_quest_save_v1";

 

    const DEFAULT_SAVE = {

      coins: 30,

      stars: 0,

      hp: 100,

      unlocked: { listening: true, speaking: false, reading: false, writing: false },

      worldStars: { listening: 0, speaking: 0, reading: 0, writing: 0 },

      ownedItems: ["compass"],

      equipped: "compass",

      finnPos: { x: 16, y: 72 }

    };

 

    const SHOP_ITEMS = [

      { id: "compass", name: "Nhà thám hiểm", icon: "🧭", price: 0, bonus: "Mặc định" },

      { id: "wizard", name: "Pháp sư rừng xanh", icon: "🧙‍♂️", price: 40, bonus: "+20 điểm/câu" },

      { id: "knight", name: "Hiệp sĩ lâu đài", icon: "🛡️", price: 60, bonus: "Hồi +25 HP khi thắng" },

      { id: "dragon", name: "Chiến binh rồng lửa", icon: "🐉", price: 80, bonus: "Combo tăng nhanh" }

    ];

 

    const LISTENING_BANK = [

      { en: "apple", vi: "🍎 Quả táo" },

      { en: "dolphin", vi: "🐬 Cá heo" },

      { en: "treasure", vi: "💎 Kho báu" },

      { en: "island", vi: "🏝️ Hòn đảo" },

      { en: "starfish", vi: "⭐ Sao biển" },

      { en: "lighthouse", vi: "🗼 Ngọn hải đăng" },

      { en: "turtle", vi: "🐢 Rùa biển" },

      { en: "rainbow", vi: "🌈 Cầu vồng" }

    ];

 

    const SPEAKING_QUESTS = [

      {

        npc: "🦉 Cú Thông Thái",

        say: "Hello Finn! What is your name?",

        viHint: "Chào Finn! Bạn tên là gì?",

        target: "My name is Finn",

        options: ["My name is Finn", "I like pizza", "Good night"]

      },

      {

        npc: "🐿️ Sóc Nhanh Nhẹn",

        say: "Where is the magic tree?",

        viHint: "Cây thần kỳ ở đâu nhỉ?",

        target: "Turn left at the river",

        options: ["Turn left at the river", "I am nine years old", "It is a blue car"]

      },

      {

        npc: "🦊 Cáo Nấu Ăn",

        say: "What would you like to drink?",

        viHint: "Bạn muốn uống gì nào?",

        target: "Apple juice please",

        options: ["Apple juice please", "See you tomorrow", "Open the door"]

      }

    ];

 

    const READING_QUESTS = [

      {

        letter: "📜 Mật thư 1: 'The golden key is hidden under the BIG BLUE BOOK.'",

        question: "Manh mối chỉ ra chiếc chìa khóa vàng nằm ở đâu?",

        options: ["Dưới quyển sách xanh lớn", "Trên ngọn tháp cao", "Trong chiếc thuyền nhỏ"],

        answer: "Dưới quyển sách xanh lớn"

      },

      {

        letter: "📜 Mật thư 2: 'Do NOT open the red door. Take the SECRET STAIRS.'",

        question: "Theo mật thư, lối đi an toàn là lối nào?",

        options: ["Cầu thang bí mật", "Cánh cửa màu đỏ", "Hầm tối phía tây"],

        answer: "Cầu thang bí mật"

      }

    ];

 

    const WRITING_QUESTS = [

      {

        vi: "Ghép câu thần chú: 'I love English'",

        pieces: ["English", "I", "love", "dragon"],

        solution: ["I", "love", "English"]

      },

      {

        vi: "Ghép câu thần chú: 'Fly high dragon'",

        pieces: ["high", "Fly", "dragon", "sleep"],

        solution: ["Fly", "high", "dragon"]

      }

    ];

 

    let state = loadSave();

    let soundEnabled = true;

    let activeWorld = null;

    let gameLoopId = null;

    let timerId = null;

    let spawnId = null;

    let bubbles = [];

    let currentTarget = null;

    let missionDone = 0;

    const missionGoal = 5;

    let hearts = 3;

    let score = 0;

    let combo = 1;

    let timeLeft = 45;

    let subIndex = 0;

    let pickedWords = [];

 

    function loadSave() {

      try {

        const raw = localStorage.getItem(STORAGE_KEY);

        if (!raw) return structuredClone(DEFAULT_SAVE);

        return { ...structuredClone(DEFAULT_SAVE), ...JSON.parse(raw) };

      } catch {

        return structuredClone(DEFAULT_SAVE);

      }

    }

 

    function persistSave() {

      try {

        localStorage.setItem(STORAGE_KEY, JSON.stringify(state));

      } catch {}

    }

 

    function showToast(msg) {

      const el = document.getElementById("toast");

      el.textContent = msg;

      el.classList.add("show");

      clearTimeout(showToast._t);

      showToast._t = setTimeout(() => el.classList.remove("show"), 2200);

    }

 

    function toggleSound() {

      soundEnabled = !soundEnabled;

      document.getElementById("btnSound").textContent = soundEnabled ? "🔊 Tiếng: Bật" : "🔇 Tiếng: Tắt";

      showToast(soundEnabled ? "Đã bật âm thanh" : "Đã tắt âm thanh");

    }

 

    function playPopSound(good = true) {

      if (!soundEnabled) return;

      try {

        const AudioCtx = window.AudioContext || window.webkitAudioContext;

        const ctx = new AudioCtx();

        const osc = ctx.createOscillator();

        const gain = ctx.createGain();

        osc.type = good ? "sine" : "sawtooth";

        osc.frequency.setValueAtTime(good ? 520 : 190, ctx.currentTime);

        if (good) osc.frequency.exponentialRampToValueAtTime(880, ctx.currentTime + 0.12);

        gain.gain.setValueAtTime(0.18, ctx.currentTime);

        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.16);

        osc.connect(gain);

        gain.connect(ctx.destination);

        osc.start();

        osc.stop(ctx.currentTime + 0.17);

      } catch {}

    }

 

    function speakEnglish(text) {

      if (!soundEnabled || !("speechSynthesis" in window)) return;

      try {

        window.speechSynthesis.cancel();

        const utter = new SpeechSynthesisUtterance(text);

        utter.lang = "en-US";

        utter.rate = 0.92;

        window.speechSynthesis.speak(utter);

      } catch {}

    }

 

    function replayCurrentAudio() {

      if (activeWorld === "listening" && currentTarget) {

        speakEnglish(currentTarget.en);

      } else if (activeWorld === "speaking") {

        const q = SPEAKING_QUESTS[subIndex % SPEAKING_QUESTS.length];

        speakEnglish(q.say);

      } else if (activeWorld === "writing") {

        const q = WRITING_QUESTS[subIndex % WRITING_QUESTS.length];

        speakEnglish(q.solution.join(" "));

      } else {

        showToast("Hãy đọc kỹ mật thư và chọn manh mối đúng nhé!");

      }

    }

 

    function updateHUD() {

      document.getElementById("hudCoins").textContent = state.coins;

      const totalStars = Object.values(state.worldStars).reduce((a, b) => a + b, 0);

      state.stars = totalStars;

      document.getElementById("hudStars").textContent = totalStars;

      document.getElementById("hpFill").style.width = `${Math.max(0, Math.min(100, state.hp))}%`;

      document.getElementById("hpText").textContent = Math.max(0, state.hp);

 

      const item = SHOP_ITEMS.find(i => i.id === state.equipped) || SHOP_ITEMS[0];

      document.getElementById("finnOutfitIcon").textContent = item.icon;

 

      const finn = document.getElementById("finnAvatar");

      finn.style.left = `${state.finnPos.x}%`;

      finn.style.top = `${state.finnPos.y}%`;

 

      const worlds = ["listening", "speaking", "reading", "writing"];

      worlds.forEach(w => {

        const node = document.getElementById(`node-${w}`);

        const starEl = document.getElementById(`stars-${w}`);

        if (state.unlocked[w]) {

          node.classList.remove("locked");

          const s = state.worldStars[w] || 0;

          starEl.textContent = "★".repeat(s) + "☆".repeat(3 - s);

        } else {

          node.classList.add("locked");

          starEl.textContent = "🔒 Mở khóa";

        }

      });

 

      persistSave();

    }

 

    function setDialogue(speaker, text) {

      document.getElementById("finnDialogue").innerHTML = `<strong>${speaker}:</strong> ${text}`;

    }

 

    function petFinn() {

      const lines = [

        "Finn vui quá! Cùng chinh phục 4 vùng đất tiếng Anh nào!",

        "Chạm vào bong bóng có nghĩa đúng để tạo Combo thật cao nhé!",

        "Thu thập nhiều xu để mở khóa áo giáp và mũ pháp sư cho Finn!"

      ];

      setDialogue("Finn", lines[Math.floor(Math.random() * lines.length)]);

      playPopSound(true);

    }

 

    function moveFinn(dxPct, dyPct) {

      state.finnPos.x = Math.max(8, Math.min(90, state.finnPos.x + dxPct * 0.25));

      state.finnPos.y = Math.max(18, Math.min(84, state.finnPos.y + dyPct * 0.25));

      updateHUD();

    }

 

    window.addEventListener("keydown", (e) => {

      if (!document.getElementById("viewMap").classList.contains("active")) return;

      if (e.key === "ArrowLeft") moveFinn(-16, 0);

      if (e.key === "ArrowRight") moveFinn(16, 0);

      if (e.key === "ArrowUp") moveFinn(0, -16);

      if (e.key === "ArrowDown") moveFinn(0, 16);

    });

 

    function selectWorld(world) {

      if (!state.unlocked[world]) {

        showToast("Hãy hoàn thành vùng đất trước để mở khóa khu vực này!");

        setDialogue("Finn", "Khu vực này đang có phép thuật bảo vệ. Hãy vượt qua vùng trước đó trước nhé!");

        return;

      }

 

      const coords = {

        listening: { x: 18, y: 50 },

        speaking: { x: 43, y: 40 },

        reading: { x: 68, y: 44 },

        writing: { x: 82, y: 78 }

      };

      state.finnPos = coords[world];

      updateHUD();

      startLevel(world);

    }

 

    function goToMap() {

      stopLevelTimers();

      document.getElementById("resultModal").classList.remove("open");

      document.getElementById("viewGame").classList.remove("active");

      document.getElementById("viewMap").classList.add("active");

      document.getElementById("btnHome").style.display = "none";

      updateHUD();

    }

 

    function stopLevelTimers() {

      cancelAnimationFrame(gameLoopId);

      clearInterval(timerId);

      clearInterval(spawnId);

    }

 

    function startLevel(world) {

      stopLevelTimers();

      activeWorld = world;

      missionDone = 0;

      hearts = 3;

      score = 0;

      combo = 1;

      timeLeft = 45;

      subIndex = 0;

      pickedWords = [];

 

      if (state.hp <= 15) state.hp = 60;

      updateHUD();

 

      document.getElementById("viewMap").classList.remove("active");

      document.getElementById("viewGame").classList.add("active");

      document.getElementById("btnHome").style.display = "inline-flex";

 

      renderArenaHUD();

 

      const field = document.getElementById("bubbleField");

      const card = document.getElementById("activityCard");

 

      timerId = setInterval(() => {

        timeLeft--;

        renderArenaHUD();

        if (timeLeft <= 0) finishLevel(false, "Hết giờ mất rồi! Thử lại nhé.");

      }, 1000);

 

      if (world === "listening") {

        field.style.display = "block";

        card.style.display = "none";

        pickNextListeningTarget();

        spawnBubble();

        spawnBubble();

        spawnId = setInterval(spawnBubble, 1150);

        gameLoopId = requestAnimationFrame(updateBubbles);

      } else {

        field.style.display = "none";

        card.style.display = "flex";

        renderSkillActivity();

      }

    }

 

    function replayCurrentWorld() {

      document.getElementById("resultModal").classList.remove("open");

      if (activeWorld) startLevel(activeWorld);

    }

 

    function renderArenaHUD() {

      document.getElementById("gameMission").textContent = `🎯 Nhiệm vụ: ${missionDone}/${missionGoal}`;

      document.getElementById("gameTimer").textContent = `⏱️ ${timeLeft}s`;

      document.getElementById("gameScore").textContent = `⚡ ${score} điểm`;

      document.getElementById("gameCombo").textContent = `🔥 x${combo}`;

      document.getElementById("gameHearts").textContent = "❤️".repeat(hearts) + "🖤".repeat(Math.max(0, 3 - hearts));

    }

 

    function pickNextListeningTarget() {

      currentTarget = LISTENING_BANK[Math.floor(Math.random() * LISTENING_BANK.length)];

      document.getElementById("promptSub").textContent = "Nghe & chạm bong bóng tiếng Anh có nghĩa:";

      document.getElementById("promptMain").textContent = currentTarget.vi;

      speakEnglish(currentTarget.en);

    }

 

    function spawnBubble() {

      const field = document.getElementById("bubbleField");

      if (!field || bubbles.length >= 7) return;

      const rect = field.getBoundingClientRect();

      if (rect.width < 80 || rect.height < 80) return;

 

      const isTrap = Math.random() < 0.16 && bubbles.some(b => !b.isTrap && b.word === currentTarget?.en);

      let wordObj = LISTENING_BANK[Math.floor(Math.random() * LISTENING_BANK.length)];

 

      // Ensure target word appears frequently

      if (!isTrap && Math.random() < 0.42 && currentTarget) {

        wordObj = currentTarget;

      }

 

      const el = document.createElement("button");

      el.type = "button";

      el.className = isTrap ? "bubble trap" : "bubble";

      el.textContent = isTrap ? "👾" : wordObj.en;

 

      const b = {

        el,

        word: isTrap ? "__TRAP__" : wordObj.en,

        isTrap,

        x: 70 + Math.random() * Math.max(80, rect.width - 140),

        y: rect.height + 40,

        vx: (Math.random() - 0.5) * (1.2 + missionDone * 0.25),

        vy: -(1.35 + Math.random() * 0.9 + missionDone * 0.22)

      };

 

      el.style.left = `${b.x}px`;

      el.style.top = `${b.y}px`;

 

      el.addEventListener("pointerdown", (e) => {

        e.stopPropagation();

        onBubbleTap(b);

      });

 

      field.appendChild(el);

      bubbles.push(b);

    }

 

    function updateBubbles() {

      const field = document.getElementById("bubbleField");

      if (!field || activeWorld !== "listening") return;

      const rect = field.getBoundingClientRect();

 

      for (let i = bubbles.length - 1; i >= 0; i--) {

        const b = bubbles[i];

        b.x += b.vx;

        b.y += b.vy;

 

        if (b.x < 55 || b.x > rect.width - 55) b.vx *= -1;

 

        b.el.style.left = `${b.x}px`;

        b.el.style.top = `${b.y}px`;

 

        if (b.y < -70) {

          b.el.remove();

          bubbles.splice(i, 1);

        }

      }

 

      gameLoopId = requestAnimationFrame(updateBubbles);

    }

 

    function onBubbleTap(b) {

      const idx = bubbles.indexOf(b);

      if (idx === -1) return;

      b.el.remove();

      bubbles.splice(idx, 1);

 

      if (!b.isTrap && currentTarget && b.word === currentTarget.en) {

        const bonus = state.equipped === "wizard" ? 20 : 0;

        score += 20 * combo + bonus;

        combo = Math.min(5, combo + (state.equipped === "dragon" ? 2 : 1));

        missionDone++;

        playPopSound(true);

        showToast(`Chính xác! "${b.word}" (+${20 * combo + bonus})`);

        renderArenaHUD();

 

        if (missionDone >= missionGoal) {

          finishLevel(true, "Bạn đã tìm đủ kho báu âm thanh dưới đại dương!");

        } else {

          pickNextListeningTarget();

        }

      } else {

        handleMistake(b.isTrap ? "Chạm trúng quái vật biển!" : `Chưa đúng rồi! Từ cần tìm là "${currentTarget.en}".`);

      }

    }

 

    function handleMistake(msg) {

      combo = 1;

      hearts--;

      state.hp = Math.max(0, state.hp - 15);

      playPopSound(false);

      showToast(msg);

      renderArenaHUD();

      updateHUD();

 

      if (hearts <= 0 || state.hp <= 0) {

        finishLevel(false, "Finn bị mất hết tim năng lượng rồi. Nghỉ ngơi và thử lại nhé!");

      }

    }

 

    function renderSkillActivity() {

      const card = document.getElementById("activityCard");

      card.innerHTML = "";

 

      if (activeWorld === "speaking") {

        const q = SPEAKING_QUESTS[subIndex % SPEAKING_QUESTS.length];

        document.getElementById("promptSub").textContent = `${q.npc} nói:`;

        document.getElementById("promptMain").textContent = `"${q.say}" (${q.viHint})`;

        speakEnglish(q.say);

 

        const micBtn = document.createElement("button");

        micBtn.className = "btn btn-mint";

        micBtn.textContent = "🎤 Nói câu trả lời (hoặc chạm thẻ bên dưới)";

        micBtn.onclick = () => startSpeechRecognition(q.target);

        card.appendChild(micBtn);

 

        const grid = document.createElement("div");

        grid.className = "choice-grid";

        q.options.forEach(opt => {

          const btn = document.createElement("button");

          btn.className = "tile-btn";

          btn.textContent = opt;

          btn.onclick = () => evaluateTextAnswer(opt.toLowerCase(), q.target.toLowerCase(), opt);

          grid.appendChild(btn);

        });

        card.appendChild(grid);

      }

 

      if (activeWorld === "reading") {

        const q = READING_QUESTS[subIndex % READING_QUESTS.length];

        document.getElementById("promptSub").textContent = "Giải mã mật thư lâu đài:";

        document.getElementById("promptMain").textContent = q.letter;

 

        const qTitle = document.createElement("div");

        qTitle.style.fontWeight = "800";

        qTitle.style.fontSize = "1.05rem";

        qTitle.textContent = q.question;

        card.appendChild(qTitle);

 

        const grid = document.createElement("div");

        grid.className = "choice-grid";

        q.options.forEach(opt => {

          const btn = document.createElement("button");

          btn.className = "tile-btn";

          btn.textContent = opt;

          btn.onclick = () => evaluateTextAnswer(opt, q.answer, opt);

          grid.appendChild(btn);

        });

        card.appendChild(grid);

      }

 

      if (activeWorld === "writing") {

        const q = WRITING_QUESTS[subIndex % WRITING_QUESTS.length];

        document.getElementById("promptSub").textContent = "Chạm ghép các từ thành câu thần chú:";

        document.getElementById("promptMain").textContent = q.vi;

 

        const line = document.createElement("div");

        line.style.fontSize = "1.25rem";

        line.style.fontWeight = "900";

        line.style.color = "var(--accent-mint)";

        line.textContent = pickedWords.length ? pickedWords.join(" ") : "___ ___ ___";

        card.appendChild(line);

 

        const grid = document.createElement("div");

        grid.className = "choice-grid";

        q.pieces.forEach(word => {

          const btn = document.createElement("button");

          btn.className = "tile-btn";

          btn.textContent = word;

          btn.onclick = () => {

            pickedWords.push(word);

            speakEnglish(word);

            if (pickedWords.length === q.solution.length) {

              const ok = pickedWords.join(" ") === q.solution.join(" ");

              pickedWords = [];

              evaluateTextAnswer(ok ? "ok" : "no", "ok", q.solution.join(" "));

            } else {

              renderSkillActivity();

            }

          };

          grid.appendChild(btn);

        });

        card.appendChild(grid);

 

        const clr = document.createElement("button");

        clr.className = "btn btn-coral btn-sm";

        clr.textContent = "↺ Xóa chữ đã chọn";

        clr.onclick = () => { pickedWords = []; renderSkillActivity(); };

        card.appendChild(clr);

      }

    }

 

    function startSpeechRecognition(expected) {

      const SR = window.SpeechRecognition || window.webkitSpeechRecognition;

      if (!SR) {

        showToast("Thiết bị này chưa hỗ trợ nhận diện giọng nói — hãy chạm thẻ đáp án nhé!");

        return;

      }

      const rec = new SR();

      rec.lang = "en-US";

      rec.interimResults = false;

      showToast("🎧 Đang nghe giọng nói của bạn...");

      rec.onresult = (ev) => {

        const spoken = ev.results[0][0].transcript || "";

        evaluateTextAnswer(spoken.toLowerCase().trim(), expected.toLowerCase().trim(), spoken);

      };

      rec.onerror = () => {

        showToast("Chưa nghe rõ — bạn có thể thử lại hoặc chạm thẻ câu trả lời.");

      };

      rec.start();

    }

 

    function evaluateTextAnswer(given, expected, displayLabel) {

      const matched = given === expected || (expected.length > 6 && given.includes(expected.split(" ")[0]));

      if (matched) {

        score += 30 * combo;

        combo = Math.min(5, combo + 1);

        missionDone++;

        subIndex++;

        playPopSound(true);

        showToast(`Tuyệt vời! "${displayLabel}"`);

        renderArenaHUD();

        if (missionDone >= missionGoal) {

          finishLevel(true, "Thử thách vượt qua rực rỡ!");

        } else {

          renderSkillActivity();

        }

      } else {

        pickedWords = [];

        handleMistake(`Chưa đúng "${displayLabel}" — cùng thử lại nhé!`);

        if (activeWorld !== "listening") renderSkillActivity();

      }

    }

 

    function finishLevel(won, message) {

      stopLevelTimers();

      bubbles.forEach(b => b.el.remove());

      bubbles = [];

 

      const order = ["listening", "speaking", "reading", "writing"];

      const idx = order.indexOf(activeWorld);

 

      if (won) {

        const earnedCoins = 25 + score;

        const earnedStars = hearts === 3 ? 3 : hearts === 2 ? 2 : 1;

        state.coins += earnedCoins;

        state.worldStars[activeWorld] = Math.max(state.worldStars[activeWorld] || 0, earnedStars);

        if (state.equipped === "knight") {

          state.hp = Math.min(100, state.hp + 25);

        }

        if (idx >= 0 && idx + 1 < order.length) {

          state.unlocked[order[idx + 1]] = true;

        }

        updateHUD();

        document.getElementById("resultBadge").textContent = "🏆";

        document.getElementById("resultTitle").textContent = "Chiến thắng rực rỡ!";

        document.getElementById("resultDesc").textContent = `${message} Bạn nhận được +${earnedCoins} xu và ${"⭐".repeat(earnedStars)}!`;

      } else {

        updateHUD();

        document.getElementById("resultBadge").textContent = "💫";

        document.getElementById("resultTitle").textContent = "Chưa qua màn lần này";

        document.getElementById("resultDesc").textContent = message;

      }

 

      document.getElementById("resultModal").classList.add("open");

    }

 

    function openShop() {

      const grid = document.getElementById("shopGrid");

      grid.innerHTML = "";

      SHOP_ITEMS.forEach(item => {

        const owned = state.ownedItems.includes(item.id);

        const equipped = state.equipped === item.id;

        const card = document.createElement("div");

        card.className = "shop-item";

        card.innerHTML = `

          <div style="font-size:2.2rem;">${item.icon}</div>

          <div style="font-weight:900;">${item.name}</div>

          <div style="font-size:0.78rem; color:var(--text-soft);">${item.bonus}</div>

          <div style="font-size:0.85rem; color:var(--accent-gold);">🪙 ${item.price}</div>

        `;

        const btn = document.createElement("button");

        btn.className = equipped ? "btn btn-mint btn-sm" : owned ? "btn btn-cyan btn-sm" : "btn btn-gold btn-sm";

        btn.textContent = equipped ? "Đang dùng" : owned ? "Trang bị" : "Mua ngay";

        btn.onclick = () => {

          if (owned) {

            state.equipped = item.id;

            updateHUD();

            openShop();

            showToast(`Đã trang bị ${item.name} cho Finn!`);

          } else if (state.coins >= item.price) {

            state.coins -= item.price;

            state.ownedItems.push(item.id);

            state.equipped = item.id;

            updateHUD();

            openShop();

            showToast(`Đã mở khóa ${item.name}!`);

          } else {

            showToast("Chưa đủ xu rồi — chơi thêm màn để kiếm xu nhé!");

          }

        };

        card.appendChild(btn);

        grid.appendChild(card);

      });

      document.getElementById("shopModal").classList.add("open");

    }

 

    function closeModal(id) {

      document.getElementById(id).classList.remove("open");

    }

 

    function closeModalBackdrop(e, id) {

      if (e.target.id === id) closeModal(id);

    }

 

    updateHUD();

  </script>

</body>

</html>