<?php
declare(strict_types=1);
/**
 * OpenStreetMap(Leaflet) 목업 지도 — 지정판매소·창고·수불 지점 대략 표시
 *
 * @var string $lgLabel
 * @var string $mapId
 * @var string $mapHeight
 * @var bool $mapFill
 * @var array{centerLat:float,centerLng:float,zoom:int,markers:list<array>} $govMapPanel
 */
$mapId     = $mapId ?? 'govPortalMap';
$mapHeight = $mapHeight ?? '200px';
$mapFill   = $mapFill ?? false;
$govMapPanel = $govMapPanel ?? [
    'centerLat' => 35.8714,
    'centerLng' => 128.6014,
    'zoom'      => 11,
    'markers'   => [],
];
$wrapClass = 'portal-map-wrap' . ($mapFill ? ' is-fill' : '');
$wrapStyle = $mapFill ? '' : 'height:' . esc($mapHeight, 'attr') . ';';
?>
<div class="<?= esc($wrapClass, 'attr') ?>" id="<?= esc($mapId, 'attr') ?>-wrap"<?= $wrapStyle !== '' ? ' style="' . $wrapStyle . '"' : '' ?>>
  <div class="portal-map-lg-badge">
    <?= esc($lgLabel) ?>
    <small>지정판매소·창고 (목업)</small>
  </div>
  <div id="<?= esc($mapId, 'attr') ?>" class="portal-map-leaflet" role="application" aria-label="<?= esc($lgLabel) ?> 판매·수불 지도"></div>
  <div class="portal-map-legend" aria-hidden="true">
    <span class="lg-warehouse">창고</span>
    <span class="lg-shop">판매소</span>
    <span class="lg-flow">수불</span>
  </div>
</div>
<script>
(function () {
  var mapId = <?= json_encode($mapId, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
  var cfg = <?= json_encode($govMapPanel, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS) ?>;
  var lgLabel = <?= json_encode($lgLabel, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS) ?>;

  function markerStyle(kind) {
    if (kind === 'warehouse') return { color: '#2563eb', fill: '#3b82f6' };
    if (kind === 'shop') return { color: '#059669', fill: '#10b981' };
    return { color: '#d97706', fill: '#f59e0b' };
  }

  function initMap() {
    var el = document.getElementById(mapId);
    if (!el || typeof L === 'undefined') return;

    if (el._govPortalMap) {
      el._govPortalMap.remove();
      el._govPortalMap = null;
    }

    var map = L.map(el, {
      zoomControl: true,
      scrollWheelZoom: false,
      attributionControl: true,
    }).setView([cfg.centerLat, cfg.centerLng], cfg.zoom || 11);

    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 18,
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a>',
    }).addTo(map);

    (cfg.markers || []).forEach(function (m) {
      var st = markerStyle(m.kind || 'flow');
      var circle = L.circleMarker([m.lat, m.lng], {
        radius: 7,
        color: st.color,
        fillColor: st.fill,
        fillOpacity: 0.85,
        weight: 2,
      }).addTo(map);
      if (m.title) {
        circle.bindPopup('<strong>' + m.title + '</strong>');
      }
    });

    L.circleMarker([cfg.centerLat, cfg.centerLng], {
      radius: 9,
      color: '#1a2b4b',
      fillColor: '#4a69bd',
      fillOpacity: 0.9,
      weight: 2,
    }).addTo(map).bindPopup('<strong>' + lgLabel + '</strong><br>담당 지자체');

    var bounds = [];
    (cfg.markers || []).forEach(function (m) { bounds.push([m.lat, m.lng]); });
    if (bounds.length > 1) {
      map.fitBounds(bounds, { padding: [28, 28], maxZoom: 13 });
    }

    el._govPortalMap = map;
    setTimeout(function () { map.invalidateSize(); }, 120);
  }

  function boot() {
    if (typeof L !== 'undefined') {
      initMap();
      return;
    }
    var el = document.getElementById(mapId);
    if (el) {
      el.innerHTML = '<div style="padding:1rem;text-align:center;font-size:12px;color:#666;">지도를 불러오지 못했습니다. 네트워크 연결을 확인해 주세요.</div>';
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
</script>
