'use strict';
/** v49 parity pack: map UX unification hints + voice path guide */

function $(id) { return document.getElementById(id); }

function bindVoicePathGuide() {
  const el = $('voicePathGuide');
  if (!el) return;
  const update = () => {
    const relay = typeof ws !== 'undefined' && ws && ws.readyState === WebSocket.OPEN;
    const p2p = typeof rtc !== 'undefined' && rtc.conns.some((c) => c.dc && c.dc.readyState === 'open');
    const android = /Android/i.test(navigator.userAgent || '');
    if (p2p && !relay) {
      el.innerHTML = '⚡ <b>WebRTC 即時語音</b>：按住 PTT 走標準 Opus（與 Chrome／iPhone 互通）';
      el.className = 'voice-path-guide ok';
    } else if (p2p && relay) {
      el.innerHTML = '🔀 P2P+中繼：語音優先 WebRTC；文字／位置可走 Mesh';
      el.className = 'voice-path-guide ok';
    } else if (relay) {
      el.innerHTML = android
        ? '📡 <b>中繼語音片段</b>（約 0.7s）：與 APK 跨平台互通；近距請用熱點+QR 或 APK Wi‑Fi Direct'
        : '📡 <b>中繼語音片段</b>（約 0.7s）：跨網穩定；無外網請用熱點+QR 兩輪配對';
      el.className = 'voice-path-guide warn';
    } else {
      el.innerHTML = '❌ 未連線：有網→中繼+6碼；無網→掃 QR／貼配對碼（Chrome 無 Wi‑Fi Direct）';
      el.className = 'voice-path-guide bad';
    }
  };
  update();
  setInterval(update, 4000);
}

function bindOfflineMapQuickStart() {
  const status = $('mapDownloadStatus');
  const checkBtn = $('mapDownloadCheckBtn');
  if (checkBtn && !checkBtn._v49) {
    checkBtn._v49 = true;
    checkBtn.addEventListener('click', () => {
      if (status) status.textContent = '提示：APK 用「下載台灣離線圖」；網頁用 PMTiles。兩者皆支援進山離線。';
    });
  }
  const dlBtn = $('mapDownloadBtn');
  if (dlBtn && !dlBtn._v49Hint) {
    dlBtn._v49Hint = true;
    const orig = dlBtn.onclick;
    dlBtn.addEventListener('click', () => {
      if (status && !status.textContent) {
        status.textContent = '下載中…（與 APK MapLibre 圖磚快取同概念）';
      }
    });
  }
  if (status && state.mapSrc === 'offline') {
    status.textContent = status.textContent || '✓ 離線 PMTiles 模式（APK 對應：MapLibre 圖磚下載）';
  }
}

function initStabilityV49() {
  if (typeof initStabilityV48 === 'function') initStabilityV48();
  bindVoicePathGuide();
  bindOfflineMapQuickStart();
}

window.initStabilityV49 = initStabilityV49;
