<?= view('components/print_header', ['printTitle' => '지정판매소 지도']) ?>
<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel">
  <div class="flex flex-wrap items-center justify-between gap-y-2">
    <span class="text-sm font-bold text-gray-700">지정판매소 지도</span>
    <a href="<?= mgmt_url('designated-shops') ?>" class="border border-gray-300 text-gray-600 px-3 py-1 rounded-sm text-sm hover:bg-gray-50">목록으로</a>
  </div>
</section>
<div id="kakao-map" class="w-full border border-gray-300 rounded-lg mt-2" style="height:600px;"></div>
<div class="mt-2 text-sm text-gray-500">총 <?= count($shops) ?>개 판매소 표시</div>

<script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=<?= esc($kakaoJavascriptKey ?? '', 'attr') ?>&libraries=services"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var mapContainer = document.getElementById('kakao-map');
    if (typeof kakao === 'undefined' || typeof kakao.maps === 'undefined') {
        mapContainer.innerHTML = '<div class="flex items-center justify-center h-full text-gray-500 text-sm px-4 text-center">카카오맵을 불러올 수 없습니다. Kakao Developers → 제품 설정에서 「Kakao Map」을 켜고, 플랫폼(Web)에 이 사이트 URL을 등록했는지 확인하세요.</div>';
        return;
    }

    var mapOption = {
        center: new kakao.maps.LatLng(35.8714, 128.6014), // 대구 기본 좌표
        level: 8
    };
    var map = new kakao.maps.Map(mapContainer, mapOption);

    var geocoder = new kakao.maps.services.Geocoder();
    var shops = <?= json_encode(array_map(function($s) {
        return ['name' => $s->ds_name, 'addr' => $s->ds_addr ?? '', 'rep' => $s->ds_rep_name ?? '', 'tel' => $s->ds_tel ?? ''];
    }, $shops), JSON_UNESCAPED_UNICODE) ?>;

    var bounds = new kakao.maps.LatLngBounds();
    var markerCount = 0;

    shops.forEach(function(shop) {
        if (!shop.addr) return;
        geocoder.addressSearch(shop.addr, function(result, status) {
            if (status === kakao.maps.services.Status.OK) {
                var coords = new kakao.maps.LatLng(result[0].y, result[0].x);
                var marker = new kakao.maps.Marker({ map: map, position: coords });
                var infoContent = '<div style="padding:5px;font-size:12px;min-width:150px;">' +
                    '<strong>' + shop.name + '</strong><br/>' +
                    (shop.rep ? '대표: ' + shop.rep + '<br/>' : '') +
                    (shop.tel ? 'TEL: ' + shop.tel + '<br/>' : '') +
                    '<span style="color:#888;">' + shop.addr + '</span></div>';
                var infowindow = new kakao.maps.InfoWindow({ content: infoContent });
                kakao.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map, marker);
                });
                bounds.extend(coords);
                markerCount++;
                if (markerCount > 0) map.setBounds(bounds);
            }
        });
    });
});
</script>
