// events-carousel.js

// --- State Variables ---
let allEvents = [];
let selectedEvents = [];
let currentIndex = 0;

// --- Helpers ---
const parseZohoTimestamp = (raw) => {
  if (!raw && raw !== 0) return new Date(0);
  const s = String(raw).trim();

  let m = s.match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})([+-]\d{4}|Z)?$/i);
  if (m) {
    const [, Y, Mo, D, hh, mm, ss, tz] = m;
    let tzPart = '';
    if (tz && tz.toUpperCase() !== 'Z') tzPart = tz.slice(0,3) + ':' + tz.slice(3);
    else if (tz && tz.toUpperCase() === 'Z') tzPart = 'Z';
    const iso = `${Y}-${Mo}-${D}T${hh}:${mm}:${ss}${tzPart}`;
    const d = new Date(iso);
    if (!isNaN(d)) return d;
  }

  m = s.match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})([+-]\d{4}|Z)?$/i);
  if (m) {
    const [, Y, Mo, D, hh, mm, tz] = m;
    let tzPart = '';
    if (tz && tz.toUpperCase() !== 'Z') tzPart = tz.slice(0,3) + ':' + tz.slice(3);
    else if (tz && tz.toUpperCase() === 'Z') tzPart = 'Z';
    const iso = `${Y}-${Mo}-${D}T${hh}:${mm}:00${tzPart}`;
    const d = new Date(iso);
    if (!isNaN(d)) return d;
  }

  m = s.match(/^(\d{4})(\d{2})(\d{2})$/);
  if (m) {
    const [, Y, Mo, D] = m;
    return new Date(Number(Y), Number(Mo) - 1, Number(D));
  }

  const tryDate = new Date(s);
  if (!isNaN(tryDate)) return tryDate;

  const mmdd = s.match(/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2,4})$/);
  if (mmdd) {
    let month = parseInt(mmdd[1], 10);
    let day = parseInt(mmdd[2], 10);
    let year = parseInt(mmdd[3], 10);
    if (year < 100) year += 2000;
    return new Date(year, month - 1, day);
  }

  return new Date(0);
};

const eventTimestamp = (ev) => {
  if (!ev) return 0;
  const candidate = ev.start || ev.displayDate || ev.date || ev.eventDate || ev.createdAt || ev.created;
  return parseZohoTimestamp(candidate).getTime();
};

// --- Render the visible items ---
const renderEvents = () => {
  const eventList = document.getElementById("event-list");
  if (!eventList) return;
  eventList.innerHTML = "";

  if (selectedEvents.length === 0) {
    eventList.innerHTML = `<p class="no-events-message">No events found for this category.</p>`;
    return;
  }

  const lastIndex = selectedEvents.length - 1;
  let visibleIndexes = [];

  if (selectedEvents.length <= 3) {
    visibleIndexes = Array.from({ length: selectedEvents.length }, (_, i) => i);
  } else if (currentIndex === 0) {
    visibleIndexes = [0, 1, 2];
  } else if (currentIndex === lastIndex) {
    visibleIndexes = [lastIndex - 2, lastIndex - 1, lastIndex];
  } else {
    visibleIndexes = [currentIndex - 1, currentIndex, currentIndex + 1];
  }

  visibleIndexes = visibleIndexes.filter(i => i >= 0 && i <= lastIndex);

  visibleIndexes.forEach((index) => {
    const event = selectedEvents[index];
    if (!event) return;

    const card = document.createElement("div");
    card.className = "event-card";

    card.addEventListener('click', () => {
      if (index !== currentIndex) {
        currentIndex = index;
        renderEvents();
      }
    });

    if (index === currentIndex) {
      card.classList.add("is-expanded");
      card.innerHTML = `
        <h3 class="event-title ${event.category}">${event.title || ''}</h3>
        <p class="event-date">${event.displayDate || event.start || ''}</p>
        <p class="event-location">${event.location ? `Location: ${event.location}` : ''}</p>
        <p class="event-description">${event.description ? event.description : ''}</p>
      `;
    } else {
      card.classList.add("is-collapsed");
      card.innerHTML = `
        <h3 class="event-title ${event.category}">${event.title || ''}</h3>
        <p class="event-date">${event.displayDate || event.start || ''}</p>
      `;
      card.style.cursor = 'pointer';
    }

    eventList.appendChild(card);
  });
};

// --- Navigation Functions ---
const scrollUp = () => {
  if (currentIndex > 0) {
    currentIndex--;
    renderEvents();
  }
};

const scrollDown = () => {
  if (currentIndex < selectedEvents.length - 1) {
    currentIndex++;
    renderEvents();
  }
};

// --- Category Update and Filtering ---
const updateEventList = (category) => {
  const scrollUpButton = document.getElementById('scroll-up');
  const scrollDownButton = document.getElementById('scroll-down');
  if (scrollUpButton) scrollUpButton.removeEventListener('click', scrollUp);
  if (scrollDownButton) scrollDownButton.removeEventListener('click', scrollDown);

  if (category === 'all') {
    selectedEvents = allEvents.slice();
  } else {
    selectedEvents = allEvents.filter(event => event.category === category);
  }

  selectedEvents.sort((a, b) => eventTimestamp(a) - eventTimestamp(b));

  currentIndex = 0;
  renderEvents();

  if (scrollUpButton) scrollUpButton.addEventListener('click', scrollUp);
  if (scrollDownButton) scrollDownButton.addEventListener('click', scrollDown);
};

// --- Initialization ---
document.addEventListener('DOMContentLoaded', () => {
  fetch("../data/events.json")
    .then(response => {
      if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
      return response.json();
    })
    .then(data => {
      allEvents = Array.isArray(data) ? data : (data.normalizedEvents || []);
      console.log("Events data loaded successfully:", allEvents);

      const categoryButtons = document.querySelectorAll(".cat-btn");
      categoryButtons.forEach(button => {
        button.addEventListener('click', (event) => {
          event.preventDefault();

          // --- Active button logic ---
          categoryButtons.forEach(btn => btn.parentElement.classList.remove('active'));
          button.parentElement.classList.add('active');

          const url = new URL(button.href);
          const category = url.searchParams.get('category');
          updateEventList(category);
        });
      });

      // Set default category and active button
      const currentUrl = new URL(window.location.href);
      const defaultCategory = currentUrl.searchParams.get('category') || 'all';
      updateEventList(defaultCategory);
      categoryButtons.forEach(btn => {
        const url = new URL(btn.href);
        const btnCategory = url.searchParams.get('category');
        if (btnCategory === defaultCategory) btn.parentElement.classList.add('active');
      });
    })
    .catch(error => {
      console.error('Problem fetching events data:', error);
      const eventList = document.getElementById("event-list");
      if (eventList) eventList.innerHTML = `<p class="error-message">Failed to load events. Please try again later.</p>`;
    });
});
