'use strict';
/** v51: 穩定性提示、醫療卡 QR、圍欄地圖點選、離線佇列提示 */

function initStabilityV51() {
  if (typeof initStabilityV50 === 'function') initStabilityV50();
  bindStabilityHints();
  bindMedCardQr();
  bindGeofenceMapPick();
}

function bindStabilityHints() {
  const pinHint = $('relayPinHint');
  if (pinHint && !pinHint._v51) {
    pinHint._v51 = true;
    pinHint.textContent = '遠距中繼建議在伺服器設 RELAY_ROOM_PINS；跨網 WebRTC 不穩可自建 coturn。';
  }
  const batHint = $('batteryHint');
  if (batHint && !batHint._v51) {
    batHint._v51 = true;
    batHint.textContent = '長時間開定位＋中繼較耗電，戶外請帶行動電源。';
  }
  const pwaHint = $('pwaUpdateHint');
  if (pwaHint && !pwaHint._v51) {
    pwaHint._v51 = true;
    pwaHint.textContent = '更新後請完全關閉分頁再開，或清除網站資料，以載入最新 v51。';
  }
  if (navigator.getBattery) {
    navigator.getBattery().then(b => {
      const el = $('batteryLevelHint');
      if (!el) return;
      const pct = Math.round(b.level * 100);
      el.textContent = `本機電量約 ${pct}%${b.charging ? '（充電中）' : ''}`;
    }).catch(() => {});
  }
}

function bindMedCardQr() {
  const btn = $('medCardQrBtn');
  const modal = $('medCardQrModal');
  const close = $('medCardQrCloseBtn');
  const canvas = $('medCardQrCanvas');
  if (!btn || btn._v51) return;
  btn._v51 = true;
  btn.onclick = () => {
    const payload = medCardQrPayload();
    if (!payload || payload === 'p2p-med:|||') {
      alert('請先填寫並儲存急救卡');
      return;
    }
    if (modal) modal.classList.remove('hidden');
    if (canvas && window.qrcode) {
      const qr = qrcode(0, 'M');
      qr.addData(payload);
      qr.make();
      const size = 220;
      canvas.width = size;
      canvas.height = size;
      const ctx = canvas.getContext('2d');
      const cells = qr.getModuleCount();
      const scale = size / cells;
      ctx.fillStyle = '#fff';
      ctx.fillRect(0, 0, size, size);
      ctx.fillStyle = '#000';
      for (let r = 0; r < cells; r++) {
        for (let c = 0; c < cells; c++) {
          if (qr.isDark(r, c)) ctx.fillRect(c * scale, r * scale, scale, scale);
        }
      }
    }
  };
  if (close) close.onclick = () => modal?.classList.add('hidden');
}

function medCardQrPayload() {
  const blood = ($('medBlood')?.value || '').trim();
  const allergies = ($('medAllergies')?.value || '').trim();
  const notes = ($('medNotes')?.value || '').trim();
  const phone = ($('medPhone')?.value || '').trim();
  return 'p2p-med:' + [blood, allergies, notes, phone].join('|');
}

let geofenceCenterMarker = null;

function setGeofenceCenterMarker(lat, lon) {
  if (!map || lat == null || lon == null) return;
  const ll = [lon, lat];
  if (!geofenceCenterMarker) {
    const el = document.createElement('div');
    el.style.cssText = 'width:14px;height:14px;border-radius:50%;background:#f57c00;border:2px solid #fff;box-shadow:0 0 4px rgba(0,0,0,.4)';
    geofenceCenterMarker = new maplibregl.Marker({ element: el }).setLngLat(ll).addTo(map);
  } else {
    geofenceCenterMarker.setLngLat(ll);
  }
}

function bindGeofenceMapPick() {
  const btn = $('geofenceMapPickBtn');
  if (!btn || btn._v51) return;
  btn._v51 = true;
  btn.onclick = () => {
    state.geofencePickMode = !state.geofencePickMode;
    btn.textContent = state.geofencePickMode ? '點地圖設中心（進行中）' : '地圖點選中心';
    if (state.geofencePickMode) {
      showPage('map');
      ensureMap();
      wireGeofenceMapClick();
      showMapHint('點地圖上任意位置設為圍欄中心');
    }
  };
}

function wireGeofenceMapClick() {
  if (!map || map._geofencePickBound) return;
  map._geofencePickBound = true;
  const btn = $('geofenceMapPickBtn');
  map.on('click', (e) => {
    if (!state.geofencePickMode) return;
    const g = state.geofence;
    g.lat = e.lngLat.lat;
    g.lon = e.lngLat.lng;
    g.enabled = true;
    const sw = $('geofenceSwitch');
    if (sw) sw.checked = true;
    state.geofencePickMode = false;
    if (btn) btn.textContent = '地圖點選中心';
    persistGeofence();
    setGeofenceCenterMarker(g.lat, g.lon);
    checkGeofence();
    showMapHint('已設圍欄中心');
  });
}

function refreshGeofenceCenterMarker() {
  const g = state.geofence;
  if (g && g.lat != null && g.lon != null) setGeofenceCenterMarker(g.lat, g.lon);
}

window.initStabilityV51 = initStabilityV51;
window.medCardQrPayload = medCardQrPayload;
window.refreshGeofenceCenterMarker = refreshGeofenceCenterMarker;
window.wireGeofenceMapClick = wireGeofenceMapClick;
