'use strict';
/** v83: Web 補齊 APK／舊版功能（不重複 DOM）；v104 多機鎖定 */

function toggleLockedPeer(sid) {
  const set = new Set(state.lockedPeers || []);
  if (set.has(sid)) set.delete(sid); else set.add(sid);
  state.lockedPeers = [...set];
  state.lockedPeer = set.size ? [...set][0] : null;
  try { store.setJSON('p2p_locked_peers', state.lockedPeers); } catch {}
}

function renderPeerLockLists() {
  const targets = ['walkiePeerLockList'];
  const now = Date.now();
  const ids = Object.keys(state.peers || {}).filter((sid) => now - (state.peers[sid].ts || 0) <= STALE_MS * 3);
  targets.forEach((tid) => {
    const box = $(tid);
    if (!box) return;
    if (!ids.length) {
      box.innerHTML = '<div class="muted small">尚無在線隊友</div>';
      return;
    }
    const lockedN = (state.lockedPeers || []).length;
    box.innerHTML = lockedN
      ? `<div class="muted small" style="margin-bottom:6px">已鎖定 ${lockedN} 人（同一警報距離）</div>`
      : '<div class="muted small" style="margin-bottom:6px">可同時鎖定多位</div>';
    ids.forEach((sid) => {
      const p = state.peers[sid];
      const locked = (state.lockedPeers || []).includes(sid);
      const roleTag = (p.roleName || (typeof ROLE_LABELS !== 'undefined' && ROLE_LABELS[p.role]) || '').trim();
      const rolePart = roleTag ? ` · ${escapeHtml(roleTag)}` : '';
      const bat = p.battery != null ? ` · 🔋${p.battery}%` : '';
      const item = document.createElement('div');
      item.className = 'peer-item';
      item.innerHTML = `<span>${escapeHtml(p.name)}${rolePart}${bat}</span>`;
      const btn = document.createElement('button');
      btn.className = 'btn ghost small';
      btn.textContent = locked ? '已鎖定 ✓' : '鎖定';
      btn.onclick = () => {
        toggleLockedPeer(sid);
        if (typeof renderPeerList === 'function') renderPeerList();
        renderPeerLockLists();
        if (typeof updateDistances === 'function') updateDistances();
      };
      item.appendChild(btn);
      box.appendChild(item);
    });
    if (lockedN) {
      const clear = document.createElement('button');
      clear.className = 'btn ghost small';
      clear.textContent = '全部解除鎖定';
      clear.style.marginTop = '6px';
      clear.onclick = () => {
        state.lockedPeers = [];
        state.lockedPeer = null;
        try { store.setJSON('p2p_locked_peers', []); } catch {}
        if (typeof renderPeerList === 'function') renderPeerList();
        renderPeerLockLists();
        if (typeof updateDistances === 'function') updateDistances();
      };
      box.appendChild(clear);
    }
  });
}

function renderFloorCalButtons() {
  const row = $('walkieFloorCalRow');
  if (!row || row._bound) return;
  row._bound = true;
  row.innerHTML = '';
  [-2, -1, 1, 2, 3, 5].forEach((f) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.className = 'btn ghost small';
    b.textContent = `${f}F`;
    b.onclick = () => { if (typeof setFloor === 'function') setFloor(String(f)); };
    row.appendChild(b);
  });
}

function bindAudioRouteUI() {
  const route = store.get('p2p_audio_route', 'speaker');
  state.audioRoute = route;
  document.querySelectorAll('.audio-route-btn').forEach((btn) => {
    btn.classList.toggle('active', btn.dataset.route === route);
    btn.onclick = () => {
      const next = btn.dataset.route || 'speaker';
      state.audioRoute = next;
      store.set('p2p_audio_route', state.audioRoute);
      document.querySelectorAll('.audio-route-btn').forEach((b) => {
        b.classList.toggle('active', b.dataset.route === state.audioRoute);
      });
      const hint = $('audioRouteHint');
      if (hint) {
        if (state.audioRoute === 'earpiece') {
          hint.textContent = '已選聽筒模式（部分瀏覽器仍從外放播放）';
        } else if (state.audioRoute === 'bluetooth') {
          hint.textContent = '藍牙：瀏覽器通常無法強制路由；請在系統音訊選藍牙耳機';
        } else {
          hint.textContent = '外放模式；戶外建議降低音量或使用耳機';
        }
      }
    };
  });
}

function bindOfflineModePrefUI() {
  const sw = $('offlineModeSwitch');
  if (!sw) return;
  state.offlineFirst = store.get('p2p_offline_first', '0') === '1';
  sw.checked = state.offlineFirst;
  const status = $('offlineModeStatus');
  const refresh = () => {
    if (status) {
      status.textContent = state.offlineFirst
        ? '✓ 無網優先：顯示 QR／貼碼配對，暫不自動連中繼'
        : '依網路狀態自動切換（有網→中繼，無網→QR）';
    }
    if (typeof updateOfflineModeBanner === 'function') updateOfflineModeBanner();
    if (typeof updateDegradeBanner === 'function') updateDegradeBanner();
  };
  sw.onchange = (e) => {
    state.offlineFirst = e.target.checked;
    store.set('p2p_offline_first', state.offlineFirst ? '1' : '0');
    if (state.offlineFirst && typeof ws !== 'undefined' && ws) {
      try { ws.close(); } catch (_) {}
    }
    refresh();
  };
  refresh();
}

