document.addEventListener('DOMContentLoaded', () => {
  const map = L.map('map').setView([38.893567, 139.818873], 13);

  // OSMタイル
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map);

  // CSV読み込み
  Papa.parse("gitbucket_rensyuu.csv", {
    download: true,
    header: true,
    complete: function(results) {
      results.data.forEach(row => {
        if (row.latitude && row.longitude) {
          const lat = parseFloat(row.latitude);
          const lng = parseFloat(row.longitude);

          // 説明文（空欄は無視）
          const descriptions = [row.description1, row.description2, row.description3]
            .filter(desc => desc && desc.trim() !== "")
            .map(desc => `<p>${desc}</p>`)
            .join("");

          // 画像処理（空欄は無視、クリックでモーダル）
          let images = "";
          if (row.img1 && row.img1.trim() !== "") {
            images += `<img src="${row.img1}" width="106" height="73" onclick="openModal('${row.img1}')" style="cursor:pointer;">`;
          }
          if (row.img2 && row.img2.trim() !== "") {
            images += `<img src="${row.img2}" width="106" height="73" onclick="openModal('${row.img2}')" style="cursor:pointer;">`;
          }

          // icon処理（空欄ならデフォルトを使用）
          const iconUrl = row.icon && row.icon.trim() !== "" ? row.icon : "images/default_icon.png";
          const markerIcon = L.icon({
            iconUrl: iconUrl,
            iconSize: [32, 32],
            iconAnchor: [16, 32],
            popupAnchor: [0, -32]
          });

          // ポップアップ内容
          const popupContent = `
            <div class="popup-content">
              <h3>${row.name}</h3>
              ${descriptions}
              ${images}
            </div>
          `;

          // マーカー追加（カスタムアイコン付き）
          L.marker([lat, lng], { icon: markerIcon }).addTo(map).bindPopup(popupContent);
        }
      });
    }
  });

  // モーダル開閉
  window.openModal = function(imageSrc) {
    const modal = document.getElementById('image-modal');
    const modalImage = document.getElementById('modal-image');
    modalImage.src = imageSrc;
    modal.style.display = 'block';
  };

  window.closeModal = function() {
    const modal = document.getElementById('image-modal');
    modal.style.display = 'none';
  };

  // モーダル外クリックで閉じる
  window.onclick = function(event) {
    const modal = document.getElementById('image-modal');
    if (event.target === modal) {
      modal.style.display = 'none';
    }
  };
});
