/* ============================================
   20th Kenya Expo — Main JavaScript
   Inexpo Group | Kenya Expo 2026
   ============================================ */

(function() {
  'use strict';

  // === 1. NAVBAR SCROLL HANDLER ===
  const nav = document.getElementById('mainNav');
  const ribbon = document.getElementById('announcementRibbon');
  let lastScroll = 0;

  function handleScroll() {
    const y = window.scrollY;
    if (nav) {
      if (y > 50) {
        nav.classList.add('scrolled');
        nav.style.top = '0';
      } else {
        nav.classList.remove('scrolled');
        nav.style.top = '38px';
      }
    }
    if (ribbon && y > 100) {
      ribbon.classList.add('hidden');
    } else if (ribbon) {
      ribbon.classList.remove('hidden');
    }
    lastScroll = y;
  }
  window.addEventListener('scroll', handleScroll, { passive: true });
  handleScroll();

  // === 2. MOBILE MENU TOGGLE ===
  window.toggleMobileMenu = function() {
    const overlay = document.getElementById('mobileMenuOverlay');
    if (overlay) overlay.classList.toggle('open');
    document.body.style.overflow = overlay && overlay.classList.contains('open') ? 'hidden' : '';
  };

  // === 3. SCROLL REVEAL ANIMATIONS ===
  const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('active');
      }
    });
  }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });

  document.querySelectorAll('.reveal').forEach(el => revealObserver.observe(el));

  // === 4. ANIMATED COUNTERS ===
  const counterObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting && !entry.target.classList.contains('counted')) {
        entry.target.classList.add('counted');
        const target = parseInt(entry.target.dataset.target, 10);
        const suffix = entry.target.dataset.suffix || '';
        const duration = 2000;
        const start = performance.now();
        function update(now) {
          const elapsed = now - start;
          const progress = Math.min(elapsed / duration, 1);
          const eased = 1 - Math.pow(1 - progress, 3);
          entry.target.textContent = Math.floor(eased * target) + suffix;
          if (progress < 1) requestAnimationFrame(update);
        }
        requestAnimationFrame(update);
      }
    });
  }, { threshold: 0.5 });

  document.querySelectorAll('[data-target]').forEach(el => counterObserver.observe(el));

  // === 5. FORM AJAX SUBMISSION ===
  function bindAjaxForms() {
    document.querySelectorAll('form').forEach(form => {
      if (form.id === 'newsletterForm' || form.dataset.ajax === 'true' || form.querySelector('[name="type"]')) {
        form.addEventListener('submit', async function(e) {
          e.preventDefault();
          const btn = form.querySelector('button[type="submit"]');
          const originalText = btn ? btn.innerHTML : '';
          if (btn) { btn.disabled = true; btn.innerHTML = '<span class="spinner" style="width:18px;height:18px;border-width:2px;display:inline-block;vertical-align:middle;"></span> Sending...'; }

          const formData = new FormData(form);
          const data = Object.fromEntries(formData.entries());
          const csrf = document.querySelector('meta[name="csrf-token"]')?.content || data._csrf || '';

          try {
            const res = await fetch('/api/submit_lead.php', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrf
              },
              body: JSON.stringify(data)
            });
            const json = await res.json();
            if (json.success) {
              showToast(json.message || 'Thank you! We\'ll be in touch.', 'success');
              form.reset();
              if (form.id === 'newsletterForm') {
                const toast = document.getElementById('newsletterToast');
                if (toast) { toast.textContent = 'Subscribed successfully!'; toast.style.display = 'block'; toast.style.color = 'var(--success)'; }
              }
            } else {
              showToast(json.error || 'Something went wrong. Please try again.', 'error');
            }
          } catch (err) {
            showToast('Network error. Please try again.', 'error');
          } finally {
            if (btn) { btn.disabled = false; btn.innerHTML = originalText; }
          }
        });
      }
    });
  }
  bindAjaxForms();

  // === 6. TOAST NOTIFICATIONS ===
  window.showToast = function(message, type) {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    const toast = document.createElement('div');
    toast.className = 'toast-message toast-' + (type || 'success');
    toast.textContent = message;
    container.appendChild(toast);
    setTimeout(() => { toast.style.opacity = '0'; toast.style.transform = 'translateX(120%)'; setTimeout(() => toast.remove(), 400); }, 4000);
  };

  // === 7. GALLERY LIGHTBOX ===
  let galleryImages = [];
  let currentLightboxIndex = 0;

  function initLightbox() {
    const items = document.querySelectorAll('.gallery-item');
    galleryImages = Array.from(items).map(item => ({
      url: item.dataset.url,
      title: item.dataset.title,
      caption: item.dataset.caption
    }));

    items.forEach((item, i) => {
      item.addEventListener('click', () => openLightbox(i));
    });
  }

  function openLightbox(index) {
    currentLightboxIndex = index;
    let overlay = document.getElementById('lightboxOverlay');
    if (!overlay) {
      overlay = document.createElement('div');
      overlay.id = 'lightboxOverlay';
      overlay.className = 'lightbox-overlay';
      overlay.innerHTML = `
        <button class="lightbox-close" onclick="closeLightbox()" aria-label="Close"><i class="fas fa-times"></i></button>
        <button class="lightbox-nav lightbox-prev" onclick="navLightbox(-1)" aria-label="Previous"><i class="fas fa-chevron-left"></i></button>
        <button class="lightbox-nav lightbox-next" onclick="navLightbox(1)" aria-label="Next"><i class="fas fa-chevron-right"></i></button>
        <img id="lightboxImg" class="lightbox-img" src="" alt="">
        <div class="lightbox-caption"><h4 id="lightboxTitle"></h4><p id="lightboxCaption"></p></div>
      `;
      overlay.addEventListener('click', function(e) { if (e.target === this) closeLightbox(); });
      document.addEventListener('keydown', handleLightboxKey);
      document.body.appendChild(overlay);
    }
    updateLightbox();
    overlay.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  window.closeLightbox = function() {
    const overlay = document.getElementById('lightboxOverlay');
    if (overlay) { overlay.classList.remove('active'); document.body.style.overflow = ''; }
  };

  window.navLightbox = function(dir) {
    currentLightboxIndex = (currentLightboxIndex + dir + galleryImages.length) % galleryImages.length;
    updateLightbox();
  };

  function updateLightbox() {
    const img = galleryImages[currentLightboxIndex];
    const imgEl = document.getElementById('lightboxImg');
    const titleEl = document.getElementById('lightboxTitle');
    const capEl = document.getElementById('lightboxCaption');
    if (imgEl) imgEl.src = img.url;
    if (titleEl) titleEl.textContent = img.title;
    if (capEl) capEl.textContent = img.caption;
  }

  function handleLightboxKey(e) {
    const overlay = document.getElementById('lightboxOverlay');
    if (!overlay || !overlay.classList.contains('active')) return;
    if (e.key === 'Escape') closeLightbox();
    if (e.key === 'ArrowLeft') navLightbox(-1);
    if (e.key === 'ArrowRight') navLightbox(1);
  }

  // Initialize lightbox on gallery pages
  if (document.querySelector('.gallery-grid')) initLightbox();

  // === 8. GALLERY FILTER PILLS ===
  const filterPills = document.querySelectorAll('.filter-pill');
  filterPills.forEach(pill => {
    pill.addEventListener('click', function() {
      const filter = this.dataset.filter;
      filterPills.forEach(p => p.classList.remove('active'));
      this.classList.add('active');
      document.querySelectorAll('.gallery-item').forEach(item => {
        item.style.display = (!filter || filter === 'all' || item.dataset.category === filter) ? '' : 'none';
      });
    });
  });

  // === 9. ACTIVE NAV LINK DETECTION ===
  const currentPath = window.location.pathname;
  document.querySelectorAll('#mainNav .nav-link, .mobile-nav-list a').forEach(link => {
    if (link.getAttribute('href') === currentPath || (currentPath === '/' && link.getAttribute('href') === '/index.php')) {
      link.classList.add('active');
    }
  });

  // === 10. SMOOTH SCROLL ===
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
      const href = this.getAttribute('href');
      if (href === '#') return;
      const target = document.querySelector(href);
      if (target) {
        e.preventDefault();
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    });
  });

  // === 11. PACKAGES PAGE — FILTER PILLS ===
  const pkgFilterBtns = document.querySelectorAll('.pkg-filter-btn');
  pkgFilterBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      const filter = this.dataset.filter;
      pkgFilterBtns.forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      document.querySelectorAll('.pkg-card').forEach(card => {
        const name = card.dataset.name;
        card.closest('.pkg-col').style.display = (!filter || filter === 'all' || name === filter) ? '' : 'none';
      });
    });
  });

  // === 12. PACKAGES — ENQUIRE NOW CLICK ===
  document.querySelectorAll('.pkg-enquire-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const pkgName = this.dataset.package;
      const select = document.getElementById('enquiryPackage');
      if (select) select.value = pkgName;
      const form = document.getElementById('enquiry-form');
      if (form) form.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  });

  // === 13. SPONSORSHIP — BECOME SPONSOR CLICK ===
  document.querySelectorAll('.spon-enquire-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const tier = this.dataset.tier;
      const select = document.getElementById('sponEnquiryTier');
      if (select) select.value = tier;
      const form = document.getElementById('sponsorship-enquiry');
      if (form) form.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  });

  // === 14. ADMIN LEADS SEARCH + FILTER ===
  window.adminLeads = {
    init: function() {
      const searchInput = document.getElementById('leadsSearch');
      const filterTabs = document.querySelectorAll('.admin-filter-tab');
      const rows = document.querySelectorAll('.lead-row');
      let currentFilter = 'all';

      if (searchInput) {
        searchInput.addEventListener('input', () => this.filterRows(searchInput.value, currentFilter));
      }
      filterTabs.forEach(tab => {
        tab.addEventListener('click', () => {
          currentFilter = tab.dataset.filter;
          filterTabs.forEach(t => t.classList.remove('active'));
          tab.classList.add('active');
          this.filterRows(searchInput ? searchInput.value : '', currentFilter);
        });
      });
      this.filterRows('', 'all');
    },
    filterRows: function(search, typeFilter) {
      const rows = document.querySelectorAll('.lead-row');
      const term = (search || '').toLowerCase();
      let visible = 0;
      rows.forEach(row => {
        const text = (row.textContent || '').toLowerCase();
        const type = row.dataset.type;
        const matchesSearch = !term || text.includes(term);
        const matchesType = !typeFilter || typeFilter === 'all' || type === typeFilter;
        row.style.display = matchesSearch && matchesType ? '' : 'none';
        if (matchesSearch && matchesType) visible++;
      });
      const countEl = document.getElementById('leadsCount');
      if (countEl) countEl.textContent = visible;
    }
  };

  // === 15. ADMIN KPI REFRESH ===
  window.refreshStats = async function() {
    try {
      const res = await fetch('/api/get_stats.php');
      const data = await res.json();
      const fields = ['totalLeads','exhibitorLeads','visitorLeads','sponsorLeads','newsletterLeads','todayLeads','totalGallery','totalPackages','totalSponsorship'];
      fields.forEach(f => {
        const el = document.getElementById(f);
        if (el && data[f.toLowerCase().replace(/([A-Z])/g, '_$1').replace(/^_/, '').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase()] !== undefined) {
          const key = f.toLowerCase().replace(/([A-Z])/g, '_$1').replace(/^_/, '').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
          el.textContent = data[key] ?? data[key.replace(/s$/, '')] ?? '0';
        }
      });
    } catch(e) { console.error('Stats refresh failed', e); }
  };

  // === 16. ADMIN GALLERY MANAGER ===
  window.adminGallery = {
    images: [],
    init: function() {
      try {
        const el = document.getElementById('galleryData');
        this.images = el ? JSON.parse(el.textContent) : [];
      } catch(e) { this.images = []; }
      this.bindEvents();
    },
    bindEvents: function() {
      document.querySelectorAll('.gallery-edit-btn').forEach(btn => {
        btn.addEventListener('click', () => this.openEditModal(btn.dataset.id));
      });
      document.querySelectorAll('.gallery-delete-btn').forEach(btn => {
        btn.addEventListener('click', () => this.deleteImage(btn.dataset.id, btn.dataset.title));
      });
      const addForm = document.getElementById('addImageForm');
      if (addForm) addForm.addEventListener('submit', (e) => { e.preventDefault(); this.submitAddForm(); });
      const editForm = document.getElementById('editImageForm');
      if (editForm) editForm.addEventListener('submit', (e) => { e.preventDefault(); this.submitEditForm(); });
    },
    openAddModal: function() {
      const form = document.getElementById('addImageForm');
      if (form) form.reset();
      const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('addImageModal'));
      modal.show();
    },
    openEditModal: function(id) {
      const img = this.images.find(i => i.id === id);
      if (!img) return;
      document.getElementById('editImageId').value = img.id;
      document.getElementById('editImageUrl').value = img.url || '';
      document.getElementById('editImageTitle').value = img.title || '';
      document.getElementById('editImageCategory').value = img.category || 'expo';
      document.getElementById('editImageCaption').value = img.caption || '';
      document.getElementById('editImageAlt').value = img.alt || '';
      document.getElementById('editImageFeatured').checked = img.featured || false;
      document.getElementById('editImageSort').value = img.sort_order || 0;
      const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editImageModal'));
      modal.show();
    },
    deleteImage: async function(id, title) {
      if (!confirm('Delete image "' + (title || id) + '"?')) return;
      try {
        const res = await fetch('/api/gallery_delete.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id })
        });
        const json = await res.json();
        if (json.success) {
          showToast('Image deleted', 'success');
          const card = document.querySelector('.admin-gallery-card[data-id="' + id + '"]');
          if (card) card.remove();
          this.images = this.images.filter(i => i.id !== id);
        } else {
          showToast(json.error || 'Delete failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    submitAddForm: async function() {
      const form = document.getElementById('addImageForm');
      const data = Object.fromEntries(new FormData(form).entries());
      data.featured = !!form.querySelector('[name="featured"]')?.checked;
      data.sort_order = parseInt(data.sort_order, 10) || 0;
      try {
        const res = await fetch('/api/gallery_add.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        const json = await res.json();
        if (json.success) {
          showToast('Image added', 'success');
          this.images.push(json.image);
          location.reload();
        } else {
          showToast(json.error || 'Add failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    submitEditForm: async function() {
      const form = document.getElementById('editImageForm');
      const data = Object.fromEntries(new FormData(form).entries());
      data.featured = !!form.querySelector('[name="featured"]')?.checked;
      data.sort_order = parseInt(data.sort_order, 10) || 0;
      try {
        const res = await fetch('/api/gallery_update.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        const json = await res.json();
        if (json.success) {
          showToast('Image updated', 'success');
          const idx = this.images.findIndex(i => i.id === data.id);
          if (idx >= 0) this.images[idx] = json.image;
          location.reload();
        } else {
          showToast(json.error || 'Update failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    }
  };

  // === 17. ADMIN PACKAGES MANAGER ===
  window.adminPackages = {
    data: [],
    init: function() {
      try {
        const el = document.getElementById('pkgData');
        this.data = el ? JSON.parse(el.textContent) : [];
      } catch(e) { this.data = []; }
      this.bindEvents();
    },
    bindEvents: function() {
      document.querySelectorAll('.pkg-edit-btn').forEach(btn => {
        btn.addEventListener('click', () => this.openEditModal(btn.dataset.id));
      });
      document.querySelectorAll('.pkg-delete-btn').forEach(btn => {
        btn.addEventListener('click', () => this.deletePackage(btn.dataset.id, btn.dataset.name));
      });
      document.querySelectorAll('.pkg-toggle-btn').forEach(btn => {
        btn.addEventListener('click', () => this.toggleActive(btn.dataset.id, btn.dataset.active === '1'));
      });
      const addForm = document.getElementById('addPkgForm');
      if (addForm) addForm.addEventListener('submit', (e) => { e.preventDefault(); this.submitAddForm(); });
      const editForm = document.getElementById('editPkgForm');
      if (editForm) editForm.addEventListener('submit', (e) => { e.preventDefault(); this.submitEditForm(); });
    },
    openAddModal: function() {
      const form = document.getElementById('addPkgForm');
      if (form) form.reset();
      const container = document.getElementById('addPkgFeatures');
      if (container) container.innerHTML = '';
      this.addFeatureRow('addPkgFeatures');
      const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('addPkgModal'));
      modal.show();
    },
    openEditModal: function(id) {
      const pkg = this.data.find(p => p.id === id);
      if (!pkg) return;
      document.getElementById('editPkgId').value = pkg.id;
      document.getElementById('editPkgName').value = pkg.name || '';
      document.getElementById('editPkgBadge').value = pkg.badge || '';
      document.getElementById('editPkgHighlight').checked = pkg.highlight || false;
      document.getElementById('editPkgPriceLabel').value = pkg.price_label || '';
      document.getElementById('editPkgPriceNote').value = pkg.price_note || '';
      document.getElementById('editPkgIcon').value = pkg.icon || '';
      document.getElementById('editPkgColor').value = pkg.color || '#9AA5B4';
      document.getElementById('editPkgSpace').value = pkg.space_sqm || 9;
      document.getElementById('editPkgCtaLabel').value = pkg.cta_label || 'Enquire Now';
      document.getElementById('editPkgSort').value = pkg.sort_order || 0;
      document.getElementById('editPkgActive').checked = pkg.active || false;
      const container = document.getElementById('editPkgFeatures');
      if (container) {
        container.innerHTML = '';
        (pkg.features || []).forEach(f => this.addFeatureRow('editPkgFeatures', f.label, f.value));
      }
      const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editPkgModal'));
      modal.show();
    },
    deletePackage: async function(id, name) {
      if (!confirm('Delete package "' + (name || id) + '"?')) return;
      try {
        const res = await fetch('/api/packages_delete.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id })
        });
        const json = await res.json();
        if (json.success) {
          showToast('Package deleted', 'success');
          const card = document.querySelector('.admin-pkg-card[data-id="' + id + '"]');
          if (card) card.remove();
          this.data = this.data.filter(p => p.id !== id);
        } else {
          showToast(json.error || 'Delete failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    addFeatureRow: function(containerId, labelVal, valueVal) {
      const container = document.getElementById(containerId);
      if (!container) return;
      const row = document.createElement('div');
      row.className = 'feature-row';
      row.innerHTML = '<input type="text" class="form-control" placeholder="Label" value="' + (labelVal || '') + '" style="flex:1;"><input type="text" class="form-control" placeholder="Value" value="' + (valueVal || '') + '" style="flex:1;"><button type="button" class="btn-icon btn-icon-danger" onclick="adminPackages.removeFeatureRow(this)"><i class="fas fa-times"></i></button>';
      container.appendChild(row);
    },
    removeFeatureRow: function(btn) {
      btn.closest('.feature-row').remove();
    },
    collectFeatures: function(containerId) {
      const rows = document.querySelectorAll('#' + containerId + ' .feature-row');
      const features = [];
      rows.forEach(row => {
        const inputs = row.querySelectorAll('input');
        if (inputs[0] && inputs[0].value.trim()) {
          features.push({ label: inputs[0].value.trim(), value: inputs[1] ? inputs[1].value.trim() : '' });
        }
      });
      return features;
    },
    buildPayload: function(formId, featureContainerId) {
      const form = document.getElementById(formId);
      const data = Object.fromEntries(new FormData(form).entries());
      data.highlight = !!form.querySelector('[name="highlight"]')?.checked;
      data.active = !!form.querySelector('[name="active"]')?.checked;
      data.space_sqm = parseInt(data.space_sqm, 10) || 0;
      data.sort_order = parseInt(data.sort_order, 10) || 0;
      data.features = this.collectFeatures(featureContainerId);
      return data;
    },
    submitAddForm: async function() {
      const data = this.buildPayload('addPkgForm', 'addPkgFeatures');
      try {
        const res = await fetch('/api/packages_save.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        const json = await res.json();
        if (json.success) {
          showToast('Package added', 'success');
          location.reload();
        } else {
          showToast(json.error || 'Add failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    submitEditForm: async function() {
      const data = this.buildPayload('editPkgForm', 'editPkgFeatures');
      try {
        const res = await fetch('/api/packages_save.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        const json = await res.json();
        if (json.success) {
          showToast('Package updated', 'success');
          location.reload();
        } else {
          showToast(json.error || 'Update failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    toggleActive: async function(id, currentState) {
      try {
        const res = await fetch('/api/packages_save.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id, active: !currentState })
        });
        const json = await res.json();
        if (json.success) {
          showToast('Package ' + (!currentState ? 'activated' : 'deactivated'), 'success');
          location.reload();
        }
      } catch(e) { showToast('Network error', 'error'); }
    }
  };

  // === 18. ADMIN SPONSORSHIP MANAGER ===
  window.adminSponsorship = {
    data: [],
    init: function() {
      try {
        const el = document.getElementById('sponData');
        this.data = el ? JSON.parse(el.textContent) : [];
      } catch(e) { this.data = []; }
      this.bindEvents();
    },
    bindEvents: function() {
      document.querySelectorAll('.spon-edit-btn').forEach(btn => {
        btn.addEventListener('click', () => this.openEditModal(btn.dataset.id));
      });
      document.querySelectorAll('.spon-delete-btn').forEach(btn => {
        btn.addEventListener('click', () => this.deleteTier(btn.dataset.id, btn.dataset.name));
      });
      document.querySelectorAll('.spon-toggle-btn').forEach(btn => {
        btn.addEventListener('click', () => this.toggleActive(btn.dataset.id, btn.dataset.active === '1'));
      });
      document.querySelectorAll('.slot-inc-btn').forEach(btn => {
        btn.addEventListener('click', () => this.updateSlots(btn.dataset.id, parseInt(btn.dataset.delta, 10)));
      });
      const addForm = document.getElementById('addSponForm');
      if (addForm) addForm.addEventListener('submit', (e) => { e.preventDefault(); this.submitAddForm(); });
      const editForm = document.getElementById('editSponForm');
      if (editForm) editForm.addEventListener('submit', (e) => { e.preventDefault(); this.submitEditForm(); });
    },
    openAddModal: function() {
      const form = document.getElementById('addSponForm');
      if (form) form.reset();
      const bContainer = document.getElementById('addSponBenefits');
      if (bContainer) bContainer.innerHTML = '';
      this.addBenefitRow('addSponBenefits');
      const vContainer = document.getElementById('addSponVisibility');
      if (vContainer) vContainer.innerHTML = '';
      this.addVisibilityRow('addSponVisibility');
      const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('addSponModal'));
      modal.show();
    },
    openEditModal: function(id) {
      const tier = this.data.find(t => t.id === id);
      if (!tier) return;
      document.getElementById('editSponId').value = tier.id;
      document.getElementById('editSponTier').value = tier.tier || '';
      document.getElementById('editSponBadge').value = tier.badge || '';
      document.getElementById('editSponHighlight').checked = tier.highlight || false;
      document.getElementById('editSponPriceLabel').value = tier.price_label || '';
      document.getElementById('editSponPriceNote').value = tier.price_note || '';
      document.getElementById('editSponIcon').value = tier.icon || '';
      document.getElementById('editSponColor').value = tier.color || '#D4AF37';
      document.getElementById('editSponSort').value = tier.sort_order || 0;
      document.getElementById('editSponActive').checked = tier.active || false;
      document.getElementById('editSponSlotsAvail').value = tier.slots_available || 0;
      document.getElementById('editSponSlotsTaken').value = tier.slots_taken || 0;
      const bContainer = document.getElementById('editSponBenefits');
      if (bContainer) {
        bContainer.innerHTML = '';
        (tier.benefits || []).forEach(b => this.addBenefitRow('editSponBenefits', b));
      }
      const vContainer = document.getElementById('editSponVisibility');
      if (vContainer) {
        vContainer.innerHTML = '';
        (tier.visibility_items || []).forEach(v => this.addVisibilityRow('editSponVisibility', v));
      }
      const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editSponModal'));
      modal.show();
    },
    deleteTier: async function(id, name) {
      if (!confirm('Delete tier "' + (name || id) + '"?')) return;
      try {
        const res = await fetch('/api/sponsorship_delete.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id })
        });
        const json = await res.json();
        if (json.success) {
          showToast('Tier deleted', 'success');
          const card = document.querySelector('.admin-spon-card[data-id="' + id + '"]');
          if (card) card.remove();
          this.data = this.data.filter(t => t.id !== id);
        } else {
          showToast(json.error || 'Delete failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    addBenefitRow: function(containerId, value) {
      const container = document.getElementById(containerId);
      if (!container) return;
      const row = document.createElement('div');
      row.className = 'benefit-row';
      row.innerHTML = '<textarea class="form-control" rows="2" placeholder="Benefit description" style="flex:1;">' + (value || '') + '</textarea><button type="button" class="btn-icon btn-icon-danger" onclick="adminSponsorship.removeBenefitRow(this)"><i class="fas fa-times"></i></button>';
      container.appendChild(row);
    },
    removeBenefitRow: function(btn) {
      btn.closest('.benefit-row').remove();
    },
    collectBenefits: function(containerId) {
      const rows = document.querySelectorAll('#' + containerId + ' .benefit-row textarea');
      return Array.from(rows).map(t => t.value.trim()).filter(v => v);
    },
    addVisibilityRow: function(containerId, value) {
      const container = document.getElementById(containerId);
      if (!container) return;
      const row = document.createElement('div');
      row.className = 'visibility-row';
      row.innerHTML = '<input type="text" class="form-control" placeholder="Visibility item" value="' + (value || '') + '" style="flex:1;"><button type="button" class="btn-icon btn-icon-danger" onclick="adminSponsorship.removeVisibilityRow(this)"><i class="fas fa-times"></i></button>';
      container.appendChild(row);
    },
    removeVisibilityRow: function(btn) {
      btn.closest('.visibility-row').remove();
    },
    collectVisibility: function(containerId) {
      const rows = document.querySelectorAll('#' + containerId + ' .visibility-row input');
      return Array.from(rows).map(i => i.value.trim()).filter(v => v);
    },
    buildPayload: function(formId, benefitContainerId, visibilityContainerId) {
      const form = document.getElementById(formId);
      const data = Object.fromEntries(new FormData(form).entries());
      data.highlight = !!form.querySelector('[name="highlight"]')?.checked;
      data.active = !!form.querySelector('[name="active"]')?.checked;
      data.sort_order = parseInt(data.sort_order, 10) || 0;
      data.slots_available = parseInt(data.slots_available, 10) || 0;
      data.slots_taken = parseInt(data.slots_taken, 10) || 0;
      data.benefits = this.collectBenefits(benefitContainerId);
      data.visibility_items = this.collectVisibility(visibilityContainerId);
      return data;
    },
    submitAddForm: async function() {
      const data = this.buildPayload('addSponForm', 'addSponBenefits', 'addSponVisibility');
      try {
        const res = await fetch('/api/sponsorship_save.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        const json = await res.json();
        if (json.success) {
          showToast('Sponsorship tier added', 'success');
          location.reload();
        } else {
          showToast(json.error || 'Add failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    submitEditForm: async function() {
      const data = this.buildPayload('editSponForm', 'editSponBenefits', 'editSponVisibility');
      try {
        const res = await fetch('/api/sponsorship_save.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        const json = await res.json();
        if (json.success) {
          showToast('Sponsorship tier updated', 'success');
          location.reload();
        } else {
          showToast(json.error || 'Update failed', 'error');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    updateSlots: async function(id, delta) {
      const tier = this.data.find(t => t.id === id);
      if (!tier) return;
      const newTaken = Math.max(0, (tier.slots_taken || 0) + delta);
      try {
        const res = await fetch('/api/sponsorship_save.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id, slots_taken: newTaken })
        });
        const json = await res.json();
        if (json.success) {
          tier.slots_taken = newTaken;
          const indicator = document.querySelector('.admin-spon-card[data-id="' + id + '"] .slot-indicator span');
          if (indicator) indicator.textContent = (tier.slots_available - newTaken) + ' of ' + tier.slots_available + ' available';
          showToast('Slots updated', 'success');
        }
      } catch(e) { showToast('Network error', 'error'); }
    },
    toggleActive: async function(id, currentState) {
      try {
        const res = await fetch('/api/sponsorship_save.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id, active: !currentState })
        });
        const json = await res.json();
        if (json.success) {
          showToast('Tier ' + (!currentState ? 'activated' : 'deactivated'), 'success');
          location.reload();
        }
      } catch(e) { showToast('Network error', 'error'); }
    }
  };

  // === 19. INITIALIZE ADMIN MODULES ON DOM READY ===
  document.addEventListener('DOMContentLoaded', function() {
    if (document.getElementById('pkgData')) adminPackages.init();
    if (document.getElementById('sponData')) adminSponsorship.init();
    if (document.getElementById('galleryData')) adminGallery.init();
    if (document.querySelector('.admin-leads-table')) adminLeads.init();
    if (document.getElementById('totalLeads')) refreshStats();
  });

  // === 20. EVENT COUNTDOWN ===
  window.initCountdown = function(targetDate, elementId) {
    const el = document.getElementById(elementId);
    if (!el) return;
    function update() {
      const diff = new Date(targetDate) - new Date();
      if (diff <= 0) { el.textContent = '0'; return; }
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      el.textContent = days;
    }
    update();
    setInterval(update, 60000);
  };

})();