function bindMixedTeamUI() {
  const sw = $('mixedTeamSwitch');
  if (!sw) return;
  state.mixedTeam = store.get('p2p_mixed_team', '0') === '1';
  sw.checked = state.mixedTeam;
  document.body.classList.toggle('mixed-team-apk', state.mixedTeam);
  sw.onchange = (e) => {
    state.mixedTeam = e.target.checked;
    store.set('p2p_mixed_team', state.mixedTeam ? '1' : '0');
    document.body.classList.toggle('mixed-team-apk', state.mixedTeam);
    if (state.mixedTeam && typeof setConnMode === 'function') setConnMode('hotspot');
    const ptt = $('pttBtn');
    if (ptt) ptt.title = state.mixedTeam ? '混用模式：請用 WebRTC 配對後按住' : '';
  };
}

function bindAuxRelayUI() {
  const btn = $('auxRelayEnableBtn');
  if (!btn || btn._v83) return;
  btn._v83 = true;
  state.auxRelay = store.get('p2p_aux_relay', '0') === '1';
  const refresh = () => {
    btn.textContent = state.auxRelay ? '✓ 中繼輔助已啟用（有網自動連）' : '有網時啟用中繼輔助';
  };
  refresh();
  btn.onclick = () => {
    state.auxRelay = !state.auxRelay;
    store.set('p2p_aux_relay', state.auxRelay ? '1' : '0');
    refresh();
    if (state.auxRelay && navigator.onLine !== false && typeof connectRelay === 'function') {
      connectRelay(true);
    }
  };
}

function bindAutoRelayUI() {
  const sw = $('autoRelaySwitch');
  if (!sw) return;
  state.autoRelay = store.get('p2p_auto_relay', '1') !== '0';
  sw.checked = state.autoRelay;
  sw.onchange = (e) => {
    state.autoRelay = e.target.checked;
    store.set('p2p_auto_relay', state.autoRelay ? '1' : '0');
  };
}

function maybeAutoMeshBridge() {
  if (!state.autoRelay) return;
  const p2p = typeof rtc !== 'undefined' && rtc.conns.some(c => c.dc && c.dc.readyState === 'open');
  if (p2p) return;
  if (!state.meshBridge && typeof ws !== 'undefined' && ws && ws.readyState === WebSocket.OPEN) {
    const peers = $('onlinePeersWalkie');
    const hasPeers = peers && peers.children.length > 0;
    if (hasPeers) {
      state.meshBridge = true;
      store.set('p2p_mesh_bridge', '1');
      const sw = $('meshBridgeSwitch');
      if (sw) { sw.checked = true; sw.dispatchEvent(new Event('change')); }
    }
  }
}

function bindSettingsRallyShortcuts() {
  const here = $('settingsRallyHereBtn');
  const all = $('settingsRallyAllBtn');
  const mapBtn = $('settingsRallyMapBtn');
  const clearBtn = $('settingsRallyClearBtn');
  if (here && !here._v83) {
    here._v83 = true;
    here.onclick = () => {
      if ($('rallyHereBtn')) $('rallyHereBtn').click();
      else if (!state.self) alert('尚無定位');
      else if (typeof setRallyPoint === 'function') setRallyPoint(state.self.lat, state.self.lon, '集合點');
      syncSettingsRallyList();
    };
  }
  if (all && !all._v83) {
    all._v83 = true;
    all.onclick = () => {
      if ($('rallyAllBtn')) $('rallyAllBtn').click();
      syncSettingsRallyList();
    };
  }
  if (mapBtn && !mapBtn._v107) {
    mapBtn._v107 = true;
    mapBtn.onclick = () => {
      showPage('map');
      if ($('rallyMapBtn')) $('rallyMapBtn').click();
    };
  }
  if (clearBtn && !clearBtn._v107) {
    clearBtn._v107 = true;
    clearBtn.onclick = () => {
      if ($('rallyClearBtn')) $('rallyClearBtn').click();
      syncSettingsRallyList();
    };
  }
}

function syncSettingsRallyList() {
  const src = $('rallyList');
  const dst = $('settingsRallyList');
  if (src && dst) dst.innerHTML = src.innerHTML || '<div class="muted small">尚無集合點</div>';
}

function bindSafetyGotoMapGeofence() {
  const btn = $('safetyGotoMapGeofenceBtn');
  if (!btn || btn._v107) return;
  btn._v107 = true;
  btn.onclick = () => {
    showPage('map');
    $('mapGeofencePreviewCard')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };
}

function bindWalkieStatusTap() {
  const card = $('walkieStatusCard');
  if (!card || card._v83) return;
  card._v83 = true;
  card.style.cursor = 'pointer';
  card.title = '點擊查看連線詳情';
  card.onclick = () => {
    const hb = $('healthBadge');
    const txt = hb ? hb.textContent : '';
    if (txt) alert('連線狀態：' + txt);
  };
}

function bindGotoConnMode() {
  const btn = $('gotoConnModeBtn');
  if (!btn || btn._v83) return;
  btn._v83 = true;
  btn.onclick = () => {
    showPage('settings');
    $('connModeCard')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };
}

function initApkParity() {
  renderFloorCalButtons();
  bindAudioRouteUI();
  bindOfflineModePrefUI();
  bindMixedTeamUI();
  bindAuxRelayUI();
  bindAutoRelayUI();
  bindSettingsRallyShortcuts();
  bindSafetyGotoMapGeofence();
  bindWalkieStatusTap();
  bindGotoConnMode();
  renderPeerLockLists();
  syncSettingsRallyList();
  if (state.auxRelay && navigator.onLine !== false && typeof connectRelay === 'function') {
    const p2p = typeof rtc !== 'undefined' && rtc.conns.some(c => c.dc && c.dc.readyState === 'open');
    if (!p2p) connectRelay(true);
  }
  setInterval(maybeAutoMeshBridge, 12000);
  setInterval(syncSettingsRallyList, 4000);
}

window.renderPeerLockLists = renderPeerLockLists;
window.initApkParity = initApkParity;
window.maybeAutoMeshBridge = maybeAutoMeshBridge;
