// Klientský skript pro zobrazení mapy a deníku z dovolené

let map;
let markerMode = 'all'; // 'all' | 'stays'
let routesVisible = true;

const layers = {};
const markerStore = {};
const bounds = [];

let galleryPhotos = []; // [{ web, name }]
let currentPhotoIndex = -1;

const translations = {
  en: {
    vacTitle: "Vacation",
    vacDate: "Vacation Dates",
    btnShowAll: "Show All",
    btnShowStays: "Stays Only",
    btnHideRoutes: "Hide Routes",
    btnShowRoutes: "Show Routes",
    footerNote: "Lines show chronological order, not the exact road route.",
    legendTitle: "Daily Itinerary",
    legendToggle: "🗺️ Legend",
    legendClose: "❌ Close",
    dayLabel: "Day",
    defaultProgram: "Daily Program",
    noNotes: "No notes for this day.",
    accommodation: "Accommodation",
    stop: "Stop",
    noDescription: "No description available.",
    defaultRouteDesc: "Route and places visited.",
    btnLangText: "🇨🇿 CZ"
  },
  cs: {
    vacTitle: "Dovolená",
    vacDate: "Termín dovolené",
    btnShowAll: "Zobrazit vše",
    btnShowStays: "Jen ubytování",
    btnHideRoutes: "Skrýt spojnice",
    btnShowRoutes: "Zobrazit spojnice",
    footerNote: "Spojnice znázorňují pořadí, nikoli přesnou silniční trasu.",
    legendTitle: "Itinerář po dnech",
    legendToggle: "🗺️ Legenda",
    legendClose: "❌ Zavřít",
    dayLabel: "Den",
    defaultProgram: "Program dne",
    noNotes: "Žádné zápisky k tomuto dni.",
    accommodation: "Ubytování",
    stop: "Zastávka",
    noDescription: "Bez bližšího popisu.",
    defaultRouteDesc: "Trasa a navštívená místa.",
    btnLangText: "🇬🇧 EN"
  }
};

let currentLang = 'en'; // Default to EN

// Po načtení stránky zkontrolujeme šifrování
document.addEventListener('DOMContentLoaded', () => {
  const langToggle = document.getElementById('btn-lang-toggle');
  if (langToggle) {
    langToggle.textContent = currentLang === 'en' ? '🇨🇿 CZ' : '🇬🇧 EN';
    langToggle.addEventListener('click', () => {
      currentLang = currentLang === 'en' ? 'cs' : 'en';
      langToggle.textContent = currentLang === 'en' ? '🇨🇿 CZ' : '🇬🇧 EN';
      if (typeof vacationData !== 'undefined') {
        initMapAndUI(vacationData);
      }
    });
  }

  // Legend Toggle Click Handler (set up ONCE)
  const legendToggle = document.getElementById('btn-legend-toggle');
  const mapLegend = document.getElementById('map-legend');
  if (legendToggle && mapLegend) {
    legendToggle.addEventListener('click', (e) => {
      e.stopPropagation();
      mapLegend.classList.toggle('expanded');
      const isExpanded = mapLegend.classList.contains('expanded');
      const t = translations[currentLang];
      legendToggle.textContent = isExpanded ? t.legendClose : t.legendToggle;
    });
  }

  if (typeof isEncrypted !== 'undefined' && isEncrypted) {
    // Web je uzamčen heslem
    document.getElementById('login-overlay').style.display = 'flex';
    document.getElementById('login-form').addEventListener('submit', handleLogin);
  } else if (typeof vacationData !== 'undefined') {
    // Web je volně přístupný
    document.getElementById('app').style.display = 'grid';
    initMapAndUI(vacationData);
  } else {
    alert('Chyba: Data dovolené nebyla nalezena.');
  }

  // Nastavení zavření galerie a navigace
  const modal = document.getElementById('gallery-modal');
  
  document.getElementById('close-gallery').addEventListener('click', () => {
    modal.style.display = 'none';
  });

  const btnPrev = document.getElementById('btn-gallery-prev');
  const btnNext = document.getElementById('btn-gallery-next');

  if (btnPrev) {
    btnPrev.addEventListener('click', (e) => {
      e.stopPropagation();
      navigateGallery(-1);
    });
  }

  if (btnNext) {
    btnNext.addEventListener('click', (e) => {
      e.stopPropagation();
      navigateGallery(1);
    });
  }

  modal.addEventListener('click', (e) => {
    if (e.target === modal || e.target.id === 'gallery-caption') {
      modal.style.display = 'none';
    }
  });

  window.addEventListener('keydown', (e) => {
    const isGalleryVisible = modal.style.display === 'block';
    if (e.key === 'Escape') {
      if (isGalleryVisible) {
        modal.style.display = 'none';
      } else if (map) {
        map.closePopup();
      }
    } else if (isGalleryVisible) {
      if (e.key === 'ArrowRight' || e.key === 'Space') {
        navigateGallery(1);
      } else if (e.key === 'ArrowLeft') {
        navigateGallery(-1);
      }
    }
  });

  let touchstartX = 0;
  let touchendX = 0;

  modal.addEventListener('touchstart', e => {
    touchstartX = e.changedTouches[0].screenX;
  }, { passive: true });

  modal.addEventListener('touchend', e => {
    touchendX = e.changedTouches[0].screenX;
    handleSwipeGesture();
  }, { passive: true });

  function handleSwipeGesture() {
    const threshold = 50;
    if (touchendX < touchstartX - threshold) {
      navigateGallery(1);
    }
    if (touchendX > touchstartX + threshold) {
      navigateGallery(-1);
    }
  }
});

