<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>香港地铁全景图 | 高德/百度公交地铁模式 & 实时双币票价系统</title>
  <!-- Inline SVG Favicon for Cloudflare Pages (Prevents 404 on /favicon.ico) -->
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' rx='25' fill='%232563eb'/><path d='M30 25h40a10 10 0 0 1 10 10v35a10 10 0 0 1-10 10l5 8H65l-5-8H40l-5 8H25l5-8a10 10 0 0 1-10-10V35a10 10 0 0 1 10-10zm2 12v16h36V37H32zm6 25a5 5 0 1 0 0 10 5 5 0 0 0 0-10zm24 0a5 5 0 1 0 0 10 5 5 0 0 0 0-10z' fill='%23fff'/></svg>">

  <!-- Tailwind CSS CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Leaflet CSS & JS -->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
  <!-- FontAwesome Icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
  <!-- Google Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;600;700;800&family=Plus+Jakarta+Sans:wght@500;600;700&display=swap" rel="stylesheet">

  <script>
    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            sans: ['"Noto Sans SC"', '"Plus Jakarta Sans"', 'system-ui', 'sans-serif'],
          },
          colors: {
            mtr: {
              eastrail: '#53B7E8',    // 东铁线 天蓝
              tsuenwan: '#E60012',    // 荃湾线 红色
              island: '#0071CE',      // 港岛线 蓝色
              kwuntong: '#00AB4E',    // 观塘线 绿色
              tuenma: '#923011',      // 屯马线 棕色
              tungchung: '#F38B00',   // 东涌线 橙色
              airport: '#008779',     // 机场快线 蓝绿色
              southisland: '#B6BD00', // 南港岛线 黄绿色
              tseungkwano: '#A35EB5', // 将军澳线 紫色
              disney: '#F173AC',      // 迪士尼线 粉色
            }
          }
        }
      }
    }
  </script>

  <style>
    /* Map and Leaflet Overrides */
    #map {
      height: 100%;
      width: 100%;
      z-index: 10;
      background: #f0f3f6;
    }
    
    /* Clean Leaflet div icon overrides - strictly eliminate square black borders */
    .leaflet-div-icon {
      background: transparent !important;
      border: none !important;
    }

    .leaflet-control-zoom {
      border: none !important;
      box-shadow: 0 4px 16px rgba(0,0,0,0.12) !important;
      border-radius: 12px !important;
      overflow: hidden;
    }
    .leaflet-control-zoom a {
      background-color: #ffffff !important;
      color: #1e293b !important;
      border-bottom: 1px solid #f1f5f9 !important;
      width: 38px !important;
      height: 38px !important;
      line-height: 38px !important;
      font-size: 16px !important;
    }

    /* Radar radar animation for Border Crossings */
    @keyframes amap-radar {
      0% { transform: scale(0.95); opacity: 0.9; }
      60% { transform: scale(1.8); opacity: 0.25; }
      100% { transform: scale(2.4); opacity: 0; }
    }

    .border-station-radar {
      position: relative;
    }
    .border-station-radar::after {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background-color: currentColor;
      border-radius: 50%;
      animation: amap-radar 2.2s cubic-bezier(0.2, 0.6, 0.35, 1) infinite;
      z-index: -1;
    }

    /* GaoDe/Baidu style Station node transitions */
    .amap-station-marker {
      display: flex;
      align-items: center;
      justify-content: center;
      transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
      cursor: pointer;
    }
    .amap-station-marker:hover {
      transform: scale(1.35);
      z-index: 9999 !important;
    }

    /* Modal Animation */
    @keyframes modalFadeIn {
      from { opacity: 0; transform: scale(0.96) translateY(8px); }
      to { opacity: 1; transform: scale(1) translateY(0); }
    }
    .animate-modal-in {
      animation: modalFadeIn 0.22s cubic-bezier(0.16, 1, 0.3, 1) forwards;
    }

    /* Leaflet Tooltip for Stations */
    .leaflet-tooltip.amap-station-tooltip {
      background: rgba(255, 255, 255, 0.96);
      border: 1px solid rgba(226, 232, 240, 0.9);
      border-radius: 8px;
      padding: 3px 8px;
      font-size: 11px;
      font-weight: 700;
      color: #1e293b;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      white-space: nowrap;
    }
    .leaflet-tooltip.amap-border-tooltip {
      background: #ffffff;
      border: 2px solid #ef4444;
      border-radius: 10px;
      padding: 4px 10px;
      font-weight: 800;
      box-shadow: 0 6px 16px rgba(239, 68, 68, 0.25);
    }
    .leaflet-tooltip-top:before, .leaflet-tooltip-bottom:before {
      display: none;
    }

    /* Glassmorphism */
    .glass-panel {
      background: rgba(255, 255, 255, 0.94);
      backdrop-filter: blur(14px);
      -webkit-backdrop-filter: blur(14px);
    }
  </style>
</head>

