// ─── Общее: деактивация всех режимов ────────────────────────────────────────────

function deactivateAllModes() {
  if (routeMode) { routeMode = false; document.getElementById('tb-route').classList.remove('active'); closeSheet('sheet-route'); clearRoute(); }
  if (rulerMode) toggleRuler();
  if (markerMode) toggleMarkerMode();
  if (typeof reconMode !== 'undefined' && reconMode) toggleReconMode();
  if (typeof linkMode !== 'undefined' && linkMode) toggleLinkMode();
  if (typeof scenicMode !== 'undefined' && scenicMode) toggleScenicMode();
  if (window._map) window._map.getCanvas().style.cursor = '';
}

// ─── Утилиты ──────────────────────────────────────────────────────────────────

function formatDuration(seconds) {
  const totalMin = Math.round(seconds / 60);
  if (totalMin < 60) return totalMin + ' мин';
  const days = Math.floor(totalMin / 1440);
  const hours = Math.floor((totalMin % 1440) / 60);
  const mins = totalMin % 60;
  if (days > 0) {
    if (hours === 0 && mins === 0) return `${days} дн`;
    if (mins === 0) return `${days} дн ${hours} ч`;
    return `${days} дн ${hours} ч ${mins} мин`;
  }
  if (mins === 0) return `${hours} ч`;
  return `${hours} ч ${mins} мин`;
}

function formatDist(m) {
  if (!m) return '—';
  if (m >= 1000) return (m / 1000).toFixed(1) + ' км';
  return Math.round(m) + ' м';
}

// ─── Компас ───────────────────────────────────────────────────────────────────
let compassLocked = false;

function toggleCompass() {
  const map = window._map;
  if (!map) return;
  const btn = document.getElementById('btn-compass');
  compassLocked = !compassLocked;
  if (compassLocked) {
    map.rotateTo(0, { duration: 300 });
    map.dragRotate.disable();
    map.touchZoomRotate.disableRotation();
    btn.textContent = '⬆️';
    btn.title = 'Север вверху (нажми для свободного вращения)';
    btn.classList.add('active');
  } else {
    map.dragRotate.enable();
    map.touchZoomRotate.enableRotation();
    btn.textContent = '🧭';
    btn.title = 'Свободное вращение';
    btn.classList.remove('active');
  }
}

// ─── Геолокация ───────────────────────────────────────────────────────────────
let locationMarker = null;

function locateMe() {
  if (!navigator.geolocation) {
    alert('Геолокация недоступна в этом браузере');
    return;
  }
  const btn = document.getElementById('btn-locate-x');
  btn.textContent = '⏳';
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      const { longitude, latitude } = pos.coords;
      const map = window._map;
      btn.textContent = '🎯';
      map.flyTo({ center: [longitude, latitude], zoom: 13, duration: 800 });
      if (locationMarker) {
        locationMarker.setLngLat([longitude, latitude]);
      } else {
        const el = document.createElement('div');
        el.className = 'my-location-marker';
        el.innerHTML = '<div class="my-location-dot"></div><div class="my-location-pulse"></div>';
        locationMarker = new maplibregl.Marker({ element: el, anchor: 'center' })
          .setLngLat([longitude, latitude])
          .addTo(map);
      }
    },
    (err) => {
      btn.textContent = '🎯';
      alert('Не удалось определить местоположение: ' + err.message);
    },
    { enableHighAccuracy: true, timeout: 10000 }
  );
}

// ─── Layer visibility state ───────────────────────────────────────────────────
const layerState = {
  tracks: true,
  paths: true,
  poi: true,
  basemap: true,
};

const layerGroups = {
  tracks:  ['trails-track', 'trails-asphalt'],
  paths:   ['trails-path-bridleway'],
  poi:     ['poi-circles', 'poi-labels'],
  basemap: ['osm-base'],
};

function toggleLayer(group) {
  layerState[group] = !layerState[group];
  const btn = document.getElementById('btn-' + group);
  btn.classList.toggle('active', layerState[group]);
  const visibility = layerState[group] ? 'visible' : 'none';
  layerGroups[group].forEach(id => {
    if (window._map && window._map.getLayer(id)) {
      window._map.setLayoutProperty(id, 'visibility', visibility);
    }
  });
}


// ─── Роутинг — состояние ──────────────────────────────────────────────────────
const ROUTE_COLORS = ['#0066ff', '#00aa44', '#9933cc', '#ff8800', '#888888'];

let routeMode = false;
let routeWaypoints = [];      // [{lon, lat}, ...]
let routeResults = [];        // массив маршрутов из API
let activeRouteIdx = 0;
let waypointMarkers = [];     // MapLibre маркеры точек
let addingWaypoint = false;   // режим добавления промежуточной точки
let buildDebounceTimer = null;

function getBasePath() {
  return window.location.pathname.replace(/\/[^/]*$/, '') || '';
}

// ─── Режим маршрута ───────────────────────────────────────────────────────────
function toggleRouteMode() {
  routeMode = !routeMode;
  const btn = document.getElementById('tb-route');
  const panel = document.getElementById('route-panel');
  if (routeMode) {
    deactivateAllModes();
    routeMode = true;
    btn.classList.add('active');
    panel.style.display = 'block';
    clearRoute();
    window._map.getCanvas().style.cursor = 'crosshair';
  } else {
    btn.classList.remove('active');
    panel.style.display = 'none';
    clearRoute();
    window._map.getCanvas().style.cursor = '';
  }
}

function clearRoute() {
  // Убираем маркеры точек
  waypointMarkers.forEach(m => m.remove());
  waypointMarkers = [];
  routeWaypoints = [];
  routeResults = [];
  activeRouteIdx = 0;
  addingWaypoint = false;

  // Убираем слои маршрутов
  const map = window._map;
  if (map) {
    for (let i = 0; i < 5; i++) {
      if (map.getLayer('route-line-' + i)) map.removeLayer('route-line-' + i);
      if (map.getLayer('route-line-' + i + '-outline')) map.removeLayer('route-line-' + i + '-outline');
    }
    if (map.getSource('route')) map.removeSource('route');
    for (let i = 0; i < 5; i++) {
      if (map.getSource('route-' + i)) map.removeSource('route-' + i);
    }
  }

  document.getElementById('route-status').textContent = 'Кликни точку старта';
  document.getElementById('route-actions').style.display = 'none';
  document.getElementById('route-cards').innerHTML = '';
  document.getElementById('waypoints-list').innerHTML = '';
  document.getElementById('btn-add-waypoint').style.display = '';

  if (routeMode && map) map.getCanvas().style.cursor = 'crosshair';
}

// ─── Добавление промежуточной точки ──────────────────────────────────────────
function startAddWaypoint() {
  if (routeWaypoints.length >= 10) return;
  addingWaypoint = true;
  window._map.getCanvas().style.cursor = 'crosshair';
  document.getElementById('route-status').textContent = 'Кликни на карте для добавления точки';
}

