document.addEventListener('DOMContentLoaded', () => {
  const map = L.map('map').setView([38.9175, 139.8353], 16);
 
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map);
  
  // 現在地表示
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
      const lat = position.coords.latitude;
      const lng = position.coords.longitude;
      L.marker([lat, lng], {
        icon: L.icon({
          iconUrl: 'images/favicon-32x32-now.png',
          iconSize: [24, 24],
          iconAnchor: [12, 12]
        })
      }).addTo(map).bindPopup('現在地');
    });
  }
 
// カスタムアイコンを定義
  const customIcon = L.icon({
    iconUrl: 'images/.png', // カスタムマーカー画像のパス
    iconSize: [32, 32], // マーカーのサイズ
    iconAnchor: [16, 32], // アイコンの「足」の位置
    popupAnchor: [0, -32] // ポップアップの表示位置
  });
 
  fetch('fes.csv')
    .then(response => response.text())
    .then(text => {
      const rows = text.split('\n').filter(row => row.trim());
      const headers = rows[0].split(',').map(h => h.trim());
 
      for (let i = 1; i < rows.length; i++) {
        const values = rows[i].split(',').map(v => v.replace(/^"|"$/g, '').trim());
        const data = {};
        headers.forEach((key, index) => data[key] = values[index] || '');
 
        const lat = parseFloat(data.latitude);
        const lng = parseFloat(data.longitude);
        if (isNaN(lat) || isNaN(lng)) continue;
 
        const isOpen = !isClosedToday(data.description1) && isOpenNow(data.description2);
        const iconPath = isOpen ? (data.icon || 'images/.png') : 'images/.png';
 
        const customIcon = L.icon({
          iconUrl: iconPath,
          iconSize: [32, 32],
          iconAnchor: [16, 32],
          popupAnchor: [0, -32]
        });
 
        const description = [data.description1, data.description2, data.description3, data.mama]
          .filter(Boolean)
          .map(d => d.trim())
          .join('<br>');
 
        const image1 = data.img1 && data.img1.trim() !== '' ? data.img1 : 'images/.png';
        const image2 = data.img2 && data.img2.trim() !== '' ? data.img2 : 'images/.png';
 
        const popupContent = `
          <div class="popup-content">
            <h3>${data.name.replace(/"$/, '')}</h3>
            <p>${description}</p>
            <img src="${image1}" width="106" height="73" style="cursor: pointer;" onclick="openModal('${image1}')" />
            <img src="${image2}" width="106" height="73" style="cursor: pointer;" onclick="openModal('${image2}')" />
            <button onclick="addToFavorites('${data.name}')">行きたいお店リストに追加</button>
          </div>`;
 
        const marker = L.marker([lat, lng], { icon: customIcon }).addTo(map).bindPopup(popupContent);
        marker.isOpen = isOpen;
        markers.push(marker);
      }
    })
    .catch(error => {
      console.error('CSV読み込みエラー:', error);
    });
 
let markers = [];
 
  // マーカーを追加し、ポップアップを設定
  snacks.forEach(snack => {
    const markerIcon = L.icon({
      iconUrl: snack.icon || 'images/.png', // 個別アイコンまたはデフォルトアイコン
      iconSize: [32, 32],
      iconAnchor: [16, 32],
      popupAnchor: [0, -32]
    });
 
const marker = L.marker([snack.lat, snack.lng], { icon: markerIcon }).addTo(map);
   const popupContent = `
  <div class="popup-content">
    <h3>${snack.name}</h3>
    <p>${snack.description1 || ''}</p>
    <p>${snack.description2 || ''}</p>
    <p>${snack.description3 || ''}</p>
    <p>${snack.mama || ''}</p>
    <img src="${snack.img1}" width="106" height="73" onclick="openModal('${snack.img1}')" style="cursor: pointer;" />
    <img src="${snack.img2}" width="106" height="73" onclick="openModal('${snack.img2}')" style="cursor: pointer;" />
    <button onclick="addToFavorites('${snack.name}')">行きたいお店リストに追加</button>
  </div>
`;
 
    marker.bindPopup(popupContent);
    markers.push({ marker, name: snack.name });
  });
 
// リスト追加機能
window.addToFavorites = function(name){
  const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
  favorites.push({ name, addedAt: new Date().toISOString() });
  localStorage.setItem('favorites', JSON.stringify(favorites));
  alert(`${name}を行きたいお店リストに追加しました！`);
  };
  
// モーダルの開閉操作
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';
  }
　};
});