function initMapAndUI(data) {
  // 0. Vyplnění fotek do globální galerie pro posouvání
  galleryPhotos = [];
  data.points.forEach(p => {
    if (p.processedPhotos) {
      p.processedPhotos.forEach(photo => {
        if (!galleryPhotos.some(gp => gp.web === photo.web)) {
          galleryPhotos.push({
            web: photo.web,
            name: p.name
          });
        }
      });
    }
  });

  const t = translations[currentLang];

  // 1. Nastavení barevného schématu
  const scheme = data.colorScheme || 'light';
  document.body.className = `scheme-${scheme}`;

  // 2. Vyplnění hlavičky
  document.getElementById('vac-title').textContent = data.title || t.vacTitle;
  document.getElementById('vac-date').textContent = data.dateText || t.vacDate;
  const descEl = document.getElementById('vac-desc');
  if (data.description) {
    descEl.textContent = data.description;
    descEl.style.display = 'block';
  } else {
    descEl.style.display = 'none';
  }

  // 2b. Vyplnění textů ovládacích prvků
  document.getElementById('btn-show-all').textContent = t.btnShowAll;
  document.getElementById('btn-show-stays').textContent = t.btnShowStays;
  document.getElementById('btn-toggle-routes').textContent = routesVisible ? t.btnHideRoutes : t.btnShowRoutes;
  document.querySelector('.footer-note').textContent = t.footerNote;

  // 3. Inicializace/Re-inicializace mapy Leaflet
  if (map) {
    map.remove();
  }
  
  // Vyčistit lokální vrstvy
  Object.keys(layers).forEach(key => delete layers[key]);
  Object.keys(markerStore).forEach(key => delete markerStore[key]);
  bounds.length = 0;

  map = L.map('map', { zoomControl: true }).setView([48.0, 14.0], 5);
  
  const isDark = scheme === 'dark' || scheme === 'night';
  const tileUrl = isDark 
    ? 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'
    : 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png';
    
  L.tileLayer(tileUrl, {
    maxZoom: 19,
    attribution: '&copy; OpenStreetMap'
  }).addTo(map);

  L.control.scale({ imperial: false }).addTo(map);

  // 4. Vytvoření vrstev pro jednotlivé dny
  data.days.forEach(d => {
    markerStore[d.day] = [];
    layers[d.day] = {
      markers: L.layerGroup().addTo(map),
      route: L.layerGroup().addTo(map)
    };
  });

  // 5. Vykreslení špendlíků (bodů) na mapu
  data.points.forEach(p => {
    const isStay = p.type === 'ubytování';
    const dayObj = data.days.find(d => d.day === p.day);
    const dayColor = dayObj ? dayObj.color : '#2563eb';

    const markerHtml = `<div class="pin ${isStay ? 'stay' : ''}" style="background:${dayColor}"><span>${p.day}</span></div>`;
    const icon = L.divIcon({
      html: markerHtml,
      className: '',
      iconSize: [34, 34],
      iconAnchor: [17, 31],
      popupAnchor: [0, -27]
    });

    const marker = L.marker([p.lat, p.lon], { icon });

    // Příprava galerie fotek pro popup okno špendlíku
    let photosHtml = '';
    if (p.processedPhotos && p.processedPhotos.length > 0) {
      photosHtml = '<div class="popup-photos">';
      p.processedPhotos.forEach(photo => {
        photosHtml += `<img src="${photo.thumb}" onclick="openGallery('${photo.web}', '${esc(p.name)}')" alt="foto">`;
      });
      photosHtml += '</div>';
    }

    const gMapsQuery = encodeURIComponent(`${p.lat},${p.lon}`);
    const typeLabel = isStay ? t.accommodation : (p.type === 'zastávka' ? t.stop : esc(p.type));
    const popupHtml = `
      <div class="popup-content">
        <h3>${esc(p.name)}</h3>
        <div class="meta">📅 ${t.dayLabel} ${p.day} · ${typeLabel}</div>
        <p>${esc(p.description || t.noDescription)}</p>
        ${photosHtml}
        <div class="popup-links">
          <a href="https://www.google.com/maps/search/?api=1&query=${gMapsQuery}" target="_blank">Google Maps</a>
        </div>
      </div>
    `;

    marker.bindPopup(popupHtml);
    marker._isStay = isStay;
    marker._day = p.day;
    markerStore[p.day].push(marker);
    marker.addTo(layers[p.day].markers);
    bounds.push([p.lat, p.lon]);
  });

  // 6. Vykreslení čárkovaných spojnic (tras) pro dny
  data.days.forEach(d => {
    const dayPts = data.points.filter(p => p.day === d.day).sort((a, b) => a.order - b.order);
    if (dayPts.length > 1) {
      const coords = dayPts.map(p => [p.lat, p.lon]);
      L.polyline(coords, {
        color: d.color,
        weight: 4,
        opacity: 0.75,
        dashArray: '8, 8'
      }).addTo(layers[d.day].route);
    }
  });

  // 7. Vytvoření seznamu dnů v sidebaru
  const daysWrap = document.getElementById('days-wrap');
  daysWrap.innerHTML = '';

  data.days.forEach(d => {
    const card = document.createElement('div');
    card.className = 'day-card';
    card.style.setProperty('--c', d.color);

    const dayPts = data.points.filter(p => p.day === d.day);
    let photosHtml = '';
    dayPts.forEach(pt => {
      if (pt.processedPhotos) {
        pt.processedPhotos.forEach(photo => {
          photosHtml += `<img src="${photo.thumb}" onclick="openGallery('${photo.web}', '${esc(pt.name)}')" alt="foto">`;
        });
      }
    });

    const dayLabelStr = `${t.dayLabel} ${d.day}`;

    card.innerHTML = `
      <div class="day-head">
        <input type="checkbox" id="chk-day-${d.day}" checked>
        <div class="day-info" onclick="focusDay(${d.day})">
          <div class="day-name" style="color: ${d.color};">${esc(dayLabelStr)}</div>
          <div class="day-title">${esc(d.title || t.defaultProgram)}</div>
        </div>
      </div>
      <div class="day-summary">${esc(d.summary || t.noNotes)}</div>
      ${photosHtml ? `<div class="day-photos">${photosHtml}</div>` : ''}
    `;

    daysWrap.appendChild(card);
    card.querySelector('input').addEventListener('change', () => refreshDayLayer(d.day));
  });

  if (bounds.length > 0) {
    map.fitBounds(bounds, { padding: [30, 30] });
  }

  setupToolbar(data);
  setTimeout(() => {
    if (map) map.invalidateSize();
  }, 100);

  // 7b. Vyplnění legendy mapy
  const legendList = document.getElementById('legend-list');
  if (legendList) {
    legendList.innerHTML = '';
    data.days.forEach(d => {
      const item = document.createElement('div');
      item.className = 'legend-item';
      
      item.innerHTML = `
        <div class="legend-color-dot" style="background-color: ${d.color};"></div>
        <div>
          <span class="legend-day-num">${t.dayLabel} ${d.day}:</span> 
          <span>${esc(d.title || t.defaultProgram)}</span>
        </div>
      `;
      legendList.appendChild(item);
    });
  }

  const legendToggle = document.getElementById('btn-legend-toggle');
  const mapLegend = document.getElementById('map-legend');
  if (legendToggle && mapLegend) {
    document.getElementById('legend-title-text').textContent = t.legendTitle;
    const isExpanded = mapLegend.classList.contains('expanded');
    legendToggle.textContent = isExpanded ? t.legendClose : t.legendToggle;
  }

  // 7c. Výběr barevného schématu
  const webColorOptions = document.querySelectorAll('.web-color-option');
  webColorOptions.forEach(opt => {
    if (opt.dataset.scheme === scheme) {
      opt.classList.add('active');
    }
    opt.addEventListener('click', () => {
      webColorOptions.forEach(o => o.classList.remove('active'));
      opt.classList.add('active');
      
      const newScheme = opt.dataset.scheme;
      document.body.className = `scheme-${newScheme}`;
      
      if (map) {
        const isD = newScheme === 'dark';
        const newTileUrl = isD 
          ? 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'
          : 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png';
        
        map.eachLayer(layer => {
          if (layer instanceof L.TileLayer) {
            layer.setUrl(newTileUrl);
          }
        });
      }
    });
  });
}