// ─── Маркеры точек ────────────────────────────────────────────────────────────
function createWaypointMarkerEl(index, total) {
  const el = document.createElement('div');
  el.className = 'route-waypoint-marker';
  let bg, text, color = '#fff';
  if (index === 0) {
    bg = '#00aa44'; text = 'A';
    el.style.cssText = `width:22px;height:22px;background:${bg};border:2px solid #fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:${color};box-shadow:0 1px 4px rgba(0,0,0,0.3);cursor:grab;`;
  } else if (index === total - 1) {
    bg = '#cc0000'; text = 'B';
    el.style.cssText = `width:22px;height:22px;background:${bg};border:2px solid #fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:${color};box-shadow:0 1px 4px rgba(0,0,0,0.3);cursor:grab;`;
  } else {
    text = String(index);
    el.style.cssText = `width:18px;height:18px;background:#fff;border:2px solid #0066ff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;color:#0066ff;box-shadow:0 1px 4px rgba(0,0,0,0.3);cursor:grab;`;
  }
  el.textContent = text;
  return el;
}

function rebuildWaypointMarkers() {
  waypointMarkers.forEach(m => m.remove());
  waypointMarkers = [];
  const map = window._map;
  routeWaypoints.forEach((wp, i) => {
    const el = createWaypointMarkerEl(i, routeWaypoints.length);
    const marker = new maplibregl.Marker({ element: el, anchor: 'center', draggable: true })
      .setLngLat([wp.lon, wp.lat])
      .addTo(map);

    // Захватываем индекс в замыкании
    (function(idx) {
      marker.on('dragend', () => {
        const lngLat = marker.getLngLat();
        routeWaypoints[idx] = { lon: lngLat.lng, lat: lngLat.lat };
        renderWaypointsList();
        debounceBuildRoute();
      });
    })(i);

    waypointMarkers.push(marker);
  });
}

function renderWaypointsList() {
  const list = document.getElementById('waypoints-list');
  if (!routeWaypoints.length) { list.innerHTML = ''; return; }

  list.innerHTML = routeWaypoints.map((wp, i) => {
    let labelClass, labelText;
    if (i === 0) { labelClass = 'start'; labelText = 'A'; }
    else if (i === routeWaypoints.length - 1) { labelClass = 'end'; labelText = 'B'; }
    else { labelClass = 'mid'; labelText = String(i); }

    return `<div class="waypoint-row" draggable="true"
      ondragstart="onWpDragStart(event,${i})"
      ondragover="onWpDragOver(event,${i})"
      ondrop="onWpDrop(event,${i})"
      ondragleave="onWpDragLeave(event)">
      <span class="waypoint-label ${labelClass}">${labelText}</span>
      <span class="waypoint-coords">${wp.lat.toFixed(4)}, ${wp.lon.toFixed(4)}</span>
      <button class="waypoint-remove" onclick="removeWaypoint(${i})" title="Удалить точку">✕</button>
    </div>`;
  }).join('');

  // Показываем/скрываем кнопку добавления
  document.getElementById('btn-add-waypoint').style.display =
    routeWaypoints.length >= 10 ? 'none' : '';
}

// ─── Drag-and-drop порядка точек ──────────────────────────────────────────────
let dragWpIdx = null;

function onWpDragStart(e, idx) {
  dragWpIdx = idx;
  e.dataTransfer.effectAllowed = 'move';
}

function onWpDragOver(e, idx) {
  e.preventDefault();
  e.dataTransfer.dropEffect = 'move';
  document.querySelectorAll('.waypoint-row').forEach((r, i) => {
    r.classList.toggle('drag-over', i === idx);
  });
}

function onWpDragLeave(e) {
  e.currentTarget.classList.remove('drag-over');
}

function onWpDrop(e, idx) {
  e.preventDefault();
  document.querySelectorAll('.waypoint-row').forEach(r => r.classList.remove('drag-over'));
  if (dragWpIdx === null || dragWpIdx === idx) return;
  const moved = routeWaypoints.splice(dragWpIdx, 1)[0];
  routeWaypoints.splice(idx, 0, moved);
  dragWpIdx = null;
  rebuildWaypointMarkers();
  renderWaypointsList();
  if (routeWaypoints.length >= 2) debounceBuildRoute();
}

function removeWaypoint(idx) {
  routeWaypoints.splice(idx, 1);
  rebuildWaypointMarkers();
  renderWaypointsList();
  if (routeWaypoints.length >= 2) {
    debounceBuildRoute();
  } else {
    // Убираем маршруты с карты
    const map = window._map;
    for (let i = 0; i < 5; i++) {
      if (map.getLayer('route-line-' + i)) map.removeLayer('route-line-' + i);
      if (map.getLayer('route-line-' + i + '-outline')) map.removeLayer('route-line-' + i + '-outline');
      if (map.getSource('route-' + i)) map.removeSource('route-' + i);
    }
    routeResults = [];
    document.getElementById('route-cards').innerHTML = '';
    document.getElementById('route-actions').style.display =
      routeWaypoints.length >= 2 ? 'block' : 'none';
    document.getElementById('route-status').textContent =
      routeWaypoints.length === 0 ? 'Кликни точку старта' :
      routeWaypoints.length === 1 ? 'Кликни точку финиша' : '';
  }
}


// ─── Построение маршрута ──────────────────────────────────────────────────────
function debounceBuildRoute() {
  clearTimeout(buildDebounceTimer);
  buildDebounceTimer = setTimeout(buildRoute, 300);
}

async function buildRoute() {
  if (routeWaypoints.length < 2) return;
  const map = window._map;
  const basePath = getBasePath();

  document.getElementById('route-status').textContent = '⏳ Строю маршрут...';
  const btn = document.getElementById('btn-build-route');
  if (btn) btn.textContent = '⏳ Строю...';

  try {
    const resp = await fetch(basePath + '/api/route', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ waypoints: routeWaypoints, alternatives: 5 }),
    });
    if (!resp.ok) throw new Error('Маршрут не найден');
    const data = await resp.json();
    routeResults = data.routes || [];
    if (!routeResults.length) throw new Error('Маршрут не найден');

    // Убираем старые слои
    for (let i = 0; i < 5; i++) {
      if (map.getLayer('route-line-' + i)) map.removeLayer('route-line-' + i);
      if (map.getLayer('route-line-' + i + '-outline')) map.removeLayer('route-line-' + i + '-outline');
      if (map.getSource('route-' + i)) map.removeSource('route-' + i);
    }

    // Рисуем все маршруты
    routeResults.forEach((route, i) => {
      const color = ROUTE_COLORS[i] || '#888888';
      const isActive = i === activeRouteIdx;
      map.addSource('route-' + i, {
        type: 'geojson',
        data: { type: 'Feature', geometry: route.geometry, properties: {} }
      });
      // Обводка (белая) для активного
      map.addLayer({
        id: 'route-line-' + i + '-outline',
        type: 'line',
        source: 'route-' + i,
        paint: {
          'line-color': '#ffffff',
          'line-width': isActive ? 7 : 4,
          'line-opacity': isActive ? 0.6 : 0,
        },
        layout: { 'line-cap': 'round', 'line-join': 'round' }
      });
      map.addLayer({
        id: 'route-line-' + i,
        type: 'line',
        source: 'route-' + i,
        paint: {
          'line-color': color,
          'line-width': isActive ? 5 : 3,
          'line-opacity': isActive ? 0.95 : 0.5,
        },
        layout: { 'line-cap': 'round', 'line-join': 'round' }
      });

      // Клик на линию маршрута
      map.on('click', 'route-line-' + i, (e) => {
        e.stopPropagation ? e.stopPropagation() : null;
        selectRoute(i);
      });
      map.on('mouseenter', 'route-line-' + i, () => {
        map.getCanvas().style.cursor = 'pointer';
        highlightRoute(i);
      });
      map.on('mouseleave', 'route-line-' + i, () => {
        map.getCanvas().style.cursor = routeMode ? 'crosshair' : '';
        unhighlightRoute(i);
      });
    });

    activeRouteIdx = 0;
    renderRouteCards(routeResults);
    document.getElementById('route-status').textContent = `✅ ${routeResults.length} маршрут(ов)`;
    document.getElementById('route-actions').style.display = 'block';

  } catch(e) {
    document.getElementById('route-status').textContent = '❌ ' + e.message;
  }

  if (btn) btn.textContent = '🗺️ Построить маршрут';
}