<body class="h-screen w-screen overflow-hidden flex flex-col font-sans bg-slate-100 text-slate-800 antialiased select-none">
  <!-- Top Navigation Bar -->
  <header class="h-14 md:h-16 bg-white/95 border-b border-slate-200/90 px-3 md:px-6 flex items-center justify-between z-30 shadow-sm shrink-0">
    <div class="flex items-center space-x-3">
      <div class="w-9 h-9 md:w-10 md:h-10 rounded-xl bg-gradient-to-tr from-sky-600 via-blue-600 to-indigo-600 text-white flex items-center justify-center shadow-md shadow-blue-200">
        <i class="fa-solid fa-train-subway text-lg"></i>
      </div>
      <div>
        <div class="flex items-center space-x-2">
          <h1 class="font-extrabold text-base md:text-lg text-slate-900 tracking-tight leading-none">香港地铁全景图</h1>
          <span class="text-[11px] bg-blue-50 text-blue-700 font-bold px-2 py-0.5 rounded-full border border-blue-200/70 hidden sm:inline-block">
            高德/百度公交地铁模式
          </span>
        </div>
        <p class="text-[11px] text-slate-400 leading-none mt-1 font-medium">真实地理走廊校准 · 智能票价与港币换算系统</p>
      </div>
    </div>

    <!-- Quick Customs Crossing Button & Currency Settings -->
    <div class="flex items-center space-x-2">
      <!-- Live Exchange Rate Indicator & Editor -->
      <div class="hidden sm:flex items-center space-x-1.5 px-2.5 py-1 rounded-lg bg-amber-50/90 border border-amber-200/90 text-amber-900 text-xs shadow-xs" title="点击可微调当前汇率换算">
        <i class="fa-solid fa-coins text-amber-500 text-xs"></i>
        <span class="font-medium text-[11px]">汇率: 1 HKD ≈</span>
        <input 
          type="number" 
          id="cnyRateInput" 
          value="0.925" 
          step="0.005" 
          min="0.5" 
          max="1.5" 
          onchange="updateExchangeRate(this.value)"
          class="w-14 bg-white border border-amber-300 rounded px-1 text-center font-bold text-xs text-amber-900 focus:outline-none focus:ring-1 focus:ring-amber-500"
        />
        <span class="font-bold text-[11px]">CNY</span>
      </div>

      <!-- Unified Shenzhen-HK Customs Crossing Button -->
      <button 
        onclick="openBorderCrossingsModal()" 
        class="group relative flex items-center space-x-1.5 px-3 py-1.5 rounded-xl bg-gradient-to-r from-blue-600 via-indigo-600 to-blue-700 hover:from-blue-700 hover:to-indigo-800 text-white text-xs font-extrabold shadow-md shadow-blue-200 transition-all active:scale-95 border border-blue-400/40"
        title="点击查看所有可以通过海关往返深圳香港的口岸全景与接驳指引"
      >
        <span class="relative flex h-2 w-2">
          <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
          <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-400"></span>
        </span>
        <i class="fa-solid fa-passport text-amber-300 text-xs"></i>
        <span class="tracking-tight">深港地铁过关</span>
        <span class="hidden sm:inline text-[10px] bg-white/20 text-white px-1.5 py-0.5 rounded-full font-medium ml-0.5">口岸大全</span>
      </button>

      <!-- Map Theme Toggle -->
      <button id="mapStyleBtn" onclick="toggleMapStyle()" title="切换地图底图风格" class="w-8 h-8 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 flex items-center justify-center text-sm transition">
        <i class="fa-solid fa-moon"></i>
      </button>

      <!-- Mobile Sidebar Toggle -->
      <button onclick="toggleSidebar()" class="md:hidden w-8 h-8 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 flex items-center justify-center text-sm transition">
        <i class="fa-solid fa-bars"></i>
      </button>
    </div>
  </header>

  <div class="flex-1 relative flex overflow-hidden">
    <!-- Left Sidebar: Controls, Lines & Route Planner -->
    <aside id="mainSidebar" class="absolute md:relative inset-y-0 left-0 w-80 sm:w-96 glass-panel border-r border-slate-200/90 z-20 flex flex-col transform -translate-x-full md:translate-x-0 transition-transform duration-300 ease-in-out shadow-2xl md:shadow-none">
      
      <!-- Top Station Quick Search Bar -->
      <div class="p-3.5 border-b border-slate-100 bg-white/80">
        <div class="relative">
          <i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-sm"></i>
          <input 
            type="text" 
            id="stationSearchInput" 
            placeholder="搜索地铁站 (例: 罗湖 / 机场 / 中环 / 尖沙咀)..." 
            autocomplete="off"
            class="w-full pl-9 pr-8 py-2 bg-slate-100/90 focus:bg-white text-sm rounded-xl border border-slate-200/80 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 focus:outline-none transition placeholder-slate-400"
            oninput="handleSearch(this.value)"
          />
          <button id="clearSearchBtn" onclick="clearSearch()" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400 hover:text-slate-600 rounded-full flex items-center justify-center text-xs">
            <i class="fa-solid fa-xmark"></i>
          </button>
        </div>

        <!-- Search Suggestions Dropdown -->
        <div id="searchDropdown" class="hidden mt-1.5 max-h-60 overflow-y-auto bg-white rounded-xl shadow-xl border border-slate-100 divide-y divide-slate-50 text-sm z-30"></div>
      </div>

      <!-- Navigation Tabs: Route Planner & Fare / Lines Explorer / Border Crossing Info -->
      <div class="flex border-b border-slate-200 bg-slate-50/70 p-1.5 space-x-1 text-xs font-bold">
        <button onclick="switchTab('planner')" id="tabBtn-planner" class="flex-1 py-2 rounded-lg bg-white text-blue-600 shadow-sm border border-slate-200/60 flex items-center justify-center space-x-1.5 transition">
          <i class="fa-solid fa-calculator"></i>
          <span>乘车与票价</span>
        </button>
        <button onclick="switchTab('lines')" id="tabBtn-lines" class="flex-1 py-2 rounded-lg text-slate-600 hover:text-slate-900 flex items-center justify-center space-x-1.5 transition">
          <i class="fa-solid fa-route"></i>
          <span>所有线路</span>
        </button>
        <button onclick="switchTab('borders')" id="tabBtn-borders" class="flex-1 py-2 rounded-lg text-slate-600 hover:text-slate-900 flex items-center justify-center space-x-1.5 transition">
          <i class="fa-solid fa-passport"></i>
          <span>深港过关</span>
        </button>
      </div>

      <!-- Tab Content 1: Route Planner and Realistic Fare Engine -->
      <div id="tabContent-planner" class="flex-1 overflow-y-auto p-3.5 space-y-3.5">
        
        <!-- Planner Origin/Destination Selector -->
        <div class="bg-white p-3.5 rounded-2xl border border-slate-200/90 shadow-sm space-y-3">
          <div class="flex items-center justify-between text-xs">
            <span class="font-extrabold text-slate-800 flex items-center space-x-1.5">
              <i class="fa-solid fa-location-crosshairs text-blue-600"></i>
              <span>高德地铁乘车规划 & 票价计算</span>
            </span>
            <span class="text-[10px] bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded font-bold border border-emerald-200/60">
              港币 / 人民币双币显示
            </span>
          </div>
          
          <!-- Origin Station Input -->
          <div class="flex items-center space-x-2 bg-slate-50 p-2 rounded-xl border border-slate-200">
            <span class="w-3 h-3 rounded-full bg-emerald-500 shrink-0 flex items-center justify-center text-[8px] text-white font-bold">起</span>
            <div class="flex-1">
              <label class="block text-[10px] font-semibold text-slate-400 leading-tight">出发站 (Origin)</label>
              <select id="routeOrigin" onchange="calculateRouteAndFare()" class="w-full bg-transparent text-xs font-bold text-slate-800 focus:outline-none cursor-pointer">
                <option value="">请选择起点站...</option>
              </select>
            </div>
          </div>

          <!-- Swap Button -->
          <div class="flex justify-center -my-2 relative z-10">
            <button onclick="swapRouteStations()" title="互换起终点" class="w-7 h-7 bg-white hover:bg-slate-100 border border-slate-200 rounded-full text-slate-600 shadow-sm text-xs flex items-center justify-center transition active:rotate-180">
              <i class="fa-solid fa-arrow-down-up-across-line text-[11px]"></i>
            </button>
          </div>

          <!-- Destination Station Input -->
          <div class="flex items-center space-x-2 bg-slate-50 p-2 rounded-xl border border-slate-200">
            <span class="w-3 h-3 rounded-full bg-rose-500 shrink-0 flex items-center justify-center text-[8px] text-white font-bold">终</span>
            <div class="flex-1">
              <label class="block text-[10px] font-semibold text-slate-400 leading-tight">到达站 (Destination)</label>
              <select id="routeDestination" onchange="calculateRouteAndFare()" class="w-full bg-transparent text-xs font-bold text-slate-800 focus:outline-none cursor-pointer">
                <option value="">请选择到达站...</option>
              </select>
            </div>
          </div>
        </div>

        <!-- Dynamic Route & Fare Result Card -->
        <div id="routeResultBox" class="space-y-3"></div>

        <!-- Fare Policy & Special Line Notice -->
        <div class="bg-slate-50/80 p-3 rounded-xl border border-slate-200/70 text-[11px] text-slate-500 space-y-1">
          <div class="font-bold text-slate-700 flex items-center space-x-1">
            <i class="fa-solid fa-circle-info text-blue-500"></i>
            <span>计费规则与过境说明</span>
          </div>
          <p>• <strong>过境口岸</strong>:经罗湖或落马洲出入境包含特别跨境附加费,单程成人约 HK$40-52。</p>
          <p>• <strong>机场快线</strong>:实行独立高速专用线资费(香港/九龙往机场约 HK$100-115)。</p>
          <p>• <strong>换算汇率</strong>:根据输入汇率实时联动折算人民币(CNY),方便赴港旅客参考。</p>
        </div>
      </div>

      <!-- Tab Content 2: All Metro Lines Explorer -->
      <div id="tabContent-lines" class="hidden flex-1 overflow-y-auto p-3.5 space-y-2.5">
        <div class="flex items-center justify-between text-xs text-slate-500 font-semibold px-1">
          <span>点击线路可在地图上重点高亮</span>
          <button onclick="resetLineFilter()" class="text-blue-600 hover:underline">显示全网</button>
        </div>

        <div id="linesListContainer" class="space-y-2"></div>
      </div>

      <!-- Tab Content 3: Shenzhen-HK Border Crossing Info -->
      <div id="tabContent-borders" class="hidden flex-1 overflow-y-auto p-3.5 space-y-3">
        <!-- Lo Wu Card -->
        <div class="bg-gradient-to-br from-red-50 to-white p-3.5 rounded-2xl border-2 border-red-200 shadow-sm space-y-2.5">
          <div class="flex items-start justify-between">
            <div class="flex items-center space-x-2">
              <span class="px-2 py-0.5 bg-red-600 text-white rounded-md text-xs font-bold shadow-xs">罗湖口岸</span>
              <span class="text-xs text-slate-500 font-bold">东铁线直达</span>
            </div>
            <button onclick="focusBorderStation('lowu')" class="text-red-600 hover:text-red-700 text-xs font-bold flex items-center space-x-1">
              <span>在地图定位</span>
              <i class="fa-solid fa-chevron-right text-[10px]"></i>
            </button>
          </div>

          <div class="bg-white/90 p-2.5 rounded-xl border border-red-100 text-xs text-slate-700 space-y-1.5">
            <div class="font-bold text-slate-900 flex items-center space-x-1.5">
              <i class="fa-solid fa-retweet text-red-500"></i>
              <span>深圳地铁直连:<strong class="text-red-600">1号线 (罗宝线) 罗湖站</strong></span>
            </div>
            <p class="text-[11px] text-slate-600 leading-relaxed">
              港铁罗湖站下车出闸后,沿联检大楼步行过关。通关后直接步行进入<strong>深圳地铁1号线罗湖站</strong>,可直达老街(东门)、大剧院、岗厦、会展中心、车公庙、高新园及宝安机场客运码头。
            </p>
          </div>
          
          <div class="flex items-center justify-between text-[11px] text-slate-500 pt-1">
            <span><i class="fa-regular fa-clock mr-1 text-slate-400"></i>通关时间:06:30 - 24:00</span>
            <span class="text-red-700 font-bold">老牌口岸 / 客流集中</span>
          </div>
        </div>

        <!-- Lok Ma Chau Card -->
        <div class="bg-gradient-to-br from-emerald-50 to-white p-3.5 rounded-2xl border-2 border-emerald-200 shadow-sm space-y-2.5">
          <div class="flex items-start justify-between">
            <div class="flex items-center space-x-2">
              <span class="px-2 py-0.5 bg-emerald-600 text-white rounded-md text-xs font-bold shadow-xs">福田口岸 / 落马洲</span>
              <span class="text-xs text-slate-500 font-bold">东铁线支线</span>
            </div>
            <button onclick="focusBorderStation('lokmachau')" class="text-emerald-600 hover:text-emerald-700 text-xs font-bold flex items-center space-x-1">
              <span>在地图定位</span>
              <i class="fa-solid fa-chevron-right text-[10px]"></i>
            </button>
          </div>

          <div class="bg-white/90 p-2.5 rounded-xl border border-emerald-100 text-xs text-slate-700 space-y-1.5">
            <div class="font-bold text-slate-900 flex items-center space-x-1.5">
              <i class="fa-solid fa-retweet text-emerald-600"></i>
              <span>深圳地铁直连:<strong class="text-emerald-700">4号线 & 10号线 (福田口岸站)</strong></span>
            </div>
            <p class="text-[11px] text-slate-600 leading-relaxed">
              港铁落马洲站通过双层行人天桥横跨深圳河直通福田口岸联检大楼。完成出入境后,即达<strong>深圳地铁4号线与10号线</strong>。4号线直通深圳北站;10号线直达华为坂田基地与平湖。
            </p>
          </div>

          <div class="flex items-center justify-between text-[11px] text-slate-500 pt-1">
            <span><i class="fa-regular fa-clock mr-1 text-slate-400"></i>通关时间:06:30 - 22:30</span>
            <span class="text-emerald-700 font-bold">双线交汇 / 现代化设施</span>
          </div>
        </div>

        <!-- High Speed Rail / West Kowloon Note -->
        <div class="bg-white p-3.5 rounded-2xl border border-slate-200 text-xs text-slate-600 space-y-1.5">
          <div class="font-bold text-slate-800 flex items-center space-x-1.5">
            <i class="fa-solid fa-train text-blue-600"></i>
            <span>高铁香港西九龙站</span>
            <span class="text-[10px] bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded font-bold">一地两检</span>
          </div>
          <p class="text-[11px] text-slate-500 leading-relaxed">
            邻近<strong>柯士甸站(屯马线)</strong>及<strong>九龙站(东涌线/机场快线)</strong>,设有专用地下行人连系通道,支持一地两检高速直达全国各省市。
          </p>
        </div>
      </div>

      <!-- Sidebar Footer -->
      <div class="p-3 border-t border-slate-200 bg-white text-[11px] text-slate-500 flex items-center justify-between">
        <span class="font-medium">香港铁路有限公司 (MTR)</span>
        <span class="text-slate-400">标准成人八达通基准</span>
      </div>
    </aside>

    <!-- Center Map Canvas (GaoDe/Baidu Transit Style) -->
    <main class="flex-1 relative h-full">
      <div id="map"></div>

      <!-- Floating Map Legend & Tools (Top-Right) -->
      <div class="absolute top-3 right-3 z-20 flex flex-col items-end space-y-2 pointer-events-none">
        <div class="pointer-events-auto bg-white/95 backdrop-blur shadow-lg rounded-xl p-1.5 flex items-center space-x-1.5 border border-slate-200/90 text-xs font-bold">
          <button id="toggleLabelsBtn" onclick="toggleStationLabels()" class="px-2.5 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 font-semibold text-slate-700 transition flex items-center space-x-1">
            <i class="fa-solid fa-font text-slate-500 text-[11px]"></i>
            <span id="labelStatusText">隐藏站名</span>
          </button>
          <button onclick="resetMapView()" title="复位地图视角至全香港" class="w-8 h-8 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 flex items-center justify-center transition">
            <i class="fa-solid fa-compress text-xs"></i>
          </button>
        </div>

        <!-- Active Filtered Line Badge -->
        <div id="activeLineBanner" class="hidden pointer-events-auto bg-white/95 backdrop-blur px-3 py-1.5 rounded-xl shadow-lg border border-slate-200 flex items-center space-x-2 text-xs font-bold">
          <span id="activeLineDot" class="w-3.5 h-3.5 rounded-full ring-2 ring-white"></span>
          <span id="activeLineName" class="text-slate-900"></span>
          <button onclick="resetLineFilter()" title="取消筛选" class="text-slate-400 hover:text-slate-700 ml-1 text-sm">
            <i class="fa-solid fa-xmark"></i>
          </button>
        </div>
      </div>

      <!-- Shenzhen-Hong Kong Border Crossings Modal -->
      <div id="borderModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-5 bg-slate-900/60 backdrop-blur-sm">
        <div class="animate-modal-in bg-white w-full max-w-2xl max-h-[88vh] rounded-3xl shadow-2xl border border-slate-200 flex flex-col overflow-hidden">
          
          <!-- Modal Header -->
          <div class="px-5 py-4 bg-gradient-to-r from-blue-700 via-indigo-700 to-blue-800 text-white flex items-center justify-between shrink-0">
            <div class="flex items-center space-x-3">
              <div class="w-10 h-10 rounded-2xl bg-white/15 border border-white/20 flex items-center justify-center text-amber-300 text-lg shadow-inner">
                <i class="fa-solid fa-passport"></i>
              </div>
              <div>
                <div class="flex items-center space-x-2">
                  <h2 class="text-lg font-black tracking-tight">深港海关往返口岸全景大全</h2>
                  <span class="px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-400/90 text-slate-900">权威交通指引</span>
                </div>
                <p class="text-xs text-blue-100 font-medium mt-0.5">直连地铁 · 高铁一地两检 · 24小时通关 · 公交接驳全收录</p>
              </div>
            </div>
            <button onclick="closeBorderCrossingsModal()" class="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white text-sm transition">
              <i class="fa-solid fa-xmark"></i>
            </button>
          </div>

          <!-- Filter Pills -->
          <div class="px-5 py-2.5 bg-slate-50 border-b border-slate-200 flex items-center space-x-2 overflow-x-auto text-xs shrink-0">
            <span class="text-slate-400 font-bold shrink-0 text-[11px]">分类筛选:</span>
            <button onclick="filterBorderPorts('all')" id="portFilter-all" class="port-filter-btn active px-3 py-1 rounded-full font-bold bg-blue-600 text-white shadow-xs transition shrink-0">全部口岸 (8个)</button>
            <button onclick="filterBorderPorts('metro')" id="portFilter-metro" class="port-filter-btn px-3 py-1 rounded-full font-bold bg-white text-slate-600 hover:bg-slate-200 border border-slate-200 transition shrink-0">地铁直连 (双口岸)</button>
            <button onclick="filterBorderPorts('hsr')" id="portFilter-hsr" class="port-filter-btn px-3 py-1 rounded-full font-bold bg-white text-slate-600 hover:bg-slate-200 border border-slate-200 transition shrink-0">高铁一地两检</button>
            <button onclick="filterBorderPorts('24h')" id="portFilter-24h" class="port-filter-btn px-3 py-1 rounded-full font-bold bg-white text-slate-600 hover:bg-slate-200 border border-slate-200 transition shrink-0">24小时通关</button>
            <button onclick="filterBorderPorts('bus')" id="portFilter-bus" class="port-filter-btn px-3 py-1 rounded-full font-bold bg-white text-slate-600 hover:bg-slate-200 border border-slate-200 transition shrink-0">口岸公交接驳</button>
          </div>

          <!-- Port List Container -->
          <div id="borderPortsList" class="flex-1 overflow-y-auto p-4 sm:p-5 space-y-3.5 divide-y divide-slate-100"></div>

          <!-- Modal Footer Tips -->
          <div class="px-5 py-3 bg-slate-50 border-t border-slate-200 text-[11px] text-slate-500 flex flex-col sm:flex-row items-center justify-between gap-2 shrink-0">
            <div class="flex items-center space-x-1.5 text-slate-600">
              <i class="fa-solid fa-lightbulb text-amber-500"></i>
              <span>提示:内地居民持有效往来港澳通行证及签注即可正常通关;港铁及深圳地铁均支持扫码过闸。</span>
            </div>
            <button onclick="closeBorderCrossingsModal()" class="px-4 py-1.5 bg-slate-200 hover:bg-slate-300 text-slate-800 rounded-xl font-bold transition text-xs">
              关闭窗口
            </button>
          </div>
        </div>
      </div>

      <!-- Floating Selected Station Card (Bottom-Center) -->
      <div id="stationDetailCard" class="hidden absolute bottom-5 left-1/2 -translate-x-1/2 w-11/12 max-w-md bg-white/95 backdrop-blur-md rounded-2xl shadow-2xl border border-slate-200/90 z-20 overflow-hidden transition-all duration-300">
        <div id="stationCardHeaderBar" class="h-2 w-full bg-slate-300"></div>
        <div class="p-4 space-y-3">
          <div class="flex items-start justify-between">
            <div>
              <div class="flex items-center space-x-2">
                <h3 id="cardStationNameZh" class="text-xl font-extrabold text-slate-900 tracking-tight"></h3>
                <span id="cardStationNameEn" class="text-xs text-slate-400 font-medium"></span>
              </div>
              <p id="cardStationNameTc" class="text-xs text-slate-500 font-medium mt-0.5"></p>
            </div>
            <button onclick="closeStationCard()" class="text-slate-400 hover:text-slate-600 w-7 h-7 rounded-full flex items-center justify-center bg-slate-100 text-xs">
              <i class="fa-solid fa-xmark"></i>
            </button>
          </div>

          <!-- Lines list badge -->
          <div class="flex flex-wrap gap-1.5" id="cardLinesContainer"></div>

          <!-- Border connection special box if applicable -->
          <div id="cardBorderCallout" class="hidden rounded-xl p-3 border text-xs"></div>

          <!-- Fast Action Buttons -->
          <div class="pt-1 flex items-center space-x-2 text-xs font-bold">
            <button onclick="setAsRoutePoint('origin')" class="flex-1 py-2 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 border border-emerald-200 transition text-center flex items-center justify-center space-x-1.5">
              <span class="w-2 h-2 rounded-full bg-emerald-500"></span>
              <span>设为起点站</span>
            </button>
            <button onclick="setAsRoutePoint('destination')" class="flex-1 py-2 rounded-xl bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 transition text-center flex items-center justify-center space-x-1.5">
              <span class="w-2 h-2 rounded-full bg-rose-500"></span>
              <span>设为到达站</span>
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>

  <script>
    const STATIONS_DATA = {
      // === 东铁线 East Rail Line ===
      lowu: {
        id: 'lowu',
        nameZh: '罗湖',
        nameTc: '羅湖',
        nameEn: 'Lo Wu',
        lat: 22.5285,
        lng: 114.1130,
        lines: ['eastrail'],
        isBorder: true,
        borderTransfer: {
          name: '罗湖口岸 ⇄ 深圳地铁1号线 (罗宝线)',
          targetStation: '深圳地铁1号线 罗湖站',
          badgeText: '换乘深圳1号线(罗宝线)',
          badgeClass: 'bg-red-600 text-white',
          description: '从港铁罗湖站出闸后经罗湖口岸联检大楼完成两地边检查验,步行约2分钟即可进入深圳地铁1号线罗湖站。可直通老街商圈、会展中心、车公庙、高新园、宝安机场码头。'
        }
      },
      lokmachau: {
        id: 'lokmachau',
        nameZh: '落马洲',
        nameTc: '落馬洲',
        nameEn: 'Lok Ma Chau',
        lat: 22.5152,
        lng: 114.0662,
        lines: ['eastrail'],
        isBorder: true,
        borderTransfer: {
          name: '福田口岸 ⇄ 深圳地铁4号线 / 10号线',
          targetStation: '深圳地铁4/10号线 福田口岸站',
          badgeText: '换乘深圳4/10号线(福田口岸)',
          badgeClass: 'bg-emerald-600 text-white',
          description: '从落马洲出闸后直接跨过双层深港行人天桥进入福田口岸大楼,过关后即进入深圳地铁4号线(直通市民中心、深圳北站)及10号线(直通华为坂田基地、平湖)。'
        }
      },
      sheungshui: { id: 'sheungshui', nameZh: '上水', nameTc: '上水', nameEn: 'Sheung Shui', lat: 22.5013, lng: 114.1278, lines: ['eastrail'] },
      fanling: { id: 'fanling', nameZh: '粉岭', nameTc: '粉嶺', nameEn: 'Fanling', lat: 22.4920, lng: 114.1387, lines: ['eastrail'] },
      taiwo: { id: 'taiwo', nameZh: '太和', nameTc: '太和', nameEn: 'Tai Wo', lat: 22.4508, lng: 114.1610, lines: ['eastrail'] },
      taipomarket: { id: 'taipomarket', nameZh: '大埔墟', nameTc: '大埔墟', nameEn: 'Tai Po Market', lat: 22.4447, lng: 114.1702, lines: ['eastrail'] },
      university: { id: 'university', nameZh: '大学', nameTc: '大學', nameEn: 'University', lat: 22.4131, lng: 114.2104, lines: ['eastrail'] },
      fotan: { id: 'fotan', nameZh: '火炭', nameTc: '火炭', nameEn: 'Fo Tan', lat: 22.3949, lng: 114.1953, lines: ['eastrail'] },
      shatin: { id: 'shatin', nameZh: '沙田', nameTc: '沙田', nameEn: 'Sha Tin', lat: 22.3833, lng: 114.1883, lines: ['eastrail'] },
      taiwai: { id: 'taiwai', nameZh: '大围', nameTc: '大圍', nameEn: 'Tai Wai', lat: 22.3728, lng: 114.1788, lines: ['eastrail', 'tuenma'] },
      kowloontong: { id: 'kowloontong', nameZh: '九龙塘', nameTc: '九龍塘', nameEn: 'Kowloon Tong', lat: 22.3371, lng: 114.1764, lines: ['eastrail', 'kwuntong'] },
      mongkokeast: { id: 'mongkokeast', nameZh: '旺角东', nameTc: '旺角東', nameEn: 'Mong Kok East', lat: 22.3225, lng: 114.1726, lines: ['eastrail'] },
      hunghom: { id: 'hunghom', nameZh: '红磡', nameTc: '紅磡', nameEn: 'Hung Hom', lat: 22.3029, lng: 114.1813, lines: ['eastrail', 'tuenma'] },
      exhibition: { id: 'exhibition', nameZh: '会展', nameTc: '會展', nameEn: 'Exhibition Centre', lat: 22.2828, lng: 114.1755, lines: ['eastrail'] },
      admiralty: { id: 'admiralty', nameZh: '金钟', nameTc: '金鐘', nameEn: 'Admiralty', lat: 22.2783, lng: 114.1651, lines: ['eastrail', 'tsuenwan', 'island', 'southisland'] },

      // === 机场快线 Airport Express & 东涌线 Tung Chung Line ===
      hongkong: { id: 'hongkong', nameZh: '香港', nameTc: '香港', nameEn: 'Hong Kong', lat: 22.2845, lng: 114.1584, lines: ['tungchung', 'airport', 'island', 'tsuenwan'] },
      kowloon: { id: 'kowloon', nameZh: '九龙', nameTc: '九龍', nameEn: 'Kowloon', lat: 22.3049, lng: 114.1615, lines: ['tungchung', 'airport'] },
      olympic: { id: 'olympic', nameZh: '奥运', nameTc: '奧運', nameEn: 'Olympic', lat: 22.3175, lng: 114.1601, lines: ['tungchung'] },
      namcheong: { id: 'namcheong', nameZh: '南昌', nameTc: '南昌', nameEn: 'Nam Cheong', lat: 22.3270, lng: 114.1541, lines: ['tungchung', 'tuenma'] },
      laiking: { id: 'laiking', nameZh: '荔景', nameTc: '荔景', nameEn: 'Lai King', lat: 22.3486, lng: 114.1264, lines: ['tsuenwan', 'tungchung'] },
      tsingyi: { id: 'tsingyi', nameZh: '青衣', nameTc: '青衣', nameEn: 'Tsing Yi', lat: 22.3582, lng: 114.1070, lines: ['tungchung', 'airport'] },
      sunnybay: { id: 'sunnybay', nameZh: '欣澳', nameTc: '欣澳', nameEn: 'Sunny Bay', lat: 22.3312, lng: 114.0286, lines: ['tungchung', 'disney'] },
      tungchung: { id: 'tungchung', nameZh: '东涌', nameTc: '東涌', nameEn: 'Tung Chung', lat: 22.2891, lng: 113.9412, lines: ['tungchung'] },
      airport: { id: 'airport', nameZh: '机场', nameTc: '機場', nameEn: 'Airport', lat: 22.3155, lng: 113.9360, lines: ['airport'], isAirport: true },
      asiaworldexpo: { id: 'asiaworldexpo', nameZh: '博览馆', nameTc: '博覽館', nameEn: 'AsiaWorld-Expo', lat: 22.3207, lng: 113.9405, lines: ['airport'] },

      // === 荃湾线 Tsuen Wan Line ===
      central: { id: 'central', nameZh: '中环', nameTc: '中環', nameEn: 'Central', lat: 22.2819, lng: 114.1582, lines: ['tsuenwan', 'island', 'tungchung', 'airport'] },
      tsimshatsui: { id: 'tsimshatsui', nameZh: '尖沙咀', nameTc: '尖沙咀', nameEn: 'Tsim Sha Tsui', lat: 22.2976, lng: 114.1722, lines: ['tsuenwan', 'tuenma'] },
      jordan: { id: 'jordan', nameZh: '佐敦', nameTc: '佐敦', nameEn: 'Jordan', lat: 22.3049, lng: 114.1717, lines: ['tsuenwan'] },
      yaumatei: { id: 'yaumatei', nameZh: '油麻地', nameTc: '油麻地', nameEn: 'Yau Ma Tei', lat: 22.3129, lng: 114.1708, lines: ['tsuenwan', 'kwuntong'] },
      mongkok: { id: 'mongkok', nameZh: '旺角', nameTc: '旺角', nameEn: 'Mong Kok', lat: 22.3193, lng: 114.1694, lines: ['tsuenwan', 'kwuntong'] },
      princeedward: { id: 'princeedward', nameZh: '太子', nameTc: '太子', nameEn: 'Prince Edward', lat: 22.3246, lng: 114.1683, lines: ['tsuenwan', 'kwuntong'] },
      shamshuipo: { id: 'shamshuipo', nameZh: '深水埗', nameTc: '深水埗', nameEn: 'Sham Shui Po', lat: 22.3308, lng: 114.1622, lines: ['tsuenwan'] },
      cheungshawan: { id: 'cheungshawan', nameZh: '长沙湾', nameTc: '長沙灣', nameEn: 'Cheung Sha Wan', lat: 22.3356, lng: 114.1565, lines: ['tsuenwan'] },
      laichikok: { id: 'laichikok', nameZh: '荔枝角', nameTc: '荔枝角', nameEn: 'Lai Chi Kok', lat: 22.3375, lng: 114.1488, lines: ['tsuenwan'] },
      meifoo: { id: 'meifoo', nameZh: '美孚', nameTc: '美孚', nameEn: 'Mei Foo', lat: 22.3370, lng: 114.1408, lines: ['tsuenwan', 'tuenma'] },
      kwaifong: { id: 'kwaifong', nameZh: '葵芳', nameTc: '葵芳', nameEn: 'Kwai Fong', lat: 22.3568, lng: 114.1281, lines: ['tsuenwan'] },
      kwaihing: { id: 'kwaihing', nameZh: '葵兴', nameTc: '葵興', nameEn: 'Kwai Hing', lat: 22.3631, lng: 114.1311, lines: ['tsuenwan'] },
      taiwohau: { id: 'taiwohau', nameZh: '大窝口', nameTc: '大窩口', nameEn: 'Tai Wo Hau', lat: 22.3703, lng: 114.1251, lines: ['tsuenwan'] },
      tsuenwan: { id: 'tsuenwan', nameZh: '荃湾', nameTc: '荃灣', nameEn: 'Tsuen Wan', lat: 22.3737, lng: 114.1178, lines: ['tsuenwan'] },

      // === 港岛线 Island Line ===
      kennedytown: { id: 'kennedytown', nameZh: '坚尼地城', nameTc: '堅尼地城', nameEn: 'Kennedy Town', lat: 22.2813, lng: 114.1288, lines: ['island'] },
      hku: { id: 'hku', nameZh: '香港大学', nameTc: '香港大學', nameEn: 'HKU', lat: 22.2842, lng: 114.1352, lines: ['island'] },
      saiyingpun: { id: 'saiyingpun', nameZh: '西营盘', nameTc: '西營盤', nameEn: 'Sai Ying Pun', lat: 22.2863, lng: 114.1432, lines: ['island'] },
      sheungwan: { id: 'sheungwan', nameZh: '上环', nameTc: '上環', nameEn: 'Sheung Wan', lat: 22.2868, lng: 114.1522, lines: ['island'] },
      wanchai: { id: 'wanchai', nameZh: '湾仔', nameTc: '灣仔', nameEn: 'Wan Chai', lat: 22.2778, lng: 114.1731, lines: ['island'] },
      causewaybay: { id: 'causewaybay', nameZh: '铜锣湾', nameTc: '銅鑼灣', nameEn: 'Causeway Bay', lat: 22.2801, lng: 114.1852, lines: ['island'] },
      tinhau: { id: 'tinhau', nameZh: '天后', nameTc: '天后', nameEn: 'Tin Hau', lat: 22.2825, lng: 114.1923, lines: ['island'] },
      fortresshill: { id: 'fortresshill', nameZh: '炮台山', nameTc: '炮台山', nameEn: 'Fortress Hill', lat: 22.2884, lng: 114.1939, lines: ['island'] },
      northpoint: { id: 'northpoint', nameZh: '北角', nameTc: '北角', nameEn: 'North Point', lat: 22.2913, lng: 114.1998, lines: ['island', 'tseungkwano'] },
      quarrybay: { id: 'quarrybay', nameZh: '鲗鱼涌', nameTc: '鰂魚涌', nameEn: 'Quarry Bay', lat: 22.2882, lng: 114.2099, lines: ['island', 'tseungkwano'] },
      taikoo: { id: 'taikoo', nameZh: '太古', nameTc: '太古', nameEn: 'Tai Koo', lat: 22.2843, lng: 114.2166, lines: ['island'] },
      saiwanho: { id: 'saiwanho', nameZh: '西湾河', nameTc: '西灣河', nameEn: 'Sai Wan Ho', lat: 22.2822, lng: 114.2221, lines: ['island'] },
      shaukeiwan: { id: 'shaukeiwan', nameZh: '筲箕湾', nameTc: '筲箕灣', nameEn: 'Shau Kei Wan', lat: 22.2796, lng: 114.2285, lines: ['island'] },
      hengfachuen: { id: 'hengfachuen', nameZh: '杏花邨', nameTc: '杏花邨', nameEn: 'Heng Fa Chuen', lat: 22.2767, lng: 114.2399, lines: ['island'] },
      chaiwan: { id: 'chaiwan', nameZh: '柴湾', nameTc: '柴灣', nameEn: 'Chai Wan', lat: 22.2642, lng: 114.2366, lines: ['island'] },

      // === 观塘线 Kwun Tong Line ===
      whampoa: { id: 'whampoa', nameZh: '黄埔', nameTc: '黃埔', nameEn: 'Whampoa', lat: 22.3049, lng: 114.1887, lines: ['kwuntong'] },
      'homan tin': { id: 'homan tin', nameZh: '何文田', nameTc: '何文田', nameEn: 'Ho Man Tin', lat: 22.3093, lng: 114.1827, lines: ['kwuntong', 'tuenma'] },
      shekkipmei: { id: 'shekkipmei', nameZh: '石硖尾', nameTc: '石硤尾', nameEn: 'Shek Kip Mei', lat: 22.3323, lng: 114.1688, lines: ['kwuntong'] },
      lokfu: { id: 'lokfu', nameZh: '乐富', nameTc: '樂富', nameEn: 'Lok Fu', lat: 22.3386, lng: 114.1873, lines: ['kwuntong'] },
      wongtaisin: { id: 'wongtaisin', nameZh: '黄大仙', nameTc: '黃大仙', nameEn: 'Wong Tai Sin', lat: 22.3418, lng: 114.1934, lines: ['kwuntong'] },
      diamondhill: { id: 'diamondhill', nameZh: '钻石山', nameTc: '鑽石山', nameEn: 'Diamond Hill', lat: 22.3402, lng: 114.2016, lines: ['kwuntong', 'tuenma'] },
      choihung: { id: 'choihung', nameZh: '彩虹', nameTc: '彩虹', nameEn: 'Choi Hung', lat: 22.3347, lng: 114.2089, lines: ['kwuntong'] },
      kowloonbay: { id: 'kowloonbay', nameZh: '九龙湾', nameTc: '九龍灣', nameEn: 'Kowloon Bay', lat: 22.3235, lng: 114.2141, lines: ['kwuntong'] },
      ngautaukok: { id: 'ngautaukok', nameZh: '牛头角', nameTc: '牛頭角', nameEn: 'Ngau Tau Kok', lat: 22.3155, lng: 114.2191, lines: ['kwuntong'] },
      kwuntong: { id: 'kwuntong', nameZh: '观塘', nameTc: '觀塘', nameEn: 'Kwun Tong', lat: 22.3124, lng: 114.2255, lines: ['kwuntong'] },
      lamtin: { id: 'lamtin', nameZh: '蓝田', nameTc: '藍田', nameEn: 'Lam Tin', lat: 22.3068, lng: 114.2327, lines: ['kwuntong'] },
      yautong: { id: 'yautong', nameZh: '油塘', nameTc: '油塘', nameEn: 'Yau Tong', lat: 22.2978, lng: 114.2372, lines: ['kwuntong', 'tseungkwano'] },
      tiukengleng: { id: 'tiukengleng', nameZh: '调景岭', nameTc: '調景嶺', nameEn: 'Tiu Keng Leng', lat: 22.3045, lng: 114.2525, lines: ['kwuntong', 'tseungkwano'] },

      // === 屯马线 Tuen Ma Line ===
      tuenmun: { id: 'tuenmun', nameZh: '屯门', nameTc: '屯門', nameEn: 'Tuen Mun', lat: 22.3952, lng: 113.9734, lines: ['tuenma'] },
      siuhong: { id: 'siuhong', nameZh: '兆康', nameTc: '兆康', nameEn: 'Siu Hong', lat: 22.4116, lng: 113.9781, lines: ['tuenma'] },
      tinshuiwai: { id: 'tinshuiwai', nameZh: '天水围', nameTc: '天水圍', nameEn: 'Tin Shui Wai', lat: 22.4491, lng: 114.0048, lines: ['tuenma'] },
      longping: { id: 'longping', nameZh: '朗屏', nameTc: '朗屏', nameEn: 'Long Ping', lat: 22.4478, lng: 114.0248, lines: ['tuenma'] },
      yuenlong: { id: 'yuenlong', nameZh: '元朗', nameTc: '元朗', nameEn: 'Yuen Long', lat: 22.4452, lng: 114.0354, lines: ['tuenma'] },
      kamsheungroad: { id: 'kamsheungroad', nameZh: '锦上路', nameTc: '錦上路', nameEn: 'Kam Sheung Road', lat: 22.4347, lng: 114.0628, lines: ['tuenma'] },
      tsuenwanwest: { id: 'tsuenwanwest', nameZh: '荃湾西', nameTc: '荃灣西', nameEn: 'Tsuen Wan West', lat: 22.3688, lng: 114.1107, lines: ['tuenma'] },
      austin: { id: 'austin', nameZh: '柯士甸', nameTc: '柯士甸', nameEn: 'Austin', lat: 22.3041, lng: 114.1666, lines: ['tuenma'], isHsr: true },
      easttsimshatsui: { id: 'easttsimshatsui', nameZh: '尖东', nameTc: '尖東', nameEn: 'East Tsim Sha Tsui', lat: 22.2952, lng: 114.1741, lines: ['tuenma', 'tsuenwan'] },
      tokwawan: { id: 'tokwawan', nameZh: '土瓜湾', nameTc: '土瓜灣', nameEn: 'To Kwa Wan', lat: 22.3179, lng: 114.1895, lines: ['tuenma'] },
      sungwongtoi: { id: 'sungwongtoi', nameZh: '宋皇台', nameTc: '宋皇臺', nameEn: 'Sung Wong Toi', lat: 22.3275, lng: 114.1898, lines: ['tuenma'] },
      kaitak: { id: 'kaitak', nameZh: '启德', nameTc: '啟德', nameEn: 'Kai Tak', lat: 22.3312, lng: 114.1983, lines: ['tuenma'] },
      hinkeng: { id: 'hinkeng', nameZh: '显径', nameTc: '顯徑', nameEn: 'Hin Keng', lat: 22.3644, lng: 114.1722, lines: ['tuenma'] },
      chekungtemple: { id: 'chekungtemple', nameZh: '车公庙', nameTc: '車公廟', nameEn: 'Che Kung Temple', lat: 22.3756, lng: 114.1864, lines: ['tuenma'] },
      shatinwai: { id: 'shatinwai', nameZh: '沙田围', nameTc: '沙田圍', nameEn: 'Sha Tin Wai', lat: 22.3776, lng: 114.1953, lines: ['tuenma'] },
      cityone: { id: 'cityone', nameZh: '第一城', nameTc: '第一城', nameEn: 'City One', lat: 22.3857, lng: 114.2038, lines: ['tuenma'] },
      shekmun: { id: 'shekmun', nameZh: '石门', nameTc: '石門', nameEn: 'Shek Mun', lat: 22.3879, lng: 114.2088, lines: ['tuenma'] },
      taishuihang: { id: 'taishuihang', nameZh: '大水坑', nameTc: '大水坑', nameEn: 'Tai Shui Hang', lat: 22.4089, lng: 114.2215, lines: ['tuenma'] },
      hengon: { id: 'hengon', nameZh: '恒安', nameTc: '恆安', nameEn: 'Heng On', lat: 22.4182, lng: 114.2285, lines: ['tuenma'] },
      maonshan: { id: 'maonshan', nameZh: '马鞍山', nameTc: '馬鞍山', nameEn: 'Ma On Shan', lat: 22.4245, lng: 114.2323, lines: ['tuenma'] },
      wukaisha: { id: 'wukaisha', nameZh: '乌溪沙', nameTc: '烏溪沙', nameEn: 'Wu Kai Sha', lat: 22.4332, lng: 114.2404, lines: ['tuenma'] },

      // === 将军澳线 Tseung Kwan O Line ===
      tseungkwano: { id: 'tseungkwano', nameZh: '将军澳', nameTc: '將軍澳', nameEn: 'Tseung Kwan O', lat: 22.3075, lng: 114.2600, lines: ['tseungkwano'] },
      hanghau: { id: 'hanghau', nameZh: '坑口', nameTc: '坑口', nameEn: 'Hang Hau', lat: 22.3156, lng: 114.2642, lines: ['tseungkwano'] },
      polam: { id: 'polam', nameZh: '宝琳', nameTc: '寶琳', nameEn: 'Po Lam', lat: 22.3225, lng: 114.2581, lines: ['tseungkwano'] },
      lohaspark: { id: 'lohaspark', nameZh: '康城', nameTc: '康城', nameEn: 'LOHAS Park', lat: 22.2960, lng: 114.2705, lines: ['tseungkwano'] },

      // === 南港岛线 South Island Line ===
      oceanpark: { id: 'oceanpark', nameZh: '海洋公园', nameTc: '海洋公園', nameEn: 'Ocean Park', lat: 22.2478, lng: 114.1712, lines: ['southisland'] },
      wongchukhang: { id: 'wongchukhang', nameZh: '黄竹坑', nameTc: '黃竹坑', nameEn: 'Wong Chuk Hang', lat: 22.2476, lng: 114.1678, lines: ['southisland'] },
      leitung: { id: 'leitung', nameZh: '利东', nameTc: '利東', nameEn: 'Lei Tung', lat: 22.2422, lng: 114.1561, lines: ['southisland'] },
      southhorizons: { id: 'southhorizons', nameZh: '海怡半岛', nameTc: '海怡半島', nameEn: 'South Horizons', lat: 22.2435, lng: 114.1488, lines: ['southisland'] },

      // === 迪士尼线 Disneyland Resort Line ===
      disneyland: { id: 'disneyland', nameZh: '迪士尼', nameTc: '迪士尼', nameEn: 'Disneyland Resort', lat: 22.3155, lng: 114.0450, lines: ['disney'], isDisney: true }
    };

    const MTR_LINES = [
      {
        id: 'airport',
        nameZh: '机场快线',
        nameEn: 'Airport Express',
        color: '#008779',
        textColor: '#ffffff',
        description: '专用机场高速铁路线,往返中环、九龙、青衣、香港国际机场及博览馆',
        stations: ['hongkong', 'kowloon', 'tsingyi', 'airport', 'asiaworldexpo'],
        customPolyline: [
          [22.2845, 114.1584], // 香港站
          [22.2960, 114.1540], // 西区沉管海底铁路隧道
          [22.3049, 114.1615], // 九龙站
          [22.3175, 114.1590], // 西九龙走廊
          [22.3360, 114.1350], // 荔枝角湾高架
          [22.3550, 114.1180], // 青衣北铁路桥
          [22.3582, 114.1070], // 青衣站
          [22.3560, 114.0920], // 青衣西侧下坡
          [22.3525, 114.0720], // 青马大桥主跨
          [22.3495, 114.0610], // 马湾高架路段
          [22.3480, 114.0505], // 汲水门大桥
          [22.3350, 114.0320], // 阴澳海湾走廊
          [22.3120, 113.9850], // 北大屿山走廊
          [22.2980, 113.9520], // 机场南桥
          [22.3060, 113.9420], // 机场岛南进站线
          [22.3155, 113.9360], // 机场站
          [22.3207, 113.9405]  // 博览馆站
        ]
      },
      {
        id: 'tungchung',
        nameZh: '东涌线',
        nameEn: 'Tung Chung Line',
        color: '#F38B00',
        textColor: '#ffffff',
        description: '连接香港岛核心至西九龙、青衣及大屿山北部东涌新市镇',
        stations: ['hongkong', 'kowloon', 'olympic', 'namcheong', 'laiking', 'tsingyi', 'sunnybay', 'tungchung'],
        customPolyline: [
          [22.2845, 114.1584], // 香港站
          [22.2960, 114.1540], // 西区海底铁路隧道
          [22.3049, 114.1615], // 九龙站
          [22.3175, 114.1601], // 奥运站
          [22.3270, 114.1541], // 南昌站
          [22.3486, 114.1264], // 荔景站
          [22.3550, 114.1180], // 青衣桥
          [22.3582, 114.1070], // 青衣站
          [22.3525, 114.0720], // 青马大桥
          [22.3495, 114.0610], // 马湾
          [22.3480, 114.0505], // 汲水门大桥
          [22.3312, 114.0286], // 欣澳站
          [22.3120, 113.9850], // 北大屿山走廊
          [22.2891, 113.9412]  // 东涌站
        ]
      },
      {
        id: 'disney',
        nameZh: '迪士尼线',
        nameEn: 'Disneyland Resort Line',
        color: '#F173AC',
        textColor: '#ffffff',
        description: '连接欣澳站与香港迪士尼乐园度假区的特色主题铁路',
        stations: ['sunnybay', 'disneyland'],
        customPolyline: [
          [22.3312, 114.0286],
          [22.3240, 114.0380],
          [22.3155, 114.0450]
        ]
      },
      {
        id: 'eastrail',
        nameZh: '东铁线',
        nameEn: 'East Rail Line',
        color: '#53B7E8',
        textColor: '#000000',
        description: '贯通港岛、九龙及新界东,直通罗湖与落马洲双口岸',
        stations: ['admiralty', 'exhibition', 'hunghom', 'mongkokeast', 'kowloontong', 'taiwai', 'shatin', 'fotan', 'university', 'taipomarket', 'taiwo', 'fanling', 'sheungshui', 'lowu'],
        customPolyline: [
          [22.2783, 114.1651], // 金钟
          [22.2828, 114.1755], // 会展
          [22.2930, 114.1820], // 东铁过海沉管铁路隧道
          [22.3029, 114.1813], // 红磡
          [22.3225, 114.1726], // 旺角东
          [22.3371, 114.1764], // 九龙塘
          [22.3550, 114.1780], // 笔架山隧道
          [22.3728, 114.1788], // 大围
          [22.3833, 114.1883], // 沙田
          [22.3949, 114.1953], // 火炭
          [22.4131, 114.2104], // 大学
          [22.4447, 114.1702], // 大埔墟
          [22.4508, 114.1610], // 太和
          [22.4920, 114.1387], // 粉岭
          [22.5013, 114.1278], // 上水
          [22.5285, 114.1130]  // 罗湖站
        ],
        branch: {
          forkAt: 'sheungshui',
          stations: ['sheungshui', 'lokmachau'],
          customPolyline: [
            [22.5013, 114.1278],
            [22.5090, 114.0950],
            [22.5152, 114.0662]
          ]
        }
      },
      {
        id: 'tsuenwan',
        nameZh: '荃湾线',
        nameEn: 'Tsuen Wan Line',
        color: '#E60012',
        textColor: '#ffffff',
        description: '贯通香港岛中西区至九龙半岛核心弥敦道及新界西南荃湾',
        stations: ['central', 'admiralty', 'tsimshatsui', 'jordan', 'yaumatei', 'mongkok', 'princeedward', 'shamshuipo', 'cheungshawan', 'laichikok', 'meifoo', 'laiking', 'kwaifong', 'kwaihing', 'taiwohau', 'tsuenwan'],
        customPolyline: [
          [22.2819, 114.1582], // 中环
          [22.2783, 114.1651], // 金钟
          [22.2890, 114.1690], // 荃湾线维港海底隧道
          [22.2976, 114.1722], // 尖沙咀
          [22.3049, 114.1717], // 佐敦
          [22.3129, 114.1708], // 油麻地
          [22.3193, 114.1694], // 旺角
          [22.3246, 114.1683], // 太子
          [22.3308, 114.1622], // 深水埗
          [22.3356, 114.1565], // 长沙湾
          [22.3375, 114.1488], // 荔枝角
          [22.3370, 114.1408], // 美孚
          [22.3486, 114.1264], // 荔景
          [22.3568, 114.1281], // 葵芳
          [22.3631, 114.1311], // 葵兴
          [22.3703, 114.1251], // 大窝口
          [22.3737, 114.1178]  // 荃湾
        ]
      },
      {
        id: 'island',
        nameZh: '港岛线',
        nameEn: 'Island Line',
        color: '#0071CE',
        textColor: '#ffffff',
        description: '沿港岛北岸从坚尼地城延伸至柴湾,连接各主要商业金融枢纽',
        stations: ['kennedytown', 'hku', 'saiyingpun', 'sheungwan', 'central', 'admiralty', 'wanchai', 'causewaybay', 'tinhau', 'fortresshill', 'northpoint', 'quarrybay', 'taikoo', 'saiwanho', 'shaukeiwan', 'hengfachuen', 'chaiwan']
      },
      {
        id: 'kwuntong',
        nameZh: '观塘线',
        nameEn: 'Kwun Tong Line',
        color: '#00AB4E',
        textColor: '#ffffff',
        description: '横跨九龙东西部,连接黄埔、油尖旺、东九龙核心与调景岭',
        stations: ['whampoa', 'homan tin', 'yaumatei', 'mongkok', 'princeedward', 'shekkipmei', 'kowloontong', 'lokfu', 'wongtaisin', 'diamondhill', 'choihung', 'kowloonbay', 'ngautaukok', 'kwuntong', 'lamtin', 'yautong', 'tiukengleng']
      },
      {
        id: 'tuenma',
        nameZh: '屯马线',
        nameEn: 'Tuen Ma Line',
        color: '#923011',
        textColor: '#ffffff',
        description: '香港最长全封闭重铁,贯通新界东西并横跨九龙市区核心',
        stations: ['tuenmun', 'siuhong', 'tinshuiwai', 'longping', 'yuenlong', 'kamsheungroad', 'tsuenwanwest', 'meifoo', 'namcheong', 'austin', 'easttsimshatsui', 'hunghom', 'homan tin', 'tokwawan', 'sungwongtoi', 'kaitak', 'diamondhill', 'hinkeng', 'taiwai', 'chekungtemple', 'shatinwai', 'cityone', 'shekmun', 'taishuihang', 'hengon', 'maonshan', 'wukaisha']
      },
      {
        id: 'tseungkwano',
        nameZh: '将军澳线',
        nameEn: 'Tseung Kwan O Line',
        color: '#A35EB5',
        textColor: '#ffffff',
        description: '连接港岛东鲗鱼涌、北角与将军澳新市镇、日出康城',
        stations: ['northpoint', 'quarrybay', 'yautong', 'tiukengleng', 'tseungkwano', 'hanghau', 'polam'],
        branch: {
          forkAt: 'tseungkwano',
          stations: ['tseungkwano', 'lohaspark']
        }
      },
      {
        id: 'southisland',
        nameZh: '南港岛线',
        nameEn: 'South Island Line',
        color: '#B6BD00',
        textColor: '#ffffff',
        description: '由金钟直通海洋公园、黄竹坑及海怡半岛',
        stations: ['admiralty', 'oceanpark', 'wongchukhang', 'leitung', 'southhorizons']
      }
    ];

    const BORDER_PORTS_DATA = [
      {
        id: 'lowu',
        name: '罗湖口岸',
        type: 'metro',
        typeLabel: '地铁直连 · 老牌大口岸',
        badgeColor: 'bg-red-600 text-white',
        borderType: '传统两地两检',
        hours: '06:30 - 24:00',
        hkTransit: '港铁东铁线 (罗湖站,下车出闸即达联检大楼)',
        szTransit: '深圳地铁 1号线 (罗宝线) 罗湖站、深圳火车站 (广深城际)',
        linkedMtrStationId: 'lowu',
        desc: '香港与深圳客流量最大、资历最久的铁路口岸。港铁罗湖站出站即办出境,过罗湖桥即抵深圳地铁1号线罗湖站,直通老街商圈、大剧院、会展中心、车公庙与高新园。'
      },
      {
        id: 'lokmachau',
        name: '福田口岸 / 落马洲支线',
        type: 'metro',
        typeLabel: '双地铁直达 · 跨河天桥',
        badgeColor: 'bg-emerald-600 text-white',
        borderType: '传统两地两检',
        hours: '06:30 - 22:30',
        hkTransit: '港铁东铁线 (落马洲站,直通双层深港行人天桥)',
        szTransit: '深圳地铁 4号线 & 10号线 (福田口岸站直通站厅)',
        linkedMtrStationId: 'lokmachau',
        desc: '港铁落马洲站与福田口岸联检楼通过现代化双层全封闭玻璃行人天桥横跨深圳河。深圳端有4号线直达市民中心与深圳北站高铁枢纽;10号线直通华为坂田基地与平湖。'
      },
      {
        id: 'westkowloon',
        name: '广深港高铁西九龙站口岸',
        type: 'hsr',
        typeLabel: '高铁核心枢纽 · 极致快捷',
        badgeColor: 'bg-blue-600 text-white',
        borderType: '一地两检 (站内同时办结深港出入境)',
        hours: '06:30 - 23:30',
        hkTransit: '港铁屯马线 (柯士甸站地下专用通道) / 港铁东涌线·机场快线 (九龙站连廊)',
        szTransit: '广深港高速铁路:直达 深圳福田站 (14分钟)、深圳北站 (18分钟)',
        linkedMtrStationId: 'austin',
        desc: '国家级一地两检典范口岸。在香港西九龙站内同时办理香港出境与内地入境,乘坐高铁14分钟直达深圳福田CBD,18分钟到深圳北站。'
      },
      {
        id: 'huanggang',
        name: '皇岗口岸',
        type: '24h',
        typeLabel: '深港唯一24小时通关口岸',
        badgeColor: 'bg-purple-600 text-white',
        borderType: '两地两检 (跨境穿梭巴士接驳)',
        hours: '00:00 - 24:00 (全天候通关)',
        hkTransit: '全港多区“跨境全日通”专线巴士 (旺角/佐敦/湾仔/荃湾/锦上路直达)',
        szTransit: '深圳地铁 7号线 (皇岗口岸站)',
        linkedMtrStationId: 'kamsheungroad',
        desc: '深港两地唯一的全天候24小时通关陆路口岸。深夜港铁停运后往返深港的首选通道。'
      },
      {
        id: 'shenzhenbay',
        name: '深圳湾口岸',
        type: 'bus',
        typeLabel: '一地两检 · 科技园区首选',
        badgeColor: 'bg-cyan-600 text-white',
        borderType: '一地两检 (在深圳侧大楼一次完成两地出入境)',
        hours: '06:30 - 24:00',
        hkTransit: '港铁屯马线 (屯门/天水围/兆康站) 转乘专线巴士 B2 / B2P / B3X',
        szTransit: '深圳地铁 13号线 (深圳湾口岸站直达南山后海及科技园)',
        linkedMtrStationId: 'tinshuiwai',
        desc: '坐落于深圳南山区蛇口东侧,实行一地两检。港铁屯马线天水围或屯门站换乘B2P/B3X专线巴士15分钟即达口岸大楼。'
      },
      {
        id: 'liantang',
        name: '莲塘口岸 / 香园围口岸',
        type: 'bus',
        typeLabel: '人车直达新口岸 · 盐田大梅沙快线',
        badgeColor: 'bg-teal-600 text-white',
        borderType: '两地两检',
        hours: '07:00 - 22:00',
        hkTransit: '港铁东铁线 (上水站/粉岭站) 接驳九巴 B7 / B8 专线巴士',
        szTransit: '深圳地铁 2号线 / 8号线 (莲塘口岸站直通出入境大楼地下)',
        linkedMtrStationId: 'fanling',
        desc: '深港首个采用“人车直达”设计的现代化新口岸。通关环境优美宽敞,过关即达深圳地铁2/8号线莲塘口岸站。'
      },
      {
        id: 'mankamto',
        name: '文锦渡口岸',
        type: 'bus',
        typeLabel: '客流平稳 · 快速过关通道',
        badgeColor: 'bg-amber-600 text-white',
        borderType: '两地两检',
        hours: '07:00 - 22:00',
        hkTransit: '港铁上水站换乘“文锦渡跨境快线”专线巴士',
        szTransit: '深圳地铁 9号线 (文锦站步行约6分钟)',
        linkedMtrStationId: 'sheungshui',
        desc: '老牌陆路客货运口岸,客流量平稳,排队过关用时短。由港铁上水站搭乘跨境快线直通关口。'
      },
      {
        id: 'shekouferry',
        name: '蛇口邮轮母港 / 深圳机场码头',
        type: 'bus',
        typeLabel: '机场海空联运 · 免香港出入境',
        badgeColor: 'bg-indigo-600 text-white',
        borderType: '海天海空联运 / 水上客运',
        hours: '07:00 - 21:00 (依船班时刻)',
        hkTransit: '港铁机场快线 (香港国际机场海天中转客运大楼直通快船)',
        szTransit: '深圳地铁 12号线 (太子湾站) / 2号线 (蛇口港站) / 11号线 (深圳机场码头)',
        linkedMtrStationId: 'airport',
        desc: '经深圳蛇口邮轮母港或深圳机场码头搭乘高速客船直通香港国际机场禁区(海天中转大楼),无需办理香港出入境手续。'
      }
    ];

    let map;
    let currentTileLayer;
    let isDarkMode = false;
    let showStationLabels = true;
    let selectedStationId = null;
    let activeFilteredLineId = null;
    let cnyExchangeRate = 0.925;

    const linePolylineLayers = {};
    const stationMarkerLayers = {};
    let activeRoutePolylineLayer = null;

    // Clean, watermark-free basemap tiles
    const TILE_LIGHT = 'https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}';
    const TILE_LIGHT_ATTRIB = '&copy; Esri & CartoDB | 高德/百度公交地铁模式';
    const TILE_DARK = 'https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}';

    window.addEventListener('DOMContentLoaded', () => {
      initMap();
      renderSidebarLines();
      populateRouteSelects();
      setupClickListeners();
    });

    function initMap() {
      map = L.map('map', {
        center: [22.368, 114.120],
        zoom: 11,
        minZoom: 10,
        maxZoom: 18,
        zoomControl: true
      });

      map.zoomControl.setPosition('topleft');

      currentTileLayer = L.tileLayer(TILE_LIGHT, {
        attribution: TILE_LIGHT_ATTRIB,
        subdomains: 'abcd',
        maxZoom: 18
      }).addTo(map);

      drawAllMetroLines();
      drawAllStationMarkers();
    }

    function drawAllMetroLines() {
      MTR_LINES.forEach(line => {
        const coords = line.customPolyline ? line.customPolyline : getLineCoordinates(line.stations);

        const casing = L.polyline(coords, {
          color: '#ffffff',
          weight: 7.5,
          opacity: 0.9,
          lineCap: 'round',
          lineJoin: 'round',
          smoothFactor: 1
        });

        const polyline = L.polyline(coords, {
          color: line.color,
          weight: 4.8,
          opacity: 0.98,
          lineCap: 'round',
          lineJoin: 'round',
          smoothFactor: 1
        });

        let branchGroup = null;
        if (line.branch) {
          const branchCoords = line.branch.customPolyline ? line.branch.customPolyline : getLineCoordinates(line.branch.stations);
          const branchCasing = L.polyline(branchCoords, {
            color: '#ffffff',
            weight: 7.5,
            opacity: 0.9,
            lineCap: 'round',
            lineJoin: 'round'
          });
          const branchPoly = L.polyline(branchCoords, {
            color: line.color,
            weight: 4.8,
            opacity: 0.98,
            lineCap: 'round',
            lineJoin: 'round'
          });
          branchGroup = L.layerGroup([branchCasing, branchPoly]);
          branchGroup.addTo(map);
        }

        const group = L.layerGroup([casing, polyline]);
        if (branchGroup) group.addLayer(branchGroup);
        group.addTo(map);

        polyline.on('click', () => filterByLine(line.id));
        polyline.bindTooltip(`<b>${line.nameZh}</b> (${line.nameEn})`, { sticky: true, className: 'amap-station-tooltip' });

        linePolylineLayers[line.id] = {
          group: group,
          mainLine: polyline,
          casing: casing,
          color: line.color,
          coords: coords
        };
      });
    }

    function getLineCoordinates(stationIds) {
      return stationIds
        .map(id => STATIONS_DATA[id])
        .filter(st => Boolean(st))
        .map(st => [st.lat, st.lng]);
    }

    function drawAllStationMarkers() {
      Object.values(STATIONS_DATA).forEach(st => {
        const isInterchange = st.lines.length > 1;
        const isBorder = Boolean(st.isBorder);
        const isAirport = Boolean(st.isAirport);
        
        const primaryLineObj = MTR_LINES.find(l => l.id === st.lines[0]);
        const primaryColor = primaryLineObj ? primaryLineObj.color : '#0071CE';

        let markerHtml = '';

        if (isBorder) {
          const borderBadgeColor = st.id === 'lowu' ? '#dc2626' : '#059669';
          const transferText = st.id === 'lowu' ? '深圳1号线(罗宝线)' : '深圳4/10号线(福田口岸)';
          
          markerHtml = `
            <div class="border-station-radar flex items-center justify-center" style="width: 38px; height: 38px; color: ${borderBadgeColor};">
              <div class="w-7 h-7 rounded-full bg-white flex items-center justify-center shadow-lg border-[2.5px]" style="border-color: ${borderBadgeColor};">
                <i class="fa-solid fa-passport text-xs" style="color: ${borderBadgeColor};"></i>
              </div>
              <div class="absolute -top-7 left-1/2 -translate-x-1/2 whitespace-nowrap px-2.5 py-0.5 rounded-full text-[10px] font-extrabold text-white shadow-md flex items-center space-x-1" style="background-color: ${borderBadgeColor}; z-index: 9999;">
                <span>${st.nameZh}</span>
                <span class="opacity-95 font-medium text-[9px]">⇄ ${transferText}</span>
              </div>
            </div>
          `;
        } else if (isAirport) {
          markerHtml = `
            <div class="amap-station-marker" style="width: 24px; height: 24px;">
              <div class="w-6 h-6 rounded-full bg-white border-[2.5px] border-[#008779] shadow-md flex items-center justify-center text-[#008779]">
                <i class="fa-solid fa-plane text-[11px]"></i>
              </div>
            </div>
          `;
        } else if (isInterchange) {
          markerHtml = `
            <div class="amap-station-marker" style="width: 22px; height: 22px;">
              <div style="width: 19px; height: 19px; border: 2.5px solid #2563eb; background: #ffffff; border-radius: 9999px; box-shadow: 0 2px 6px rgba(37,99,235,0.25);" class="flex items-center justify-center">
                <i class="fa-solid fa-retweet text-[9px] text-blue-600"></i>
              </div>
            </div>
          `;
        } else {
          markerHtml = `
            <div class="amap-station-marker" style="width: 14px; height: 14px;">
              <div style="width: 12px; height: 12px; border: 2.5px solid ${primaryColor}; background: #ffffff; border-radius: 9999px; box-shadow: 0 1px 3px rgba(0,0,0,0.15);"></div>
            </div>
          `;
        }

        const customIcon = L.divIcon({
          className: 'amap-custom-station-icon',
          html: markerHtml,
          iconSize: isBorder ? [38, 38] : (isAirport ? [24, 24] : (isInterchange ? [22, 22] : [14, 14])),
          iconAnchor: isBorder ? [19, 19] : (isAirport ? [12, 12] : (isInterchange ? [11, 11] : [7, 7]))
        });

        const marker = L.marker([st.lat, st.lng], { icon: customIcon });

        const tooltipContent = `
          <div class="text-center">
            <span class="font-extrabold text-slate-900">${st.nameZh}</span>
            <span class="font-normal text-slate-400 text-[10px] ml-0.5">${st.nameEn}</span>
          </div>
        `;

        marker.bindTooltip(tooltipContent, {
          permanent: isBorder,
          direction: 'top',
          offset: isBorder ? [0, -14] : [0, -8],
          className: isBorder ? 'amap-border-tooltip' : 'amap-station-tooltip'
        });

        marker.on('click', () => openStationDetails(st.id));
        marker.addTo(map);
        stationMarkerLayers[st.id] = marker;
      });
    }

    function buildAdjacencyGraph() {
      const graph = {};
      Object.keys(STATIONS_DATA).forEach(stId => {
        graph[stId] = [];
      });

      MTR_LINES.forEach(line => {
        for (let i = 0; i < line.stations.length - 1; i++) {
          const u = line.stations[i];
          const v = line.stations[i+1];
          if (graph[u] && graph[v]) {
            graph[u].push({ neighbor: v, lineId: line.id });
            graph[v].push({ neighbor: u, lineId: line.id });
          }
        }
        if (line.branch) {
          for (let i = 0; i < line.branch.stations.length - 1; i++) {
            const u = line.branch.stations[i];
            const v = line.branch.stations[i+1];
            if (graph[u] && graph[v]) {
              graph[u].push({ neighbor: v, lineId: line.id });
              graph[v].push({ neighbor: u, lineId: line.id });
            }
          }
        }
      });

      return graph;
    }

    const networkGraph = buildAdjacencyGraph();

    function calculateMtrFare(originId, destId, path) {
      if (originId === destId) return { octopusHkd: 0, ticketHkd: 0, childHkd: 0 };

      const isAelOrigin = ['airport', 'asiaworldexpo'].includes(originId);
      const isAelDest = ['airport', 'asiaworldexpo'].includes(destId);

      // 1. Airport Express Journey
      if (isAelOrigin || isAelDest) {
        const otherStation = isAelOrigin ? destId : originId;
        if (['hongkong', 'central'].includes(otherStation)) {
          return { octopusHkd: 110.0, ticketHkd: 115.0, childHkd: 55.0, note: '机场快线香港站专用标准' };
        } else if (['kowloon', 'austin'].includes(otherStation)) {
          return { octopusHkd: 100.0, ticketHkd: 105.0, childHkd: 50.0, note: '机场快线九龙站专用标准' };
        } else if (otherStation === 'tsingyi') {
          return { octopusHkd: 65.0, ticketHkd: 70.0, childHkd: 32.5, note: '机场快线青衣站专用标准' };
        } else if (originId === 'airport' && destId === 'asiaworldexpo' || originId === 'asiaworldexpo' && destId === 'airport') {
          return { octopusHkd: 6.0, ticketHkd: 6.0, childHkd: 3.0, note: '机场与博览馆区间专用标准' };
        } else {
          let baseAel = 110.0;
          return { octopusHkd: baseAel, ticketHkd: baseAel + 5.0, childHkd: baseAel / 2, note: '八达通换乘机场快线赠港铁市区免费接驳' };
        }
      }

      // 2. Border Station Journey
      const isBorderOrigin = ['lowu', 'lokmachau'].includes(originId);
      const isBorderDest = ['lowu', 'lokmachau'].includes(destId);

      if (isBorderOrigin || isBorderDest) {
        const otherSt = isBorderOrigin ? STATIONS_DATA[destId] : STATIONS_DATA[originId];
        const otherId = isBorderOrigin ? destId : originId;

        if (otherId === 'sheungshui') {
          return { octopusHkd: 27.0, ticketHkd: 29.5, childHkd: 13.5, note: '罗湖/落马洲 ⇄ 上水过境专用收费' };
        } else if (['fanling', 'taiwo', 'taipomarket'].includes(otherId)) {
          return { octopusHkd: 33.0, ticketHkd: 36.0, childHkd: 16.5, note: '大埔/粉岭过境收费' };
        } else if (['university', 'fotan', 'shatin', 'taiwai'].includes(otherId)) {
          return { octopusHkd: 38.5, ticketHkd: 42.0, childHkd: 19.3, note: '沙田/大围过境收费' };
        } else if (otherSt.lines.includes('island') || otherSt.lines.includes('southisland') || ['admiralty', 'central', 'wanchai', 'causewaybay'].includes(otherId)) {
          return { octopusHkd: 51.9, ticketHkd: 56.5, childHkd: 26.0, note: '东铁线全线港岛直通过境标准' };
        } else if (['tuenmun', 'tinshuiwai', 'yuenlong'].includes(otherId)) {
          return { octopusHkd: 44.5, ticketHkd: 48.5, childHkd: 22.3, note: '新界西北过境收费' };
        } else {
          return { octopusHkd: 43.5, ticketHkd: 47.5, childHkd: 21.8, note: '九龙市区往返过境收费' };
        }
      }

      // 3. Disneyland Line
      if (originId === 'disneyland' || destId === 'disneyland') {
        const otherId = originId === 'disneyland' ? destId : originId;
        if (otherId === 'sunnybay') {
          return { octopusHkd: 7.5, ticketHkd: 8.5, childHkd: 3.8, note: '欣澳迪士尼度假区接驳' };
        } else if (['tungchung', 'tsingyi'].includes(otherId)) {
          return { octopusHkd: 16.0, ticketHkd: 18.0, childHkd: 8.0, note: '大屿山/青衣往迪士尼' };
        } else {
          return { octopusHkd: 28.5, ticketHkd: 32.0, childHkd: 14.3, note: '市区往返迪士尼度假区' };
        }
      }

      // 4. General Network
      const stops = path ? (path.length - 1) : 4;
      const st1 = STATIONS_DATA[originId];
      const st2 = STATIONS_DATA[destId];
      const isCrossHarbour = (st1.lat < 22.290 && st2.lat >= 22.295) || (st2.lat < 22.290 && st1.lat >= 22.295);

      let baseFare = 4.8;
      if (stops <= 2) {
        baseFare = isCrossHarbour ? 10.8 : 4.8;
      } else if (stops <= 5) {
        baseFare = isCrossHarbour ? 12.8 : 6.0;
      } else if (stops <= 9) {
        baseFare = isCrossHarbour ? 15.2 : 9.2;
      } else if (stops <= 14) {
        baseFare = isCrossHarbour ? 19.8 : 12.5;
      } else if (stops <= 20) {
        baseFare = isCrossHarbour ? 24.5 : 16.5;
      } else {
        baseFare = isCrossHarbour ? 29.8 : 22.0;
      }

      const octFare = parseFloat(baseFare.toFixed(1));
      const ticketFare = parseFloat((octFare * 1.08).toFixed(1));
      const childFare = parseFloat((octFare * 0.5).toFixed(1));

      return {
        octopusHkd: octFare,
        ticketHkd: ticketFare,
        childHkd: childFare,
        note: isCrossHarbour ? '含维多利亚港过海铁路附加区间' : '标准本地路段乘车票价'
      };
    }

    function updateExchangeRate(newRate) {
      const val = parseFloat(newRate);
      if (!isNaN(val) && val > 0) {
        cnyExchangeRate = val;
        calculateRouteAndFare();
      }
    }

    function calculateRouteAndFare() {
      const origin = document.getElementById('routeOrigin').value;
      const dest = document.getElementById('routeDestination').value;
      const resultBox = document.getElementById('routeResultBox');

      if (!origin || !dest) {
        resultBox.innerHTML = '';
        clearActiveRouteLayer();
        return;
      }

      if (origin === dest) {
        resultBox.innerHTML = `
          <div class="p-3 bg-amber-50 rounded-xl border border-amber-200 text-xs text-amber-800 text-center font-bold">
            起点与到达站相同,无需乘车。
          </div>
        `;
        clearActiveRouteLayer();
        return;
      }

      const queue = [[origin, [origin], []]];
      const visited = new Set([origin]);
      let shortestPath = null;
      let pathLines = [];

      while (queue.length > 0) {
        const [current, path, linesUsed] = queue.shift();

        if (current === dest) {
          shortestPath = path;
          pathLines = linesUsed;
          break;
        }

        const neighbors = networkGraph[current] || [];
        for (const edge of neighbors) {
          if (!visited.has(edge.neighbor)) {
            visited.add(edge.neighbor);
            queue.push([
              edge.neighbor, 
              [...path, edge.neighbor], 
              [...linesUsed, { from: current, to: edge.neighbor, lineId: edge.lineId }]
            ]);
          }
        }
      }

      if (shortestPath) {
        const fareData = calculateMtrFare(origin, dest, shortestPath);
        renderGaoDeStyleRouteCard(shortestPath, pathLines, fareData);
        highlightRouteOnMap(shortestPath);
      }
    }

    function renderGaoDeStyleRouteCard(path, pathSegments, fareData) {
      const resultBox = document.getElementById('routeResultBox');
      const originSt = STATIONS_DATA[path[0]];
      const destSt = STATIONS_DATA[path[path.length - 1]];

      const stopCount = path.length - 1;
      const estMinutes = Math.round(stopCount * 2.3 + 3);

      const octCny = (fareData.octopusHkd * cnyExchangeRate).toFixed(1);
      const ticketCny = (fareData.ticketHkd * cnyExchangeRate).toFixed(1);
      const childCny = (fareData.childHkd * cnyExchangeRate).toFixed(1);

      const journeyLegs = [];
      let currentLeg = null;

      pathSegments.forEach(seg => {
        if (!currentLeg || currentLeg.lineId !== seg.lineId) {
          if (currentLeg) journeyLegs.push(currentLeg);
          currentLeg = {
            lineId: seg.lineId,
            startStation: seg.from,
            endStation: seg.to,
            stops: [seg.from, seg.to]
          };
        } else {
          currentLeg.endStation = seg.to;
          currentLeg.stops.push(seg.to);
        }
      });
      if (currentLeg) journeyLegs.push(currentLeg);

      const legsHtml = journeyLegs.map((leg) => {
        const lineObj = MTR_LINES.find(l => l.id === leg.lineId);
        const fromName = STATIONS_DATA[leg.startStation].nameZh;
        const toName = STATIONS_DATA[leg.endStation].nameZh;
        const stopsCount = leg.stops.length - 1;

        return `
          <div class="relative pl-6 pb-3 border-l-2 border-slate-200 last:border-transparent last:pb-0">
            <span class="absolute -left-[7px] top-1 w-3.5 h-3.5 rounded-full border-2 bg-white flex items-center justify-center" style="border-color: ${lineObj.color};">
              <span class="w-1.5 h-1.5 rounded-full" style="background-color: ${lineObj.color};"></span>
            </span>
            <div class="text-xs">
              <div class="font-extrabold text-slate-800 flex items-center space-x-1.5 flex-wrap">
                <span class="px-2 py-0.5 rounded text-[10px] text-white font-bold" style="background-color: ${lineObj.color};">${lineObj.nameZh}</span>
                <span>${fromName} ➜ ${toName}</span>
              </div>
              <p class="text-[11px] text-slate-400 mt-0.5 font-medium">搭乘 ${stopsCount} 站 (约 ${(stopsCount * 2.2).toFixed(0)} 分钟)</p>
            </div>
          </div>
        `;
      }).join('');

      let borderAlert = '';
      if (destSt.borderTransfer) {
        borderAlert = `
          <div class="p-3 bg-red-50/90 border border-red-200 rounded-xl text-xs text-red-900 space-y-1">
            <div class="font-extrabold flex items-center space-x-1.5 text-red-700">
              <i class="fa-solid fa-person-walking-luggage"></i>
              <span>口岸过关指引:</span>
            </div>
            <p class="text-[11px] leading-relaxed text-red-800">${destSt.borderTransfer.description}</p>
          </div>
        `;
      }

      resultBox.innerHTML = `
        <div class="bg-white p-4 rounded-2xl border border-slate-200/90 shadow-md space-y-3.5">
          <div class="border-b border-slate-100 pb-3">
            <div class="flex items-center justify-between">
              <div class="text-xs text-slate-400 font-bold">乘车时长预估</div>
              <button onclick="panToRoute()" class="text-xs font-bold text-blue-600 hover:text-blue-700 bg-blue-50 px-2.5 py-1 rounded-lg transition">
                <i class="fa-solid fa-location-arrow mr-1 text-[10px]"></i>全览路线
              </button>
            </div>
            <div class="mt-1 flex items-baseline space-x-2">
              <span class="text-2xl font-black text-slate-900">约 ${estMinutes} <span class="text-sm font-bold">分钟</span></span>
              <span class="text-xs text-slate-500 font-semibold">(${stopCount} 站 · 换乘 ${journeyLegs.length - 1} 次)</span>
            </div>
          </div>

          <div class="bg-gradient-to-br from-amber-50/70 via-orange-50/40 to-white p-3.5 rounded-xl border border-amber-200/80 space-y-2">
            <div class="flex items-center justify-between text-xs">
              <span class="font-extrabold text-amber-900 flex items-center space-x-1.5">
                <i class="fa-solid fa-ticket text-amber-500"></i>
                <span>港铁票价明细 (双币估算)</span>
              </span>
              <span class="text-[10px] text-amber-800 font-bold bg-amber-100/70 px-1.5 py-0.5 rounded">
                1 HKD ≈ ${cnyExchangeRate} CNY
              </span>
            </div>

            <div class="grid grid-cols-2 gap-2 pt-1">
              <div class="bg-white/90 p-2.5 rounded-lg border border-amber-200/60 shadow-xs">
                <div class="text-[10px] font-bold text-slate-400">成人八达通 (Octopus)</div>
                <div class="text-base font-black text-slate-900 leading-tight mt-0.5">
                  HK$ ${fareData.octopusHkd}
                </div>
                <div class="text-[11px] font-extrabold text-amber-600 mt-0.5">
                  ≈ ¥${octCny} <span class="text-[10px] font-normal text-slate-400">人民币</span>
                </div>
              </div>

              <div class="bg-white/90 p-2.5 rounded-lg border border-amber-200/60 shadow-xs">
                <div class="text-[10px] font-bold text-slate-400">单程车票 (Ticket)</div>
                <div class="text-base font-black text-slate-800 leading-tight mt-0.5">
                  HK$ ${fareData.ticketHkd}
                </div>
                <div class="text-[11px] font-bold text-slate-600 mt-0.5">
                  ≈ ¥${ticketCny} <span class="text-[10px] font-normal text-slate-400">人民币</span>
                </div>
              </div>
            </div>

            <div class="flex items-center justify-between text-[11px] text-slate-500 px-1 pt-1 border-t border-amber-100">
              <span>特惠小童/长者八达通:</span>
              <span class="font-bold text-slate-800">HK$ ${fareData.childHkd} (约 ¥${childCny})</span>
            </div>
            
            <div class="text-[10px] text-amber-800 font-medium px-1">
              * ${fareData.note}
            </div>
          </div>

          <div class="pt-1 space-y-1">
            <div class="text-xs font-bold text-slate-700 pb-1 flex items-center space-x-1">
              <i class="fa-solid fa-shoe-prints text-slate-400 text-xs"></i>
              <span>换乘乘车方案</span>
            </div>
            ${legsHtml}
          </div>

          ${borderAlert}
        </div>
      `;
    }

    function highlightRouteOnMap(path) {
      clearActiveRouteLayer();

      const routeCoords = path.map(id => [STATIONS_DATA[id].lat, STATIONS_DATA[id].lng]);

      const casing = L.polyline(routeCoords, {
        color: '#0f172a',
        weight: 9,
        opacity: 0.9,
        lineCap: 'round',
        lineJoin: 'round'
      });

      const core = L.polyline(routeCoords, {
        color: '#fbbf24',
        weight: 5.5,
        opacity: 1,
        dashArray: '10, 8',
        lineCap: 'round'
      });

      activeRoutePolylineLayer = L.layerGroup([casing, core]);
      activeRoutePolylineLayer.addTo(map);

      map.fitBounds(routeCoords, { padding: [55, 55], maxZoom: 14 });
    }

    function clearActiveRouteLayer() {
      if (activeRoutePolylineLayer) {
        map.removeLayer(activeRoutePolylineLayer);
        activeRoutePolylineLayer = null;
      }
    }

    function panToRoute() {
      if (activeRoutePolylineLayer) {
        const bounds = activeRoutePolylineLayer.getLayers()[0].getBounds();
        map.fitBounds(bounds, { padding: [50, 50] });
      }
    }

    function swapRouteStations() {
      const originSel = document.getElementById('routeOrigin');
      const destSel = document.getElementById('routeDestination');
      const temp = originSel.value;
      originSel.value = destSel.value;
      destSel.value = temp;
      calculateRouteAndFare();
    }

    function renderSidebarLines() {
      const container = document.getElementById('linesListContainer');
      container.innerHTML = '';

      MTR_LINES.forEach(line => {
        const count = line.stations.length + (line.branch ? line.branch.stations.length - 1 : 0);
        const item = document.createElement('div');
        item.id = `line-card-${line.id}`;
        item.className = 'p-3 rounded-2xl bg-white border border-slate-200/90 hover:border-blue-300 hover:shadow-md cursor-pointer transition flex items-center justify-between group';
        item.onclick = () => filterByLine(line.id);

        item.innerHTML = `
          <div class="flex items-center space-x-3">
            <span class="w-4 h-4 rounded-full shrink-0 shadow-xs ring-2 ring-white" style="background-color: ${line.color};"></span>
            <div>
              <div class="font-extrabold text-xs text-slate-800 group-hover:text-blue-600 transition flex items-center space-x-1">
                <span>${line.nameZh}</span>
                <span class="text-[10px] font-normal text-slate-400">(${line.nameEn})</span>
              </div>
              <p class="text-[10px] text-slate-400 leading-tight mt-0.5">${line.description.slice(0, 26)}...</p>
            </div>
          </div>
          <span class="text-[11px] font-bold bg-slate-100 text-slate-600 px-2.5 py-1 rounded-full shrink-0">
            ${count} 站
          </span>
        `;
        container.appendChild(item);
      });
    }

    function filterByLine(lineId) {
      const line = MTR_LINES.find(l => l.id === lineId);
      if (!line) return;

      activeFilteredLineId = lineId;

      const banner = document.getElementById('activeLineBanner');
      const dot = document.getElementById('activeLineDot');
      const name = document.getElementById('activeLineName');
      banner.classList.remove('hidden');
      dot.style.backgroundColor = line.color;
      name.innerText = `${line.nameZh} (${line.nameEn})`;

      Object.keys(linePolylineLayers).forEach(id => {
        const lyr = linePolylineLayers[id];
        if (id === lineId) {
          lyr.mainLine.setStyle({ opacity: 1, weight: 6.5 });
          lyr.casing.setStyle({ opacity: 0.95, weight: 10 });
        } else {
          lyr.mainLine.setStyle({ opacity: 0.12, weight: 3 });
          lyr.casing.setStyle({ opacity: 0.08, weight: 4.5 });
        }
      });

      MTR_LINES.forEach(l => {
        const card = document.getElementById(`line-card-${l.id}`);
        if (card) {
          if (l.id === lineId) {
            card.classList.add('ring-2', 'ring-blue-500', 'bg-blue-50/60');
          } else {
            card.classList.remove('ring-2', 'ring-blue-500', 'bg-blue-50/60');
          }
        }
      });

      const coords = line.customPolyline ? line.customPolyline : getLineCoordinates(line.stations);
      map.fitBounds(coords, { padding: [40, 40], maxZoom: 14 });

      if (window.innerWidth < 768) {
        document.getElementById('mainSidebar').classList.add('-translate-x-full');
      }
    }

    function resetLineFilter() {
      activeFilteredLineId = null;
      document.getElementById('activeLineBanner').classList.add('hidden');

      Object.values(linePolylineLayers).forEach(lyr => {
        lyr.mainLine.setStyle({ opacity: 0.98, weight: 4.8 });
        lyr.casing.setStyle({ opacity: 0.9, weight: 7.5 });
      });

      MTR_LINES.forEach(l => {
        const card = document.getElementById(`line-card-${l.id}`);
        if (card) card.classList.remove('ring-2', 'ring-blue-500', 'bg-blue-50/60');
      });

      resetMapView();
    }

    function resetMapView() {
      map.setView([22.368, 114.120], 11);
    }

    function openStationDetails(stationId) {
      const st = STATIONS_DATA[stationId];
      if (!st) return;

      selectedStationId = stationId;

      const card = document.getElementById('stationDetailCard');
      const headerBar = document.getElementById('stationCardHeaderBar');
      const nameZh = document.getElementById('cardStationNameZh');
      const nameTc = document.getElementById('cardStationNameTc');
      const nameEn = document.getElementById('cardStationNameEn');
      const linesBox = document.getElementById('cardLinesContainer');
      const borderBox = document.getElementById('cardBorderCallout');

      nameZh.innerText = st.nameZh;
      nameTc.innerText = `繁体: ${st.nameTc}`;
      nameEn.innerText = st.nameEn;

      const firstLine = MTR_LINES.find(l => l.id === st.lines[0]);
      headerBar.style.backgroundColor = firstLine ? firstLine.color : '#0071CE';

      linesBox.innerHTML = '';
      st.lines.forEach(lid => {
        const lineObj = MTR_LINES.find(l => l.id === lid);
        if (lineObj) {
          const pill = document.createElement('span');
          pill.className = 'px-2.5 py-1 rounded-full text-xs font-bold shadow-xs flex items-center space-x-1 cursor-pointer';
          pill.style.backgroundColor = lineObj.color;
          pill.style.color = lineObj.textColor;
          pill.innerHTML = `<span>${lineObj.nameZh}</span>`;
          pill.onclick = () => filterByLine(lineObj.id);
          linesBox.appendChild(pill);
        }
      });

      if (st.borderTransfer) {
        borderBox.classList.remove('hidden');
        const isLowu = st.id === 'lowu';
        borderBox.className = `rounded-xl p-3 border text-xs space-y-1.5 ${isLowu ? 'bg-red-50 border-red-200 text-red-900' : 'bg-emerald-50 border-emerald-200 text-emerald-900'}`;
        borderBox.innerHTML = `
          <div class="font-extrabold flex items-center space-x-1.5 ${isLowu ? 'text-red-700' : 'text-emerald-700'}">
            <i class="fa-solid fa-passport"></i>
            <span>${st.borderTransfer.name}</span>
          </div>
          <p class="text-[11px] leading-relaxed">${st.borderTransfer.description}</p>
        `;
      } else {
        borderBox.classList.add('hidden');
      }

      card.classList.remove('hidden');
      map.panTo([st.lat, st.lng], { animate: true, duration: 0.6 });
    }

    function closeStationCard() {
      document.getElementById('stationDetailCard').classList.add('hidden');
      selectedStationId = null;
    }

    function focusBorderStation(stationKey) {
      const st = STATIONS_DATA[stationKey];
      if (!st) return;

      map.flyTo([st.lat, st.lng], 15, { duration: 1.2 });
      setTimeout(() => {
        openStationDetails(stationKey);
      }, 450);

      if (window.innerWidth < 768) {
        document.getElementById('mainSidebar').classList.add('-translate-x-full');
      }
    }

    function setAsRoutePoint(type) {
      if (!selectedStationId) return;
      switchTab('planner');
      if (type === 'origin') {
        document.getElementById('routeOrigin').value = selectedStationId;
      } else {
        document.getElementById('routeDestination').value = selectedStationId;
      }
      calculateRouteAndFare();
      closeStationCard();
    }

    function populateRouteSelects() {
      const originSel = document.getElementById('routeOrigin');
      const destSel = document.getElementById('routeDestination');

      const sortedStations = Object.values(STATIONS_DATA).sort((a, b) => a.nameZh.localeCompare(b.nameZh, 'zh-Hans-CN'));

      sortedStations.forEach(st => {
        let tag = '';
        if (st.id === 'lowu') tag = ' (罗湖口岸/换乘深圳1号线)';
        else if (st.id === 'lokmachau') tag = ' (福田口岸/换乘深圳4/10号线)';
        else if (st.id === 'airport') tag = ' (香港国际机场)';

        const opt1 = new Option(`${st.nameZh} ${st.nameEn}${tag}`, st.id);
        const opt2 = new Option(`${st.nameZh} ${st.nameEn}${tag}`, st.id);
        originSel.add(opt1);
        destSel.add(opt2);
      });

      originSel.value = 'central';
      destSel.value = 'lowu';
    }

    function handleSearch(query) {
      const q = query.trim().toLowerCase();
      const dropdown = document.getElementById('searchDropdown');
      const clearBtn = document.getElementById('clearSearchBtn');

      if (!q) {
        dropdown.classList.add('hidden');
        clearBtn.classList.add('hidden');
        return;
      }

      clearBtn.classList.remove('hidden');

      const matches = Object.values(STATIONS_DATA).filter(st => {
        return st.nameZh.toLowerCase().includes(q) ||
               st.nameTc.toLowerCase().includes(q) ||
               st.nameEn.toLowerCase().includes(q) ||
               (st.borderTransfer && st.borderTransfer.name.toLowerCase().includes(q));
      });

      if (matches.length === 0) {
        dropdown.innerHTML = '<div class="p-3 text-xs text-slate-400 text-center">未找到相符地铁站</div>';
      } else {
        dropdown.innerHTML = matches.slice(0, 8).map(st => {
          const lineBadges = st.lines.map(lid => {
            const l = MTR_LINES.find(line => line.id === lid);
            return `<span class="w-2.5 h-2.5 rounded-full inline-block" style="background-color: ${l ? l.color : '#ccc'};"></span>`;
          }).join(' ');

          const borderBadge = st.isBorder 
            ? `<span class="text-[10px] bg-red-100 text-red-700 px-1.5 py-0.5 rounded font-bold">${st.id === 'lowu' ? '罗湖过关' : '福田口岸过关'}</span>`
            : '';

          return `
            <div onclick="selectSearchStation('${st.id}')" class="p-2.5 hover:bg-slate-50 cursor-pointer flex items-center justify-between transition">
              <div class="flex items-center space-x-2">
                <i class="fa-solid fa-location-dot text-blue-500 text-xs"></i>
                <div>
                  <div class="font-bold text-xs text-slate-800">${st.nameZh} <span class="font-normal text-slate-400 text-[11px]">${st.nameEn}</span></div>
                  <div class="text-[10px] text-slate-400">${st.nameTc}</div>
                </div>
              </div>
              <div class="flex items-center space-x-1.5">
                ${borderBadge}
                <div class="flex space-x-1">${lineBadges}</div>
              </div>
            </div>
          `;
        }).join('');
      }

      dropdown.classList.remove('hidden');
    }

    function selectSearchStation(stationId) {
      document.getElementById('searchDropdown').classList.add('hidden');
      const st = STATIONS_DATA[stationId];
      if (st) {
        document.getElementById('stationSearchInput').value = st.nameZh;
        map.flyTo([st.lat, st.lng], 15, { duration: 1 });
        openStationDetails(stationId);
      }
    }

    function clearSearch() {
      const input = document.getElementById('stationSearchInput');
      input.value = '';
      document.getElementById('searchDropdown').classList.add('hidden');
      document.getElementById('clearSearchBtn').classList.add('hidden');
    }

    function switchTab(tabId) {
      ['planner', 'lines', 'borders'].forEach(t => {
        const btn = document.getElementById(`tabBtn-${t}`);
        const content = document.getElementById(`tabContent-${t}`);
        if (t === tabId) {
          btn.className = 'flex-1 py-2 rounded-lg bg-white text-blue-600 shadow-sm border border-slate-200/60 flex items-center justify-center space-x-1.5 transition font-extrabold';
          content.classList.remove('hidden');
        } else {
          btn.className = 'flex-1 py-2 rounded-lg text-slate-600 hover:text-slate-900 flex items-center justify-center space-x-1.5 transition font-semibold';
          content.classList.add('hidden');
        }
      });
    }

    function toggleSidebar() {
      const sidebar = document.getElementById('mainSidebar');
      sidebar.classList.toggle('-translate-x-full');
    }

    function toggleMapStyle() {
      isDarkMode = !isDarkMode;
      const btn = document.getElementById('mapStyleBtn');

      map.removeLayer(currentTileLayer);
      if (isDarkMode) {
        currentTileLayer = L.tileLayer(TILE_DARK, {
          attribution: '&copy; Esri & OSM | 高德/百度夜间暗色模式',
          subdomains: 'abcd',
          maxZoom: 18
        }).addTo(map);
        btn.innerHTML = '<i class="fa-solid fa-sun text-amber-500"></i>';
      } else {
        currentTileLayer = L.tileLayer(TILE_LIGHT, {
          attribution: TILE_LIGHT_ATTRIB,
          subdomains: 'abcd',
          maxZoom: 18
        }).addTo(map);
        btn.innerHTML = '<i class="fa-solid fa-moon"></i>';
      }
    }

    function openBorderCrossingsModal() {
      const modal = document.getElementById('borderModal');
      renderBorderPortsList('all');
      modal.classList.remove('hidden');
    }

    function closeBorderCrossingsModal() {
      const modal = document.getElementById('borderModal');
      modal.classList.add('hidden');
    }

    function filterBorderPorts(category) {
      document.querySelectorAll('.port-filter-btn').forEach(btn => {
        btn.className = 'port-filter-btn px-3 py-1 rounded-full font-bold bg-white text-slate-600 hover:bg-slate-200 border border-slate-200 transition shrink-0';
      });
      const activeBtn = document.getElementById(`portFilter-${category}`);
      if (activeBtn) {
        activeBtn.className = 'port-filter-btn active px-3 py-1 rounded-full font-bold bg-blue-600 text-white shadow-xs transition shrink-0';
      }
      renderBorderPortsList(category);
    }

    function renderBorderPortsList(filterCategory = 'all') {
      const container = document.getElementById('borderPortsList');
      container.innerHTML = '';

      const filtered = BORDER_PORTS_DATA.filter(port => {
        if (filterCategory === 'all') return true;
        return port.type === filterCategory;
      });

      if (filtered.length === 0) {
        container.innerHTML = '<div class="text-center py-8 text-slate-400 text-xs">暂无匹配口岸</div>';
        return;
      }

      filtered.forEach(port => {
        const item = document.createElement('div');
        item.className = 'pt-3.5 first:pt-0 pb-1 flex flex-col space-y-2.5';

        item.innerHTML = `
          <div class="flex items-start justify-between">
            <div class="flex items-center space-x-2">
              <span class="text-base font-black text-slate-900">${port.name}</span>
              <span class="px-2 py-0.5 rounded-md text-[10px] font-extrabold ${port.badgeColor}">
                ${port.typeLabel}
              </span>
            </div>
            <span class="text-[11px] font-bold text-blue-700 bg-blue-50 px-2 py-0.5 rounded-full border border-blue-200/60">
              ${port.borderType}
            </span>
          </div>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
            <div class="bg-slate-50 p-2.5 rounded-xl border border-slate-200/80 space-y-1">
              <div class="font-extrabold text-slate-700 flex items-center space-x-1.5 text-[11px]">
                <i class="fa-solid fa-train-subway text-blue-600"></i>
                <span>香港端交通连接:</span>
              </div>
              <p class="text-slate-800 font-medium leading-relaxed">${port.hkTransit}</p>
            </div>

            <div class="bg-slate-50 p-2.5 rounded-xl border border-slate-200/80 space-y-1">
              <div class="font-extrabold text-slate-700 flex items-center space-x-1.5 text-[11px]">
                <i class="fa-solid fa-retweet text-emerald-600"></i>
                <span>深圳端地铁/交通:</span>
              </div>
              <p class="text-slate-800 font-medium leading-relaxed">${port.szTransit}</p>
            </div>
          </div>

          <div class="text-xs text-slate-600 bg-amber-50/50 p-2.5 rounded-xl border border-amber-200/50 space-y-1">
            <div class="flex items-center space-x-1.5 font-bold text-amber-900 text-[11px]">
              <i class="fa-regular fa-clock text-amber-600"></i>
              <span>通关开放时间:<strong>${port.hours}</strong></span>
            </div>
            <p class="text-[11px] text-slate-600 leading-relaxed">${port.desc}</p>
          </div>

          <div class="flex items-center justify-end space-x-2 pt-1">
            <button onclick="locateBorderPortOnMap('${port.linkedMtrStationId}')" class="px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold transition flex items-center space-x-1">
              <i class="fa-solid fa-location-crosshairs text-blue-600"></i>
              <span>在地图定位</span>
            </button>
            <button onclick="setPortAsRouteDestination('${port.linkedMtrStationId}')" class="px-3 py-1.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold transition flex items-center space-x-1 shadow-xs">
              <i class="fa-solid fa-route"></i>
              <span>设为终点并算票价</span>
            </button>
          </div>
        `;

        container.appendChild(item);
      });
    }

    function locateBorderPortOnMap(stationId) {
      closeBorderCrossingsModal();
      const st = STATIONS_DATA[stationId];
      if (st) {
        map.flyTo([st.lat, st.lng], 15, { duration: 1.2 });
        setTimeout(() => {
          openStationDetails(stationId);
        }, 500);
      }
    }

    function setPortAsRouteDestination(stationId) {
      closeBorderCrossingsModal();
      switchTab('planner');
      const destSel = document.getElementById('routeDestination');
      if (destSel) {
        destSel.value = stationId;
        calculateRouteAndFare();
      }
      if (window.innerWidth < 768) {
        document.getElementById('mainSidebar').classList.remove('-translate-x-full');
      }
    }

    function toggleStationLabels() {
      showStationLabels = !showStationLabels;
      const text = document.getElementById('labelStatusText');

      Object.values(stationMarkerLayers).forEach(marker => {
        const tooltip = marker.getTooltip();
        if (tooltip && !tooltip.options.permanent) {
          if (showStationLabels) {
            marker.openTooltip();
          } else {
            marker.closeTooltip();
          }
        }
      });

      text.innerText = showStationLabels ? '隐藏站名' : '显示站名';
    }

    function setupClickListeners() {
      document.addEventListener('click', (e) => {
        const searchBox = document.getElementById('stationSearchInput');
        const dropdown = document.getElementById('searchDropdown');
        if (!searchBox.contains(e.target) && !dropdown.contains(e.target)) {
          dropdown.classList.add('hidden');
        }
      });
    }
  </script>
</body>
</html>