function refreshDayLayer(dayNum) {
  const isChecked = document.getElementById(`chk-day-${dayNum}`).checked;
  
  if (map.hasLayer(layers[dayNum].markers)) map.removeLayer(layers[dayNum].markers);
  if (map.hasLayer(layers[dayNum].route)) map.removeLayer(layers[dayNum].route);

  const filteredMarkers = markerMode === 'stays'
    ? markerStore[dayNum].filter(m => m._isStay)
    : markerStore[dayNum];

  layers[dayNum].markers = L.layerGroup(filteredMarkers);

  if (isChecked) {
    layers[dayNum].markers.addTo(map);
    if (routesVisible && markerMode === 'all') {
      layers[dayNum].route.addTo(map);
    }
  }
}

function refreshAllDays() {
  Object.keys(layers).forEach(dayNum => refreshDayLayer(dayNum));
}

function focusDay(dayNum) {
  const dayMarkers = markerStore[dayNum];
  if (dayMarkers && dayMarkers.length > 0) {
    const dayBounds = dayMarkers.map(m => m.getLatLng());
    map.fitBounds(dayBounds, { padding: [50, 50], maxZoom: 14 });
    dayMarkers[0].openPopup();
  }
}

function setupToolbar(data) {
  const btnShowAll = document.getElementById('btn-show-all');
  const btnShowStays = document.getElementById('btn-show-stays');
  const btnToggleRoutes = document.getElementById('btn-toggle-routes');

  // Remove existing listeners by replacing buttons or just check and clear them.
  // In our environment, since they are simple, we can just replace elements or remove listeners.
  // Re-adding simple click events works fine since it resets on initMapAndUI which destroys map
}