// ─── Выбор и подсветка маршрутов ─────────────────────────────────────────────
function selectRoute(idx) {
  activeRouteIdx = idx;
  const map = window._map;
  routeResults.forEach((_, i) => {
    const isActive = i === idx;
    if (map.getLayer('route-line-' + i)) {
      map.setPaintProperty('route-line-' + i, 'line-width', isActive ? 5 : 3);
      map.setPaintProperty('route-line-' + i, 'line-opacity', isActive ? 0.95 : 0.5);
    }
    if (map.getLayer('route-line-' + i + '-outline')) {
      map.setPaintProperty('route-line-' + i + '-outline', 'line-width', isActive ? 7 : 4);
      map.setPaintProperty('route-line-' + i + '-outline', 'line-opacity', isActive ? 0.6 : 0);
    }
  });
  // Обновляем CSS карточек
  document.querySelectorAll('.route-card').forEach((card, i) => {
    card.classList.toggle('active', i === idx);
  });
}

function highlightRoute(idx) {
  const map = window._map;
  if (map.getLayer('route-line-' + idx)) {
    map.setPaintProperty('route-line-' + idx, 'line-width', 7);
    map.setPaintProperty('route-line-' + idx, 'line-opacity', 1);
  }
}

function unhighlightRoute(idx) {
  const isActive = idx === activeRouteIdx;
  const map = window._map;
  if (map.getLayer('route-line-' + idx)) {
    map.setPaintProperty('route-line-' + idx, 'line-width', isActive ? 5 : 3);
    map.setPaintProperty('route-line-' + idx, 'line-opacity', isActive ? 0.95 : 0.5);
  }
}

// ─── Карточки маршрутов ───────────────────────────────────────────────────────
function renderRouteCards(routes) {
  const container = document.getElementById('route-cards');
  container.innerHTML = routes.map((route, i) => {
    const color = ROUTE_COLORS[i] || '#888888';
    const distKm = (route.distance_m / 1000).toFixed(1);
    const timeStr = formatDuration(route.duration_s);
    const isActive = i === activeRouteIdx;

    let barHtml = '';
    let summaryHtml = '';
    let detailsHtml = '';

    if (route.stats) {
      const s = route.stats;
      barHtml = `
        <div class="route-coverage-bar">
          <div style="width:${s.track_lev12_pct}%;background:#FFD700" title="Lev1-2: ${(s.track_lev12_m/1000).toFixed(1)} км"></div>
          <div style="width:${s.track_lev345_pct}%;background:#FF4400" title="Lev3-5: ${(s.track_lev345_m/1000).toFixed(1)} км"></div>
          <div style="width:${s.path_pct}%;background:#cc0000" title="Тропы: ${(s.path_m/1000).toFixed(1)} км"></div>
          <div style="width:${s.asphalt_pct}%;background:#aaaaaa" title="Асфальт: ${(s.asphalt_m/1000).toFixed(1)} км"></div>
        </div>`;
      summaryHtml = `<div class="route-card-summary">${s.dirt_total_pct}% грунт · ${s.asphalt_pct}% асфальт</div>`;
      detailsHtml = `
        <div class="route-card-details" id="route-details-${i}" style="display:none;">
          <div class="route-stat-row">🟡 Lev1-2 &nbsp; ${(s.track_lev12_m/1000).toFixed(1)} км &nbsp; ${s.track_lev12_pct}%</div>
          <div class="route-stat-row">🔴 Lev3-5 &nbsp; ${(s.track_lev345_m/1000).toFixed(1)} км &nbsp; ${s.track_lev345_pct}%</div>
          <div class="route-stat-row">🔴 Тропы &nbsp; ${(s.path_m/1000).toFixed(1)} км &nbsp; ${s.path_pct}%</div>
          <div class="route-stat-row">⬜ Асфальт &nbsp; ${(s.asphalt_m/1000).toFixed(1)} км &nbsp; ${s.asphalt_pct}%</div>
          <div style="margin-top:6px;display:flex;gap:6px;">
            <button onclick="event.stopPropagation();downloadGPX()"
              style="flex:1;padding:4px;background:#f0f0f0;border:1px solid #ccc;border-radius:4px;cursor:pointer;font-size:11px;">
              📥 GPX
            </button>
            <button onclick="event.stopPropagation();selectRoute(${i})"
              style="flex:1;padding:4px;background:#ff6600;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">
              Выбрать
            </button>
          </div>
        </div>
        <button class="route-details-toggle" onclick="event.stopPropagation();toggleRouteDetails(${i})">Подробнее ▼</button>`;
    } else {
      detailsHtml = `
        <div class="route-card-details" id="route-details-${i}" style="display:none;">
          <div style="margin-top:6px;display:flex;gap:6px;">
            <button onclick="event.stopPropagation();downloadGPX()"
              style="flex:1;padding:4px;background:#f0f0f0;border:1px solid #ccc;border-radius:4px;cursor:pointer;font-size:11px;">
              📥 GPX
            </button>
            <button onclick="event.stopPropagation();selectRoute(${i})"
              style="flex:1;padding:4px;background:#ff6600;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">
              Выбрать
            </button>
          </div>
        </div>
        <button class="route-details-toggle" onclick="event.stopPropagation();toggleRouteDetails(${i})">Подробнее ▼</button>`;
    }

    return `<div class="route-card${isActive ? ' active' : ''}" id="route-card-${i}"
      onclick="selectRoute(${i})"
      onmouseenter="highlightRoute(${i})"
      onmouseleave="unhighlightRoute(${i})">
      <div class="route-card-header">
        <span class="route-color-dot" style="background:${color}"></span>
        <span class="route-card-title">Вариант ${i + 1}</span>
        <span class="route-card-dist">${distKm} км</span>
        <span class="route-card-time">${timeStr}</span>
      </div>
      ${barHtml}
      ${summaryHtml}
      ${detailsHtml}
    </div>`;
  }).join('');
}

function toggleRouteDetails(idx) {
  const details = document.getElementById('route-details-' + idx);
  const btn = details ? details.nextElementSibling : null;
  if (!details) return;
  const isOpen = details.style.display !== 'none';
  details.style.display = isOpen ? 'none' : 'block';
  if (btn) btn.textContent = isOpen ? 'Подробнее ▼' : 'Свернуть ▲';
}


