import './style.css'

// Smooth scrolling for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();
    const target = document.querySelector(this.getAttribute('href'));
    if (target) {
      window.scrollTo({
        top: target.offsetTop,
        behavior: 'smooth'
      });
    }
  });
});

// Update navbar styling on scroll
const navbar = document.getElementById('navbar');
window.addEventListener('scroll', () => {
  if (window.scrollY > 50) {
    navbar.classList.add('scrolled');
  } else {
    navbar.classList.remove('scrolled');
  }
});

// Scroll Reveal Animation Initialization using IntersectionObserver
const revealElements = document.querySelectorAll('.scroll-reveal');

const revealOptions = {
  threshold: 0.15,
  rootMargin: "0px 0px -50px 0px"
};

const scrollObserver = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('active');
      // Optional: stop observing once revealed
      // observer.unobserve(entry.target);
    }
  });
}, revealOptions);

revealElements.forEach(el => {
  scrollObserver.observe(el);
});

// Theme toggling logic
const themeToggleBtn = document.getElementById('theme-toggle');
const moonIcon = document.getElementById('moon-icon');
const sunIcon = document.getElementById('sun-icon');

// Check for saved theme preference or use system preference (default to light)
const savedTheme = localStorage.getItem('theme');
const systemPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
let currentTheme = savedTheme || (systemPrefersDark ? 'dark' : 'light');

function applyTheme(theme) {
  if (theme === 'dark') {
    document.documentElement.setAttribute('data-theme', 'dark');
    moonIcon.style.display = 'none';
    sunIcon.style.display = 'block';
  } else {
    document.documentElement.removeAttribute('data-theme');
    moonIcon.style.display = 'block';
    sunIcon.style.display = 'none';
  }
}

// Initial appliance
applyTheme(currentTheme);

themeToggleBtn.addEventListener('click', () => {
  currentTheme = currentTheme === 'dark' ? 'light' : 'dark';
  localStorage.setItem('theme', currentTheme);
  applyTheme(currentTheme);
});

// Gallery Grid & Lightbox Logic
const finalImages = [
  "aamiainen-2-768x432.jpeg", "kipinatie10.jpeg", "kipinatie10_13.jpeg", "kipinatie10_14.jpeg",
  "kipinatie10_15.jpeg", "kipinatie10_2-2.jpeg", "kipinatie10_20.jpeg", "kipinatie10_28.jpeg",
  "kipinatie10_3.jpeg", "kipinatie10_36-7.jpeg", "kipinatie10_37.jpeg", "kipinatie10_5.jpeg",
  "kipinatie10_50-5.jpeg", "kipinatie10_52.jpeg", "kipinatie10_53.jpeg", "kipinatie10_54.jpeg",
  "kipinatie10_57.jpeg", "kipinatie10_58-2.jpeg", "kipinatie10_59.jpeg", "kipinatie10_6.jpeg",
  "kipinatie10_60.jpeg", "kipinatie10_61.jpeg", "kipinatie10_62.jpeg", "kipinatie10_64.jpeg",
  "kipinatie10_65.jpeg", "kipinatie10_68.jpeg", "kipinatie10_69-0.jpeg", "kipinatie10_70-2.jpeg",
  "kipinatie10_71-3.jpeg", "kipinatie10_8.jpeg", "kipinatie10_9.jpeg", "ranta-aurinko.jpeg"
];

const galleryImages = finalImages.map(src => ({ src, title: 'Kipinä Lomat Kuvagalleria' }));

const galleryGrid = document.getElementById('gallery-grid');
const lightbox = document.getElementById('lightbox');
const lightboxImg = document.getElementById('lightbox-img');
const lightboxCaption = document.getElementById('lightbox-caption');
const lightboxClose = document.getElementById('lightbox-close');
const lightboxPrev = document.getElementById('lightbox-prev');
const lightboxNext = document.getElementById('lightbox-next');

let currentLightboxIndex = 0;

if (galleryGrid && lightbox) {
  galleryGrid.innerHTML = '';
  // Populate Gallery Grid
  galleryImages.forEach((item, index) => {
    const galleryItem = document.createElement('div');
    galleryItem.className = 'gallery-item';
    
    const imgEl = document.createElement('img');
    imgEl.src = `/img/${item.src}`;
    imgEl.alt = item.title;
    imgEl.loading = 'lazy';

    galleryItem.appendChild(imgEl);
    galleryGrid.appendChild(galleryItem);

    // Open Lightbox on Click
    galleryItem.addEventListener('click', () => openLightbox(index));
  });

  // Lightbox Functions
  function openLightbox(index) {
    currentLightboxIndex = index;
    updateLightboxImage();
    lightbox.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  function closeLightbox() {
    lightbox.classList.remove('active');
    document.body.style.overflow = 'auto';
  }

  function updateLightboxImage() {
    lightboxImg.classList.remove('loaded');
    const currentItem = galleryImages[currentLightboxIndex];
    setTimeout(() => {
      lightboxImg.src = `/img/${currentItem.src}`;
      lightboxCaption.textContent = currentItem.title;
      setTimeout(() => lightboxImg.classList.add('loaded'), 50);
    }, 200);
  }

  function showNext() {
    currentLightboxIndex = (currentLightboxIndex + 1) % galleryImages.length;
    updateLightboxImage();
  }

  function showPrev() {
    currentLightboxIndex = (currentLightboxIndex - 1 + galleryImages.length) % galleryImages.length;
    updateLightboxImage();
  }

  lightboxClose.addEventListener('click', closeLightbox);
  lightboxNext.addEventListener('click', (e) => { e.stopPropagation(); showNext(); });
  lightboxPrev.addEventListener('click', (e) => { e.stopPropagation(); showPrev(); });
  
  lightbox.addEventListener('click', (e) => {
    if (e.target === lightbox || e.target === document.querySelector('.lightbox-content-wrapper')) {
      closeLightbox();
    }
  });

  document.addEventListener('keydown', (e) => {
    if (!lightbox.classList.contains('active')) return;
    if (e.key === 'Escape') closeLightbox();
    if (e.key === 'ArrowRight') showNext();
    if (e.key === 'ArrowLeft') showPrev();
  });
}
