$(function() {

  // ============================
  // NAVBAR SCROLL
  // ============================
  $(window).on('scroll', function() {
    if ($(this).scrollTop() > 60) {
      $('#mainNav').addClass('scrolled');
      $('#scrollTop').addClass('show');
    } else {
      $('#mainNav').removeClass('scrolled');
      $('#scrollTop').removeClass('show');
    }
    // Active nav
    $('section[id]').each(function() {
      const top = $(this).offset().top - 90;
      const bot = top + $(this).outerHeight();
      const id  = $(this).attr('id');
      if ($(window).scrollTop() >= top && $(window).scrollTop() < bot) {
        $('.nav-link').removeClass('');
        $(`a[href="#${id}"]`).addClass('');
      }
    });
  });

  // ============================
  // SMOOTH SCROLL
  // ============================
  $('a[href^="#"]').on('click', function(e) {
    const target = $(this.getAttribute('href'));
    if (target.length) {
      e.preventDefault();
      $('html,body').animate({ scrollTop: target.offset().top - 75 }, 600, 'swing');
      // Close mobile menu
      $('#navMenu').collapse('hide');
    }
  });

  // ============================
  // FADE IN ON SCROLL
  // ============================
  const observer = new IntersectionObserver(entries => {
    entries.forEach(e => {
      if (e.isIntersecting) {
        e.target.classList.add('visible');
      }
    });
  }, { threshold: 0.1 });

  document.querySelectorAll('.fade-in-up').forEach(el => observer.observe(el));

  // ============================
  // CALENDAR
  // ============================
  const events = {
    '2026-5-10':  [{ label:'Clean-Up Day', type:'event' }],
    '2026-5-15':  [{ label:'Road Work', type:'event' }],
    '2026-5-20':  [{ label:'Town Hall', type:'event' }],
    '2026-5-27':  [{ label:'Council Mtg', type:'event' }],
    '2026-5-4':   [{ label:'Today', type:'today' }],
  };

  let curYear = 2026, curMonth = 5; // May 2026

  function renderCalendar(year, month) {
    const months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    $('#calMonthYear').text(`${months[month-1]} ${year}`);

    const firstDay = new Date(year, month-1, 1).getDay();
    const daysInMonth = new Date(year, month, 0).getDate();
    const daysInPrev  = new Date(year, month-1, 0).getDate();

    let html = '';
    let day  = 1, nextDay = 1;

    for (let i = 0; i < 42; i++) {
      if (i < firstDay) {
        const d = daysInPrev - firstDay + 1 + i;
        html += `<div class="cal-cell other-month"><div class="day-num">${d}</div></div>`;
      } else if (day <= daysInMonth) {
        const key = `${year}-${month}-${day}`;
        const isToday = (year === 2026 && month === 5 && day === 4);
        let cls = isToday ? ' today' : '';
        let evHtml = '';
        if (events[key]) {
          events[key].forEach(ev => {
            evHtml += `<div class="cal-event-dot ${ev.type === 'urgent' ? 'urgent' : ''}">${ev.label}</div>`;
          });
        }
        html += `<div class="cal-cell${cls}"><div class="day-num">${isToday ? `<span>${day}</span>` : day}</div>${evHtml}</div>`;
        day++;
      } else {
        html += `<div class="cal-cell other-month"><div class="day-num">${nextDay++}</div></div>`;
      }
    }
    $('#calGrid').html(html);
  }

  renderCalendar(curYear, curMonth);

  $('#prevMonth').on('click', function() {
    curMonth--;
    if (curMonth < 1) { curMonth = 12; curYear--; }
    renderCalendar(curYear, curMonth);
  });
  $('#nextMonth').on('click', function() {
    curMonth++;
    if (curMonth > 12) { curMonth = 1; curYear++; }
    renderCalendar(curYear, curMonth);
  });

}); // end $(function)

// ============================
// DOCUMENT CATEGORIES TOGGLE
// ============================
function toggleCategory(header) {
  const cat = header.closest('.doc-category');
  const isOpen = cat.classList.contains('open');
  // close all
  document.querySelectorAll('.doc-category').forEach(c => c.classList.remove('open'));
  if (!isOpen) cat.classList.add('open');
}

// ============================
// DOCUMENT DOWNLOAD
// ============================
function downloadDoc(item) {
  const name = item.querySelector('.doc-item-name').textContent;
  showToast('Downloading File', `"${name}" download started.`, 'success');
}

// ============================
// TOAST NOTIFICATIONS
// ============================
function showToast(title, msg, type = 'info') {
  const iconMap = { success: 'bi-check-circle-fill success', info: 'bi-info-circle-fill info', error: 'bi-x-circle-fill error' };
  const icon = iconMap[type] || iconMap.info;
  const id = 'toast_' + Date.now();
  const html = `
    <div class="toast-custom ${type}" id="${id}">
      <i class="bi ${icon} toast-icon ${type}"></i>
      <div class="toast-body-t">
        <div class="toast-title">${title}</div>
        <div class="toast-msg">${msg}</div>
      </div>
    </div>`;
  $('#toastContainer').append(html);
  setTimeout(() => $(`#${id}`).fadeOut(300, function(){ $(this).remove(); }), 4000);
}

// ============================
// FORMS
// ============================
function handleSignup(e) {
  e.preventDefault();
  showToast('Successfully Subscribed!', 'You will receive email and SMS updates from City of Houston Acres.', 'success');
  e.target.reset();
}

function handleContact(e) {
  e.preventDefault();
  showToast('Message Sent!', 'Thank you for contacting City Hall. We\'ll respond within 2–3 business days.', 'success');
  e.target.reset();
}

// ============================
// LOGIN MODAL
// ============================
function openLoginModal(e) {
  e.preventDefault();
  $('#loginModal').css('display','flex');
  $('body').css('overflow','hidden');
}
function closeLoginModal() {
  $('#loginModal').hide();
  $('body').css('overflow','');
}
// close on backdrop click
$('#loginModal').on('click', function(e) {
  if (e.target === this) closeLoginModal();
});

function handleLogin(e) {
  e.preventDefault();
  showToast('Authentication Required', 'Please contact the administrator to set up your leadership credentials.', 'info');
  closeLoginModal();
}