// ─── GPX экспорт ─────────────────────────────────────────────────────────────
function escapeXml(str) {
  return (str || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

function downloadGPX() {
  const route = routeResults[activeRouteIdx];
  if (!route) return;

  const now = new Date();
  const dateStr = now.toISOString().slice(0, 10);
  const timeStr = now.toISOString().replace(/[-:]/g, '').slice(0, 15);
  const filename = `enduro-${timeStr}.gpx`;

  const distKm = (route.distance_m / 1000).toFixed(1);
  const dirtPct = route.stats ? route.stats.dirt_total_pct : '?';

  // Waypoints: точки маршрута
  const wpts = routeWaypoints.map((wp, i) => {
    const name = i === 0 ? 'Старт' : i === routeWaypoints.length - 1 ? 'Финиш' : `Точка ${i}`;
    return `  <wpt lat="${wp.lat}" lon="${wp.lon}"><name>${escapeXml(name)}</name></wpt>`;
  });

  // Добавить флажки из localStorage
  const markers = loadMarkers();
  markers.forEach(m => {
    wpts.push(`  <wpt lat="${m.lat}" lon="${m.lon}"><name>${escapeXml(m.name)}</name><sym>${escapeXml(m.icon)}</sym></wpt>`);
  });

  // Трек
  const trkpts = route.geometry.coordinates.map(([lon, lat]) =>
    `      <trkpt lat="${lat}" lon="${lon}"/>`
  ).join('\n');

  const gpx = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Enduro Trails" xmlns="http://www.topografix.com/GPX/1/1">
  <metadata>
    <name>Enduro route ${dateStr}</name>
    <desc>${distKm} км · ${dirtPct}% грунт</desc>
    <time>${now.toISOString()}</time>
  </metadata>
${wpts.join('\n')}
  <trk>
    <name>Enduro route ${dateStr}</name>
    <trkseg>
${trkpts}
    </trkseg>
  </trk>
</gpx>`;

  const blob = new Blob([gpx], { type: 'application/gpx+xml' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

// ─── Флажки / именованные метки ──────────────────────────────────────────────
const MARKER_ICONS = ['🚩', '⛺', '🔧', '⛽', '💧', '📍'];
const MARKERS_KEY = 'enduro_markers';
let markerMode = false;
let namedMarkerObjects = {}; // id -> MapLibre Marker

function loadMarkers() {
  try {
    return JSON.parse(localStorage.getItem(MARKERS_KEY) || '[]');
  } catch(e) {
    return [];
  }
}

function saveMarkers(markers) {
  try {
    localStorage.setItem(MARKERS_KEY, JSON.stringify(markers));
  } catch(e) {
    console.warn('localStorage недоступен');
  }
}

function toggleMarkerMode() {
  markerMode = !markerMode;
  const btn = document.getElementById('tb-marker');
  if (markerMode) {
    deactivateAllModes();
    markerMode = true;
    btn.classList.add('active');
    window._map.getCanvas().style.cursor = 'crosshair';
  } else {
    btn.classList.remove('active');
    window._map.getCanvas().style.cursor = '';
  }
}

function addMarker(lngLat) {
  const markers = loadMarkers();
  if (markers.length >= 50) {
    alert('Достигнут лимит 50 меток');
    return;
  }

  // Простой диалог выбора иконки и имени
  const iconChoice = promptIconChoice();
  if (iconChoice === null) return; // отмена

  const rawName = prompt('Название метки (Enter = автоимя):');
  if (rawName === null) return; // отмена
  const autoName = rawName.trim() || `Метка ${markers.length + 1}`;

  const marker = {
    id: Date.now(),
    name: autoName,
    icon: iconChoice,
    lat: lngLat.lat,
    lon: lngLat.lng
  };
  markers.push(marker);
  saveMarkers(markers);
  drawNamedMarker(marker);
}

function promptIconChoice() {
  const msg = 'Выберите иконку:\n' + MARKER_ICONS.map((ic, i) => `${i+1}. ${ic}`).join('\n') + '\n\nВведите номер (1-6) или Enter для 🚩:';
  const input = prompt(msg);
  if (input === null) return null;
  const idx = parseInt(input, 10) - 1;
  if (idx >= 0 && idx < MARKER_ICONS.length) return MARKER_ICONS[idx];
  return MARKER_ICONS[0];
}

function drawNamedMarker(markerData) {
  const map = window._map;
  const el = document.createElement('div');
  el.className = 'named-marker-el';
  el.textContent = markerData.icon;
  el.title = markerData.name;

  const popup = new maplibregl.Popup({ offset: 25, closeButton: true })
    .setHTML(`
      <div class="popup-title">${escapeXml(markerData.name)}</div>
      <div class="popup-row"><span class="popup-key">Координаты</span><span class="popup-val">${markerData.lat.toFixed(5)}, ${markerData.lon.toFixed(5)}</span></div>
      <div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap;">
        <button onclick="useMarkerAsA(${markerData.id})" style="flex:1;padding:3px 6px;background:#00aa44;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">→ Точка A</button>
        <button onclick="useMarkerAsB(${markerData.id})" style="flex:1;padding:3px 6px;background:#cc0000;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">→ Точка B</button>
        <button onclick="removeMarker(${markerData.id})" style="flex:1;padding:3px 6px;background:#f0f0f0;border:1px solid #ccc;border-radius:4px;cursor:pointer;font-size:11px;">🗑 Удалить</button>
      </div>
    `);

  const mlMarker = new maplibregl.Marker({ element: el, anchor: 'bottom' })
    .setLngLat([markerData.lon, markerData.lat])
    .setPopup(popup)
    .addTo(map);

  el.addEventListener('click', () => mlMarker.togglePopup());
  namedMarkerObjects[markerData.id] = mlMarker;
}

function renderMarkers() {
  const markers = loadMarkers();
  markers.forEach(m => drawNamedMarker(m));
}

function removeMarker(id) {
  if (namedMarkerObjects[id]) {
    namedMarkerObjects[id].remove();
    delete namedMarkerObjects[id];
  }
  const markers = loadMarkers().filter(m => m.id !== id);
  saveMarkers(markers);
}

function useMarkerAsA(id) {
  const markers = loadMarkers();
  const m = markers.find(x => x.id === id);
  if (!m) return;
  if (!routeMode) {
    toggleRouteMode();
  }
  if (routeWaypoints.length === 0) {
    routeWaypoints.push({ lon: m.lon, lat: m.lat });
  } else {
    routeWaypoints[0] = { lon: m.lon, lat: m.lat };
  }
  rebuildWaypointMarkers();
  renderWaypointsList();
  updateRouteActionsVisibility();
  if (routeWaypoints.length >= 2) debounceBuildRoute();
  // Закрыть попап
  if (namedMarkerObjects[id]) namedMarkerObjects[id].getPopup().remove();
}

function useMarkerAsB(id) {
  const markers = loadMarkers();
  const m = markers.find(x => x.id === id);
  if (!m) return;
  if (!routeMode) {
    toggleRouteMode();
  }
  if (routeWaypoints.length === 0) {
    routeWaypoints.push({ lon: m.lon, lat: m.lat });
    routeWaypoints.push({ lon: m.lon, lat: m.lat });
  } else if (routeWaypoints.length === 1) {
    routeWaypoints.push({ lon: m.lon, lat: m.lat });
  } else {
    routeWaypoints[routeWaypoints.length - 1] = { lon: m.lon, lat: m.lat };
  }
  rebuildWaypointMarkers();
  renderWaypointsList();
  updateRouteActionsVisibility();
  if (routeWaypoints.length >= 2) debounceBuildRoute();
  if (namedMarkerObjects[id]) namedMarkerObjects[id].getPopup().remove();
}

function clearAllMarkers() {
  if (!confirm('Удалить все метки?')) return;
  Object.values(namedMarkerObjects).forEach(m => m.remove());
  namedMarkerObjects = {};
  saveMarkers([]);
}

function updateRouteActionsVisibility() {
  document.getElementById('route-actions').style.display =
    routeWaypoints.length >= 2 ? 'block' : 'none';
  document.getElementById('route-status').textContent =
    routeWaypoints.length === 0 ? 'Кликни точку старта' :
    routeWaypoints.length === 1 ? 'Кликни точку финиша' : '';
}


// ─── Map init ─────────────────────────────────────────────────────────────────
async function initMap() {
  const basePath = window.location.pathname.replace(/\/[^/]*$/, '') || '';
  const tileBase = window.location.origin + basePath;
  const style = await fetch(basePath + '/style.json').then(r => r.json());
  style.sources['trails-tiles'].tiles = [`${tileBase}/api/tiles/{z}/{x}/{y}.mvt`];

  const map = new maplibregl.Map({
    container: 'map',
    style: style,
    center: [40.5, 55.5],
    zoom: 7,
    minZoom: 4,
    maxZoom: 18,
    hash: true,
  });
  window._map = map;

  map.addControl(new maplibregl.NavigationControl(), 'top-left');
  map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'bottom-right');
  map.addControl(new maplibregl.FullscreenControl(), 'top-left');

  map.on('load', () => {
    document.getElementById('loading').classList.remove('visible');
    checkDataAvailability();
    initRouteClicks(map);
    initRulerClicks(map);
    initSearch();
    renderMarkers();
  });

  map.on('error', (e) => {
    console.error('Map error:', e.error?.message || e);
    document.getElementById('loading').classList.remove('visible');
  });

  setTimeout(() => {
    document.getElementById('loading').classList.remove('visible');
  }, 15000);

  map.on('zoom', () => {
    document.getElementById('zoom-val').textContent = map.getZoom().toFixed(1);
  });

  map.on('mousemove', (e) => {
    const { lng, lat } = e.lngLat;
    document.getElementById('coords-val').textContent =
      `${lat.toFixed(4)}, ${lng.toFixed(4)}`;
  });

  const popup = new maplibregl.Popup({
    closeButton: true,
    closeOnClick: false,
    maxWidth: '300px',
  });

  function formatLength(m) {
    if (!m) return '—';
    if (m >= 1000) return (m / 1000).toFixed(1) + ' км';
    return Math.round(m) + ' м';
  }

  function poiTypeLabel(t) {
    const labels = {
      'natural=peak': '⛰ Вершина',
      'natural=water': '💧 Вода',
      'tourism=viewpoint': '👁 Смотровая',
      'historic=ruins': '🏙 Руины',
      'natural=cave_entrance': '🕳 Пещера',
      'ford=yes': '🌊 Брод',
    };
    return labels[t] || t;
  }

  ['trails-track', 'trails-path-bridleway', 'trails-asphalt'].forEach(layerId => {
    map.on('click', layerId, (e) => {
      // Не показываем попап трека если активен режим маршрута или линейки
      if (routeMode || rulerMode || markerMode) return;
      const props = e.features[0].properties;
      const html = `
        <div class="popup-title">${props.name || 'Без названия'}</div>
        <div class="popup-row"><span class="popup-key">Тип</span><span class="popup-val">${props.highway || '—'}</span></div>
        <div class="popup-row"><span class="popup-key">Покрытие</span><span class="popup-val">${props.surface || '—'}</span></div>
        <div class="popup-row"><span class="popup-key">Категория</span><span class="popup-val">${props.tracktype || '—'}</span></div>
        <div class="popup-row"><span class="popup-key">Длина</span><span class="popup-val">${formatLength(props.length_m)}</span></div>
        ${props.mtb_scale ? `<div class="popup-row"><span class="popup-key">MTB scale</span><span class="popup-val">${props.mtb_scale}</span></div>` : ''}
      `;
      popup.setLngLat(e.lngLat).setHTML(html).addTo(map);
    });
    map.on('mouseenter', layerId, () => {
      if (!routeMode && !rulerMode && !markerMode) map.getCanvas().style.cursor = 'pointer';
    });
    map.on('mouseleave', layerId, () => {
      if (!routeMode && !rulerMode && !markerMode) map.getCanvas().style.cursor = '';
    });
  });

  map.on('click', 'poi-circles', (e) => {
    if (routeMode || rulerMode || markerMode) return;
    const props = e.features[0].properties;
    const html = `
      <div class="popup-title">${props.name || 'Без названия'}</div>
      <div class="popup-row"><span class="popup-key">Тип</span><span class="popup-val">${poiTypeLabel(props.poi_type)}</span></div>
    `;
    popup.setLngLat(e.lngLat).setHTML(html).addTo(map);
  });
  map.on('mouseenter', 'poi-circles', () => {
    if (!routeMode && !rulerMode && !markerMode) map.getCanvas().style.cursor = 'pointer';
  });
  map.on('mouseleave', 'poi-circles', () => {
    if (!routeMode && !rulerMode && !markerMode) map.getCanvas().style.cursor = '';
  });

  map.on('click', (e) => {
    if (routeMode || rulerMode || markerMode) return;
    const features = map.queryRenderedFeatures(e.point, {
      layers: ['trails-track', 'trails-path-bridleway', 'trails-asphalt', 'poi-circles'],
    });
    if (!features.length) popup.remove();
  });
}

async function checkDataAvailability() {
  try {
    const basePath = window.location.pathname.replace(/\/[^/]*$/, '') || '';
    const resp = await fetch(basePath + '/api/health');
    const data = await resp.json();
    if (!data.db_exists) {
      document.getElementById('no-data-warning').classList.add('visible');
    }
  } catch (e) {
    console.warn('Health check failed:', e);
  }
}

// ─── Клики на карте (маршрут + метки) ────────────────────────────────────────
function initRouteClicks(map) {
  map.on('click', (e) => {
    const { lng, lat } = e.lngLat;

    // Режим Разведки
    if (reconMode) {
      doRecon(lng, lat);
      return;
    }

    // Режим Связки
    if (linkMode) {
      addLinkPoint(lng, lat);
      return;
    }

    // Режим Красивого маршрута
    if (scenicMode) {
      scenicStart = { lon: lng, lat: lat };
      document.getElementById('scenic-status').textContent = `📍 Старт: ${lat.toFixed(4)}, ${lng.toFixed(4)}`;
      if (scenicStartMarker) scenicStartMarker.remove();
      const el = document.createElement('div');
      el.style.cssText = 'width:16px;height:16px;background:#ff6600;border:2px solid #fff;border-radius:50%;box-shadow:0 1px 4px rgba(0,0,0,0.3);';
      scenicStartMarker = new maplibregl.Marker({ element: el, anchor: 'center' }).setLngLat([lng, lat]).addTo(map);
      return;
    }

    // Режим добавления метки
    if (markerMode) {
      addMarker(e.lngLat);
      toggleMarkerMode();
      return;
    }

    if (!routeMode) return;

    // Режим добавления промежуточной точки
    if (addingWaypoint) {
      addingWaypoint = false;
      map.getCanvas().style.cursor = 'crosshair';
      // Вставляем перед последней точкой (B)
      if (routeWaypoints.length >= 2) {
        routeWaypoints.splice(routeWaypoints.length - 1, 0, { lon: lng, lat: lat });
      } else {
        routeWaypoints.push({ lon: lng, lat: lat });
      }
      rebuildWaypointMarkers();
      renderWaypointsList();
      updateRouteActionsVisibility();
      if (routeWaypoints.length >= 2) debounceBuildRoute();
      return;
    }

    // Обычный режим: A → B
    if (routeWaypoints.length === 0) {
      routeWaypoints.push({ lon: lng, lat: lat });
      rebuildWaypointMarkers();
      renderWaypointsList();
      document.getElementById('route-status').textContent = 'Кликни точку финиша';
    } else if (routeWaypoints.length === 1) {
      routeWaypoints.push({ lon: lng, lat: lat });
      rebuildWaypointMarkers();
      renderWaypointsList();
      updateRouteActionsVisibility();
      buildRoute();
    }
    // Если уже 2+ точек — клик ничего не делает (используй "+ Точка")
  });
}

// ─── Поиск (Nominatim) ────────────────────────────────────────────────────────
let searchTimeout = null;

function initSearch() {
  const input = document.getElementById('search-input');
  const results = document.getElementById('search-results');
  input.addEventListener('input', () => {
    clearTimeout(searchTimeout);
    const q = input.value.trim();
    if (q.length < 2) { results.style.display = 'none'; return; }
    searchTimeout = setTimeout(() => doSearch(q), 400);
  });
  input.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') { results.style.display = 'none'; input.blur(); }
  });
  document.addEventListener('click', (e) => {
    if (!e.target.closest('#search-box')) results.style.display = 'none';
  });
}

async function doSearch(query) {
  const results = document.getElementById('search-results');
  results.innerHTML = '<div class="search-result-item" style="color:#888">Поиск...</div>';
  results.style.display = 'block';
  try {
    const url = `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&limit=6&countrycodes=ru&accept-language=ru`;
    const resp = await fetch(url, { headers: { 'Accept-Language': 'ru' } });
    const data = await resp.json();
    if (!data.length) {
      results.innerHTML = '<div class="search-result-item" style="color:#888">Ничего не найдено</div>';
      return;
    }
    results.innerHTML = data.map((item) => {
      const name = item.display_name.split(',')[0];
      const detail = item.display_name.split(',').slice(1, 3).join(',').trim();
      return `<div class="search-result-item" onclick="selectSearchResult(${item.lat}, ${item.lon}, '${name.replace(/'/g, "\\'")}')">
        <div class="search-result-name">${name}</div>
        <div class="search-result-detail">${detail}</div>
      </div>`;
    }).join('');
  } catch(e) {
    results.innerHTML = '<div class="search-result-item" style="color:#c00">Ошибка поиска</div>';
  }
}

function selectSearchResult(lat, lon, name) {
  window._map.flyTo({ center: [lon, lat], zoom: 13, duration: 800 });
  document.getElementById('search-results').style.display = 'none';
  document.getElementById('search-input').value = name;
}

// ─── Линейка ──────────────────────────────────────────────────────────────────
let rulerMode = false;
let rulerPoints = [];
let rulerMarkers = [];
let rulerTotal = 0;

function toggleRuler() {
  rulerMode = !rulerMode;
  const btn = document.getElementById('tb-ruler');
  if (rulerMode) {
    deactivateAllModes();
    rulerMode = true;
    btn.classList.add('active');
    window._map.getCanvas().style.cursor = 'crosshair';
    clearRuler();
  } else {
    btn.classList.remove('active');
    window._map.getCanvas().style.cursor = '';
    clearRuler();
  }
}

function clearRuler() {
  rulerPoints = [];
  rulerTotal = 0;
  rulerMarkers.forEach(m => m.remove());
  rulerMarkers = [];
  const map = window._map;
  if (map.getLayer('ruler-line')) map.removeLayer('ruler-line');
  if (map.getSource('ruler')) map.removeSource('ruler');
}

function haversineKm(a, b) {
  const R = 6371;
  const dLat = (b[1] - a[1]) * Math.PI / 180;
  const dLon = (b[0] - a[0]) * Math.PI / 180;
  const s = Math.sin(dLat/2)**2 + Math.cos(a[1]*Math.PI/180) * Math.cos(b[1]*Math.PI/180) * Math.sin(dLon/2)**2;
  return R * 2 * Math.atan2(Math.sqrt(s), Math.sqrt(1-s));
}

function updateRulerLine() {
  const map = window._map;
  const geojson = { type: 'Feature', geometry: { type: 'LineString', coordinates: rulerPoints } };
  if (map.getSource('ruler')) {
    map.getSource('ruler').setData(geojson);
  } else {
    map.addSource('ruler', { type: 'geojson', data: geojson });
    map.addLayer({
      id: 'ruler-line', type: 'line', source: 'ruler',
      paint: { 'line-color': '#0088ff', 'line-width': 2, 'line-dasharray': [4, 2], 'line-opacity': 0.9 }
    });
  }
}

function addRulerPoint(lngLat) {
  const map = window._map;
  const pt = [lngLat.lng, lngLat.lat];
  const idx = rulerPoints.length;
  rulerPoints.push(pt);

  if (rulerPoints.length > 1) {
    rulerTotal += haversineKm(rulerPoints[rulerPoints.length - 2], pt);
  }

  const label = rulerPoints.length === 1 ? '0 м' :
    rulerTotal >= 1 ? rulerTotal.toFixed(1) + ' км' : Math.round(rulerTotal * 1000) + ' м';

  const dot = document.createElement('div');
  dot.style.cssText = 'width:10px;height:10px;background:#0088ff;border:2px solid #fff;border-radius:50%;box-shadow:0 0 4px rgba(0,0,0,0.3);';
  const dotMarker = new maplibregl.Marker({ element: dot, anchor: 'center' })
    .setLngLat([lngLat.lng, lngLat.lat])
    .addTo(map);

  const labelEl = document.createElement('div');
  labelEl.style.cssText = 'display:inline-flex;align-items:center;gap:3px;background:rgba(0,0,0,0.75);color:#fff;font-size:11px;font-weight:600;padding:2px 6px;border-radius:3px;white-space:nowrap;';
  labelEl.innerHTML = `<span>${label}</span><span style="cursor:pointer;opacity:0.7;" onclick="event.stopPropagation();removeRulerPoint(${idx})">✕</span>`;
  const labelMarker = new maplibregl.Marker({ element: labelEl, anchor: 'center', offset: [0, -20] })
    .setLngLat([lngLat.lng, lngLat.lat])
    .addTo(map);

  rulerMarkers.push(dotMarker, labelMarker);
  updateRulerLine();
}

function removeRulerPoint(idx) {
  if (idx < 0 || idx >= rulerPoints.length) return;
  rulerPoints.splice(idx, 1);
  rulerMarkers.forEach(m => m.remove());
  rulerMarkers = [];
  rulerTotal = 0;
  const pts = [...rulerPoints];
  rulerPoints = [];
  pts.forEach(pt => addRulerPoint({ lng: pt[0], lat: pt[1] }));
}

function initRulerClicks(map) {
  map.on('click', (e) => {
    if (!rulerMode) return;
    addRulerPoint(e.lngLat);
  });
  map.on('dblclick', (e) => {
    if (!rulerMode) return;
    e.preventDefault();
    toggleRuler();
  });
}

// ─── Фаза 4: Разведка ───────────────────────────────────────────────────────
let reconMode = false;
let reconCenter = null;
let reconRadius = 20;

function toggleReconMode() {
  reconMode = !reconMode;
  const btn = document.getElementById('tb-recon');
  if (reconMode) {
    deactivateAllModes();
    reconMode = true;
    btn.classList.add('active');
    window._map.getCanvas().style.cursor = 'crosshair';
  } else {
    btn.classList.remove('active');
    window._map.getCanvas().style.cursor = '';
    clearRecon();
  }
}

function makeCircleGeoJSON(lon, lat, radiusKm) {
  const coords = [];
  for (let i = 0; i <= 64; i++) {
    const a = (2 * Math.PI * i) / 64;
    const dlat = (radiusKm / 111) * Math.cos(a);
    const dlon = (radiusKm / (111 * Math.cos(lat * Math.PI / 180))) * Math.sin(a);
    coords.push([lon + dlon, lat + dlat]);
  }
  return { type: 'Feature', geometry: { type: 'Polygon', coordinates: [coords] }, properties: {} };
}

async function doRecon(lon, lat) {
  reconCenter = [lon, lat];
  const map = window._map;
  const panel = document.getElementById('recon-panel');
  panel.style.display = 'block';
  document.getElementById('recon-stats').innerHTML = '<span style="color:#888">Загружаю...</span>';

  // Draw circle
  const circle = makeCircleGeoJSON(lon, lat, reconRadius);
  if (map.getSource('recon-circle')) {
    map.getSource('recon-circle').setData(circle);
  } else {
    map.addSource('recon-circle', { type: 'geojson', data: circle });
    map.addLayer({
      id: 'recon-circle-fill', type: 'fill', source: 'recon-circle',
      paint: { 'fill-color': '#ff6600', 'fill-opacity': 0.08 }
    });
    map.addLayer({
      id: 'recon-circle-stroke', type: 'line', source: 'recon-circle',
      paint: { 'line-color': '#ff6600', 'line-width': 2, 'line-opacity': 0.5 }
    });
  }

  // API call
  const basePath = window.location.pathname.replace(/\/[^/]*$/, '') || '';
  try {
    const resp = await fetch(`${basePath}/api/recon`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ lon, lat, radius_km: reconRadius })
    });
    const data = await resp.json();
    const t = data.trails || {};
    const p = data.poi || {};
    document.getElementById('recon-stats').innerHTML = `
      <div style="font-weight:600;margin-bottom:4px;">🛤 ${t.total_count || 0} грунтовок · ${t.total_km || 0} км</div>
      <div>🟡 Lev1-2: ${t.lev12_count || 0} шт · ${t.lev12_km || 0} км</div>
      <div>🔴 Lev3-5: ${t.lev345_count || 0} шт · ${t.lev345_km || 0} км</div>
      <div>🔴 Тропы: ${t.path_count || 0} шт · ${t.path_km || 0} км</div>
      <div style="margin-top:6px;border-top:1px solid #eee;padding-top:4px;">
        💧 Озёра: ${p['natural=water'] || 0} · 👁 Виды: ${p['tourism=viewpoint'] || 0}<br>
        🌊 Броды: ${p['ford=yes'] || 0} · 🏚 Руины: ${p['historic=ruins'] || 0}
      </div>
    `;
  } catch(e) {
    document.getElementById('recon-stats').innerHTML = '<span style="color:#c00">Ошибка загрузки</span>';
  }
}

function setReconRadius(km) {
  reconRadius = km;
  document.querySelectorAll('.recon-radius-btn').forEach(b => {
    b.classList.toggle('active', +b.dataset.km === km);
  });
  if (reconCenter) doRecon(reconCenter[0], reconCenter[1]);
}

function clearRecon() {
  const map = window._map;
  if (map.getLayer('recon-circle-fill')) map.removeLayer('recon-circle-fill');
  if (map.getLayer('recon-circle-stroke')) map.removeLayer('recon-circle-stroke');
  if (map.getSource('recon-circle')) map.removeSource('recon-circle');
  closeSheet('sheet-recon');
  reconCenter = null;
}

// ─── Фаза 4: Связка ───────────────────────────────────────────────────────────
let linkMode = false;
let linkPoints = [];
let linkMarkers = [];

function toggleLinkMode() {
  linkMode = !linkMode;
  const btn = document.getElementById('tb-link');
  if (linkMode) {
    deactivateAllModes();
    linkMode = true;
    btn.classList.add('active');
    window._map.getCanvas().style.cursor = 'crosshair';
    openSheet('sheet-link');
    document.getElementById('link-status').textContent = '1️⃣ Кликни конец первого трека';
    document.getElementById('link-cards').innerHTML = '';
  } else {
    btn.classList.remove('active');
    window._map.getCanvas().style.cursor = '';
    clearLink();
  }
}

function addLinkPoint(lng, lat) {
  const map = window._map;
  linkPoints.push({ lon: lng, lat: lat });
  const idx = linkPoints.length;
  const el = document.createElement('div');
  el.style.cssText = 'width:16px;height:16px;background:#ff6600;border:2px solid #fff;border-radius:50%;box-shadow:0 1px 4px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;color:#fff;';
  el.textContent = idx;
  const marker = new maplibregl.Marker({ element: el, anchor: 'center', draggable: true }).setLngLat([lng, lat]).addTo(map);
  linkMarkers.push(marker);

  if (idx === 1) {
    document.getElementById('link-status').textContent = '2️⃣ Кликни начало второго трека';
  } else if (idx >= 2) {
    buildLinkRoute();
  }
}

async function buildLinkRoute() {
  const map = window._map;
  document.getElementById('link-status').textContent = '⏳ Ищу связку...';
  const basePath = window.location.pathname.replace(/\/[^/]*$/, '') || '';
  try {
    const resp = await fetch(`${basePath}/api/route`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ waypoints: linkPoints, alternatives: 3 })
    });
    if (!resp.ok) throw new Error('Не найдена');
    const data = await resp.json();
    if (data.routes && data.routes.length > 0) {
      renderLinkCards(data.routes);
      document.getElementById('link-status').textContent = '✅ Связка найдена';
    } else {
      document.getElementById('link-status').textContent = '❌ Грунтовая связка не найдена';
    }
  } catch(e) {
    document.getElementById('link-status').textContent = '❌ ' + e.message;
  }
}

function renderLinkCards(routes) {
  const map = window._map;
  const colors = ['#0066ff', '#00aa44', '#9933cc'];
  const cardsEl = document.getElementById('link-cards');
  cardsEl.innerHTML = '';

  routes.forEach((r, i) => {
    const geojson = { type: 'Feature', geometry: r.geometry, properties: {} };
    const sid = `link-src-${i}`;
    const lid = `link-line-${i}`;
    if (map.getSource(sid)) map.removeSource(sid);
    if (map.getLayer(lid)) map.removeLayer(lid);
    map.addSource(sid, { type: 'geojson', data: geojson });
    map.addLayer({
      id: lid, type: 'line', source: sid,
      paint: {
        'line-color': colors[i % colors.length],
        'line-width': i === 0 ? 5 : 3,
        'line-opacity': i === 0 ? 0.9 : 0.5,
      },
      layout: { 'line-cap': 'round', 'line-join': 'round' }
    });

    const km = (r.distance_m / 1000).toFixed(0);
    const time = formatDuration(r.duration_s);
    const dirt = r.stats?.dirt_total_pct || '?';
    const col = colors[i % colors.length];
    const card = document.createElement('div');
    card.className = 'route-card' + (i === 0 ? ' active' : '');
    card.innerHTML = `
      <div class="route-card-header">
        <span class="route-color-dot" style="background:${col}"></span>
        <span class="route-card-title">Вариант ${i+1}</span>
        <span class="route-card-dist">${km} км</span>
        <span class="route-card-time">${time}</span>
      </div>
      <div style="font-size:11px;color:#666">${dirt}% грунт</div>
    `;
    card.onclick = () => selectLinkRoute(i);
    cardsEl.appendChild(card);
  });
}

function selectLinkRoute(idx) {
  const map = window._map;
  document.querySelectorAll('#link-cards .route-card').forEach((c, i) => c.classList.toggle('active', i === idx));
  // Highlight selected route
  for (let i = 0; i < 3; i++) {
    const lid = `link-line-${i}`;
    if (map.getLayer(lid)) {
      map.setPaintProperty(lid, 'line-width', i === idx ? 5 : 3);
      map.setPaintProperty(lid, 'line-opacity', i === idx ? 0.9 : 0.5);
    }
  }
}

function clearLink() {
  linkPoints = [];
  linkMarkers.forEach(m => m.remove());
  linkMarkers = [];
  const map = window._map;
  for (let i = 0; i < 5; i++) {
    const lid = `link-line-${i}`;
    if (map.getLayer(lid)) map.removeLayer(lid);
    const sid = `link-src-${i}`;
    if (map.getSource(sid)) map.removeSource(sid);
  }
  closeSheet('sheet-link');
  document.getElementById('link-cards').innerHTML = '';
}

// ─── Фаза 4: Красивый маршрут ────────────────────────────────────────────────
let scenicMode = false;
let scenicStart = null;
let scenicStartMarker = null;
let scenicTargetKm = 100;
let scenicRoutes = [];
let activeScenicIdx = 0;

function toggleScenicMode() {
  scenicMode = !scenicMode;
  const btn = document.getElementById('tb-scenic');
  if (scenicMode) {
    deactivateAllModes();
    scenicMode = true;
    btn.classList.add('active');
    window._map.getCanvas().style.cursor = 'crosshair';
    openSheet('sheet-scenic');
    document.getElementById('scenic-status').textContent = 'Кликни точку старта на карте';
  } else {
    btn.classList.remove('active');
    window._map.getCanvas().style.cursor = '';
    clearScenic();
  }
}

function setScenicKm(km) {
  scenicTargetKm = km;
  document.querySelectorAll('.scenic-km-btn').forEach(b => {
    b.classList.toggle('active', +b.dataset.km === km);
  });
  const inp = document.getElementById('scenic-custom-km');
  if (inp) inp.value = km;
}

async function buildScenicRoute() {
  if (!scenicStart) return;
  const map = window._map;
  document.getElementById('scenic-status').textContent = '⏳ Строю красивый маршрут...';
  document.getElementById('btn-build-scenic').textContent = '⏳ Строю...';
  document.getElementById('btn-build-scenic').disabled = true;

  const basePath = window.location.pathname.replace(/\/[^/]*$/, '') || '';
  try {
    const resp = await fetch(`${basePath}/api/scenic`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ lon: scenicStart.lon, lat: scenicStart.lat, target_km: scenicTargetKm })
    });
    if (!resp.ok) {
      const err = await resp.json().catch(() => ({}));
      throw new Error(err.detail || 'Ошибка');
    }
    const data = await resp.json();
    scenicRoutes = data.routes || [];

    if (scenicRoutes.length === 0) throw new Error('Маршрут не найден');

    // Draw routes on map
    const colors = ['#0066ff', '#00aa44', '#9933cc'];
    scenicRoutes.forEach((r, i) => {
      const geojson = { type: 'Feature', geometry: r.geometry, properties: {} };
      const sid = `scenic-src-${i}`;
      const lid = `scenic-line-${i}`;
      if (map.getLayer(lid)) map.removeLayer(lid);
      if (map.getSource(sid)) map.removeSource(sid);
      map.addSource(sid, { type: 'geojson', data: geojson });
      map.addLayer({
        id: lid, type: 'line', source: sid,
        paint: {
          'line-color': colors[i % colors.length],
          'line-width': i === activeScenicIdx ? 5 : 3,
          'line-opacity': i === activeScenicIdx ? 0.9 : 0.5,
        },
        layout: { 'line-cap': 'round', 'line-join': 'round' }
      });
    });

    // Show cards
    const cardsEl = document.getElementById('scenic-cards');
    if (cardsEl) {
      cardsEl.innerHTML = scenicRoutes.map((r, i) => {
        const col = colors[i % colors.length];
        const km = (r.distance_m / 1000).toFixed(0);
        const time = formatDuration(r.duration_s);
        const dirt = r.stats?.dirt_total_pct || '?';
        const pois = (r.scenic_pois || []).map(p => {
          const SCENIC_LABELS = {'natural=water':'💧 Озёро','tourism=viewpoint':'👁 Смотровая','historic=ruins':'🏚 Руины','natural=peak':'🔺 Вершина','natural=cave_entrance':'🕳 Пещера','ford=yes':'🌊 Брод'};
          const label = SCENIC_LABELS[p.type] || '📍 ' + p.type;
          const name = p.name ? ` — ${p.name}` : '';
          return `<div class="scenic-poi-item">${label}${name}</div>`;
        }).join('');
        return `<div class="route-card ${i===activeScenicIdx?'active':''}" onclick="selectScenicRoute(${i})">
          <div class="route-card-header">
            <span class="route-color-dot" style="background:${col}"></span>
            <span class="route-card-title">${r.name || 'Вариант '+(i+1)}</span>
            <span class="route-card-dist">${km} км</span>
            <span class="route-card-time">${time}</span>
          </div>
          <div style="font-size:11px;color:#666">${dirt}% грунт · score=${r.scenic_score||0}</div>
          ${pois ? '<div style="margin-top:4px">'+pois+'</div>' : ''}
        </div>`;
      }).join('');
    }

    document.getElementById('scenic-status').textContent = `✅ ${scenicRoutes.length} маршрут(ов)`;
  } catch(e) {
    document.getElementById('scenic-status').textContent = '❌ ' + e.message;
  }
  document.getElementById('btn-build-scenic').textContent = '🎨 Построить маршрут';
  document.getElementById('btn-build-scenic').disabled = false;
}

function selectScenicRoute(idx) {
  activeScenicIdx = idx;
  const map = window._map;
  scenicRoutes.forEach((_, i) => {
    const lid = `scenic-line-${i}`;
    if (map.getLayer(lid)) {
      map.setLayoutProperty(lid, 'visibility', 'visible');
      map.setPaintProperty(lid, 'line-width', i === idx ? 5 : 3);
      map.setPaintProperty(lid, 'line-opacity', i === idx ? 0.9 : 0.5);
    }
  });
  document.querySelectorAll('#scenic-cards .route-card').forEach((c, i) => {
    c.classList.toggle('active', i === idx);
  });
}

function clearScenic() {
  const map = window._map;
  scenicRoutes.forEach((_, i) => {
    const lid = `scenic-line-${i}`;
    const sid = `scenic-src-${i}`;
    if (map.getLayer(lid)) map.removeLayer(lid);
    if (map.getSource(sid)) map.removeSource(sid);
  });
  if (scenicStartMarker) { scenicStartMarker.remove(); scenicStartMarker = null; }
  scenicStart = null;
  scenicRoutes = [];
  closeSheet('sheet-scenic');
  const cardsEl = document.getElementById('scenic-cards');
  if (cardsEl) cardsEl.innerHTML = '';
}

initMap();