document.addEventListener('DOMContentLoaded', () => {
  // Bind toolbar once here to avoid duplicated listeners
  const btnShowAll = document.getElementById('btn-show-all');
  const btnShowStays = document.getElementById('btn-show-stays');
  const btnToggleRoutes = document.getElementById('btn-toggle-routes');

  if (btnShowAll) {
    btnShowAll.addEventListener('click', () => {
      markerMode = 'all';
      if (typeof vacationData !== 'undefined') {
        vacationData.days.forEach(d => {
          const chk = document.getElementById(`chk-day-${d.day}`);
          if (chk) chk.checked = true;
        });
      }
      refreshAllDays();
      if (bounds.length > 0) {
        map.fitBounds(bounds, { padding: [30, 30] });
      }
    });
  }

  if (btnShowStays) {
    btnShowStays.addEventListener('click', () => {
      markerMode = 'stays';
      refreshAllDays();
      if (typeof vacationData !== 'undefined') {
        const stayCoords = vacationData.points.filter(p => p.type === 'ubytování').map(p => [p.lat, p.lon]);
        if (stayCoords.length > 0) {
          map.fitBounds(stayCoords, { padding: [50, 50] });
        }
      }
    });
  }

  if (btnToggleRoutes) {
    btnToggleRoutes.addEventListener('click', () => {
      routesVisible = !routesVisible;
      const t = translations[currentLang];
      btnToggleRoutes.textContent = routesVisible ? t.btnHideRoutes : t.btnShowRoutes;
      refreshAllDays();
    });
  }
});

function openGallery(imgSrc, captionText) {
  const idx = galleryPhotos.findIndex(p => p.web === imgSrc);
  if (idx !== -1) {
    showPhoto(idx);
  } else {
    const modal = document.getElementById('gallery-modal');
    const modalImg = document.getElementById('gallery-img');
    const captionEl = document.getElementById('gallery-caption');
    modal.style.display = 'block';
    modalImg.src = imgSrc;
    captionEl.textContent = captionText || '';
    currentPhotoIndex = -1;
  }
}

function showPhoto(index) {
  if (index < 0 || index >= galleryPhotos.length) return;
  currentPhotoIndex = index;
  const photo = galleryPhotos[index];
  
  const modal = document.getElementById('gallery-modal');
  const modalImg = document.getElementById('gallery-img');
  const captionEl = document.getElementById('gallery-caption');
  
  modal.style.display = 'block';
  modalImg.src = photo.web;
  captionEl.textContent = photo.name || '';
}

// Client-side decryption helper if password protected
function handleLogin(e) {
  e.preventDefault();
  const pass = document.getElementById('pass-input').value;
  try {
    const decryptedBytes = CryptoJS.AES.decrypt(encryptedData, pass);
    const decryptedText = decryptedBytes.toString(CryptoJS.enc.Utf8);
    if (!decryptedText) {
      document.getElementById('login-error').style.display = 'block';
      return;
    }
    const data = JSON.parse(decryptedText);
    document.getElementById('login-overlay').style.display = 'none';
    document.getElementById('app').style.display = 'grid';
    window.vacationData = data; // store globally
    initMapAndUI(data);
  } catch (err) {
    document.getElementById('login-error').style.display = 'block';
  }
}

function navigateGallery(direction) {
  if (galleryPhotos.length === 0) return;
  let newIdx = currentPhotoIndex + direction;
  if (newIdx >= galleryPhotos.length) newIdx = 0;
  if (newIdx < 0) newIdx = galleryPhotos.length - 1;
  showPhoto(newIdx);
}

function esc(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
