// your Mapbox access token
mapboxgl.accessToken = 'pk.eyJ1IjoiY2FiYmJ5eSIsImEiOiJjbWRpYzY1MGgwYzA5Mm1xM25udDUzbGtpIn0.RX6zv4VI6r2vpj7IWidz0w';

// mobile stuffs
const isMobile = window.innerWidth <= 600;
const mobileMaxPx = Math.floor(window.innerWidth * 0.65);
const desktopMax  = '240px';

// Colors
const Config = {
  colors: {
    place:    '#FF0000', // red
    event:    '#FF8DA1', // pink
    food:     '#000080', // navy blue
    default:  '#000000'  // fallback black
  }
};

// 1. Initialize the map
const map = new mapboxgl.Map({
  container: 'map',                          // ID of the <div> in index.html
  projection: 'globe',
  style: 'mapbox://styles/mapbox/streets-v12',
  center: [-122.3194, 37.7849],              // SF [lng, lat]
  zoom: 11,

  attributionControl: false         // completely removes the attribution control
});

map.addControl(new mapboxgl.NavigationControl()); // Nav controls

// 2. Total Pins
const header = document.getElementById('legend-header');
header.textContent = `Total pins: ${pins.length}`;

// 3. Loop through your pins array and add markers+popups
pins.forEach(pin => {
  const [latStr, lngStr] = pin.loc.split(',').map(s => s.trim());
  const lat = parseFloat(latStr);
  const lng = parseFloat(lngStr);
  // offset is how far the popup appears above/below the pin
  const popup = new mapboxgl.Popup({ 
    offset: {
      // when the popup is above the marker, push it up by 25px (nice spacing)
      top: [0, 10],
      // when it’s below the marker, only push it down by 8px (tighter)
      bottom: [0, -40],
      // for the corners
      'top-left': [15, 25],
      'top-right': [-15, 25],
      'bottom-left': [25, 20],
      'bottom-right': [-25, 20]
    },
    // close button is intuitive
    closeButton: false,
    // mobile stuffs
    maxWidth: isMobile 
      ? `${mobileMaxPx}px`   // ~85% of the true device width 
      : '240px'              // your normal desktop width
  }).setHTML(`
<img 
  loading="lazy" 
  src="${pin.image}" 
  alt="${pin.title}"
>
<h3>
  <a href="${pin.linkUrl}" target="_blank"> ${pin.title} </a>
</h3>
<p>${pin.caption}</p>
`);
  new mapboxgl.Marker({ scale: 0.75, color: Config.colors[pin.category] || Config.colors.default })
    .setLngLat([lng, lat])
    .setPopup(popup)
    .addTo(map);
});

// 4 To show big picture.
const overlay   = document.getElementById('overlay');
const overlayImg = document.getElementById('overlay-img');

document.addEventListener('click', e => {
  // if user clicked *inside* a popup on its <img>
  if (e.target.matches('.mapboxgl-popup-content img')) {
    overlayImg.src = e.target.src;      // copy the clicked image
    overlay.classList.add('show');      // show the overlay
  }
});

overlay.addEventListener('click', e => {
  if (e.target === overlay) {
    overlay.classList.remove('show');
  }
});

