'use strict';
/** v50: E2EE QR + offline map quick fetch hint */

function initStabilityV50() {
  if (typeof initStabilityV49 === 'function') initStabilityV49();
  bindOfflineMapBundle();
  const close = $('e2eeQrCloseBtn');
  if (close) close.onclick = () => $('e2eeQrModal')?.classList.add('hidden');
}

async function bindOfflineMapBundle() {
  const btn = $('mapBundleFetchBtn');
  const status = $('mapBundleStatus');
  if (!btn || btn._v50) return;
  btn._v50 = true;
  btn.onclick = async () => {
    if (!status) return;
    status.textContent = '檢查 map/region.pmtiles…';
    try {
      const r = await fetch('map/region.pmtiles', { method: 'HEAD', cache: 'no-store' });
      if (r.ok) {
        state.pmtilesPath = 'map/region.pmtiles';
        store.set('p2p_pmtiles', state.pmtilesPath);
        state.mapSrc = 'offline';
        store.set('p2p_mapsrc', 'offline');
        if (typeof applyMapSource === 'function') applyMapSource();
        status.textContent = '✓ 已載入伺服器預建 PMTiles';
        status.className = 'map-download-status ok';
      } else {
        status.textContent = '伺服器尚無預建檔，請用電腦執行 tools/make_pmtiles.py';
        status.className = 'map-download-status warn';
      }
    } catch (e) {
      status.textContent = '無法連線：' + e.message;
      status.className = 'map-download-status bad';
    }
  };
}

window.initStabilityV50 = initStabilityV50;
