<?php
declare(strict_types=1);

/** @var string $buttonId 버튼 id (폼마다 고유) */
$buttonId = $buttonId ?? 'btn-kakao-map-open';
/** @var string $label 버튼 텍스트 */
$label = $label ?? '지도';
?>
<button type="button" id="<?= esc($buttonId, 'attr') ?>" class="no-print border border-btn-print-border text-gray-700 px-3 py-1.5 rounded-sm text-sm hover:bg-gray-50 transition shrink-0" title="카카오맵에서 이 주소 검색"><?= esc($label) ?></button>
<script>
(function () {
  var bid = <?= json_encode($buttonId, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
  function bind() {
    var btn = document.getElementById(bid);
    if (!btn) return;
    btn.addEventListener('click', function () {
      var form = btn.closest('form');
      if (!form) return;
      function val(name) {
        var el = form.querySelector('[name="' + name + '"]');
        return el ? String(el.value || '').trim() : '';
      }
      var road = val('ds_addr');
      var jibun = val('ds_addr_jibun');
      var detail = val('ds_addr_detail');
      var q = road || jibun;
      if (detail) {
        q = q ? (q + ' ' + detail) : detail;
      }
      if (!q) {
        window.alert('주소 검색으로 도로명·지번을 먼저 입력한 뒤 지도를 열 수 있습니다.');
        return;
      }
      if (typeof window.openDesignatedShopKakaoMap === 'function') {
        window.openDesignatedShopKakaoMap(q);
        return;
      }
      window.open('https://map.kakao.com/link/search/' + encodeURIComponent(q), '_blank', 'noopener,noreferrer');
    });
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', bind);
  } else {
    bind();
  }
})();
</script>
