(() => {
  const root = document.documentElement;
  const body = document.body;
  const header = document.querySelector('.site-header');
  const progress = document.querySelector('.scroll-progress span');
  const menuButton = document.querySelector('.menu-toggle');
  const nav = document.querySelector('.site-nav');
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const onScroll = () => {
    const y = window.scrollY;
    header?.classList.toggle('scrolled', y > 16);
    if (progress) {
      const max = Math.max(document.documentElement.scrollHeight - window.innerHeight, 1);
      progress.style.width = `${Math.min((y / max) * 100, 100)}%`;
    }
  };
  window.addEventListener('scroll', onScroll, { passive: true });
  onScroll();

  menuButton?.addEventListener('click', () => {
    const open = nav?.classList.toggle('open') || false;
    menuButton.setAttribute('aria-expanded', String(open));
    body.classList.toggle('menu-open', open);
  });
  nav?.querySelectorAll('a').forEach(link => link.addEventListener('click', () => {
    nav.classList.remove('open');
    menuButton?.setAttribute('aria-expanded', 'false');
    body.classList.remove('menu-open');
  }));

  const revealItems = [...document.querySelectorAll('.reveal')];
  if (!reduceMotion && 'IntersectionObserver' in window) {
    const revealObserver = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('visible');
          revealObserver.unobserve(entry.target);
        }
      });
    }, { threshold: 0.09, rootMargin: '0px 0px -4% 0px' });
    revealItems.forEach(item => revealObserver.observe(item));
  } else {
    revealItems.forEach(item => item.classList.add('visible'));
  }

  const counters = [...document.querySelectorAll('[data-count]')];
  const animateCounter = element => {
    const target = Number(element.dataset.count || 0);
    const suffix = element.dataset.suffix || '';
    if (reduceMotion) {
      element.textContent = `${target}${suffix}`;
      return;
    }
    const duration = 1050;
    const start = performance.now();
    const tick = now => {
      const progressValue = Math.min((now - start) / duration, 1);
      const eased = 1 - Math.pow(1 - progressValue, 3);
      element.textContent = `${Math.max(1, Math.round(target * eased))}${suffix}`;
      if (progressValue < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  };
  if ('IntersectionObserver' in window) {
    const countObserver = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          animateCounter(entry.target);
          countObserver.unobserve(entry.target);
        }
      });
    }, { threshold: .5 });
    counters.forEach(counter => countObserver.observe(counter));
  } else {
    counters.forEach(animateCounter);
  }

  const archiveCards = [...document.querySelectorAll('.archive-card')];
  const filters = [...document.querySelectorAll('.filter')];
  const showAll = document.getElementById('show-all');
  const filterStatus = document.getElementById('filter-status');
  let archiveExpanded = false;
  let currentFilter = 'all';

  function updateArchive() {
    let shown = 0;
    let matches = 0;
    archiveCards.forEach((card, index) => {
      const categories = (card.dataset.category || '').split(/\s+/);
      const matchesFilter = currentFilter === 'all' || categories.includes(currentFilter);
      if (matchesFilter) matches += 1;
      const deferred = Boolean(showAll) && currentFilter === 'all' && !archiveExpanded && index >= 12;
      card.classList.toggle('is-filtered', !matchesFilter);
      card.classList.toggle('is-deferred', matchesFilter && deferred);
      if (matchesFilter && !deferred) shown += 1;
    });
    if (filterStatus) {
      filterStatus.textContent = currentFilter === 'all' && !archiveExpanded
        ? `Showing ${shown} of ${matches} projects`
        : `Showing ${shown} project${shown === 1 ? '' : 's'}`;
    }
    if (showAll) {
      const shouldShow = currentFilter === 'all' && !archiveExpanded && archiveCards.length > 12;
      showAll.closest('.archive-action')?.toggleAttribute('hidden', !shouldShow);
    }
  }

  filters.forEach(button => button.addEventListener('click', () => {
    filters.forEach(item => item.classList.remove('active'));
    button.classList.add('active');
    currentFilter = button.dataset.filter || 'all';
    updateArchive();
  }));
  showAll?.addEventListener('click', () => {
    archiveExpanded = true;
    updateArchive();
  });
  updateArchive();

  const lightbox = document.querySelector('.lightbox');
  const lightboxImage = lightbox?.querySelector('figure img');
  const lightboxTitle = document.getElementById('lightbox-title');
  const lightboxMeta = document.getElementById('lightbox-meta');
  const lightboxDescription = document.getElementById('lightbox-description');
  const lightboxClose = lightbox?.querySelector('.lightbox-close');
  const lightboxPrev = lightbox?.querySelector('.lightbox-prev');
  const lightboxNext = lightbox?.querySelector('.lightbox-next');
  let lightboxIndex = 0;
  let lastTrigger = null;

  const visibleLightboxButtons = () => [...document.querySelectorAll('.archive-card:not(.is-filtered):not(.is-deferred) .archive-media')];
  const renderLightbox = index => {
    const buttons = visibleLightboxButtons();
    if (!buttons.length || !lightboxImage) return;
    lightboxIndex = (index + buttons.length) % buttons.length;
    const button = buttons[lightboxIndex];
    lightboxImage.src = button.dataset.lightbox || '';
    lightboxImage.alt = `${button.dataset.title || 'Portfolio project'} preview`;
    if (lightboxTitle) lightboxTitle.textContent = button.dataset.title || 'Portfolio project';
    if (lightboxMeta) lightboxMeta.textContent = `${button.dataset.meta || 'Selected work'} · ${lightboxIndex + 1} of ${buttons.length}`;
    if (lightboxDescription) lightboxDescription.textContent = button.dataset.description || '';
  };
  const openLightbox = button => {
    if (!lightbox) return;
    const buttons = visibleLightboxButtons();
    lastTrigger = button;
    renderLightbox(Math.max(buttons.indexOf(button), 0));
    lightbox.classList.add('open');
    lightbox.setAttribute('aria-hidden', 'false');
    body.classList.add('lightbox-open');
    lightboxClose?.focus();
  };
  const closeLightbox = () => {
    if (!lightbox) return;
    lightbox.classList.remove('open');
    lightbox.setAttribute('aria-hidden', 'true');
    body.classList.remove('lightbox-open');
    if (lightboxImage) lightboxImage.src = '';
    lastTrigger?.focus();
  };
  document.querySelectorAll('.archive-media').forEach(button => button.addEventListener('click', () => openLightbox(button)));
  document.querySelectorAll('.archive-view').forEach(button => button.addEventListener('click', () => {
    const media = button.closest('.archive-card')?.querySelector('.archive-media');
    if (media) openLightbox(media);
  }));
  lightboxClose?.addEventListener('click', closeLightbox);
  lightboxPrev?.addEventListener('click', () => renderLightbox(lightboxIndex - 1));
  lightboxNext?.addEventListener('click', () => renderLightbox(lightboxIndex + 1));
  lightbox?.addEventListener('click', event => { if (event.target === lightbox) closeLightbox(); });
  document.addEventListener('keydown', event => {
    if (!lightbox?.classList.contains('open')) return;
    if (event.key === 'Escape') closeLightbox();
    if (event.key === 'ArrowLeft') renderLightbox(lightboxIndex - 1);
    if (event.key === 'ArrowRight') renderLightbox(lightboxIndex + 1);
  });

  document.querySelectorAll('[data-slider]').forEach(slider => {
    const slides = [...slider.querySelectorAll('.principle')];
    const current = slider.querySelector('[data-slide-current]');
    let index = 0;
    const show = next => {
      index = (next + slides.length) % slides.length;
      slides.forEach((slide, slideIndex) => slide.classList.toggle('active', slideIndex === index));
      if (current) current.textContent = String(index + 1).padStart(2, '0');
    };
    slider.querySelector('[data-prev]')?.addEventListener('click', () => show(index - 1));
    slider.querySelector('[data-next]')?.addEventListener('click', () => show(index + 1));
  });

  document.querySelectorAll('.faq-list details').forEach(detail => {
    detail.addEventListener('toggle', () => {
      if (!detail.open) return;
      document.querySelectorAll('.faq-list details').forEach(other => {
        if (other !== detail) other.open = false;
      });
    });
  });

  const form = document.getElementById('contact-form');
  const formNote = document.getElementById('form-note');
  form?.addEventListener('submit', event => {
    event.preventDefault();
    if (!form.reportValidity()) return;
    const data = new FormData(form);
    const name = String(data.get('name') || '').trim();
    const email = String(data.get('email') || '').trim();
    const service = String(data.get('service') || '').trim();
    const timeline = String(data.get('timeline') || '').trim();
    const message = String(data.get('message') || '').trim();
    const subject = encodeURIComponent(`Portfolio enquiry — ${service || 'New project'} — ${name}`);
    const emailBody = encodeURIComponent([
      `Hello Adesoye,`, '',
      `My name is ${name}.`,
      `Email: ${email}`,
      `Service: ${service}`,
      `Preferred timeline: ${timeline}`, '',
      `Project details:`, message, '',
      `Regards,`, name
    ].join('\n'));
    if (formNote) {
      formNote.textContent = 'Your email app is opening with the project details prepared.';
      formNote.classList.add('success');
    }
    window.location.href = `mailto:Adesoyemathew@gmail.com?subject=${subject}&body=${emailBody}`;
  });

  const config = window.PORTFOLIO_CONFIG || {};
  document.querySelectorAll('[data-profile]').forEach(link => {
    const key = link.dataset.profile;
    const url = key ? config[key] : '';
    if (url) {
      link.href = url;
      link.target = '_blank';
      link.rel = key === 'linkedin' ? 'noopener noreferrer me' : 'noopener noreferrer';
      if (!link.getAttribute('aria-label')) link.setAttribute('aria-label', key === 'linkedin' ? 'View Adesoye Mathew on LinkedIn' : `View Adesoye Mathew on ${key}`);
      link.hidden = false;
    }
  });

  const year = document.getElementById('year');
  if (year) year.textContent = new Date().getFullYear();

  if (!reduceMotion && window.matchMedia('(pointer:fine)').matches) {
    const cursor = document.querySelector('.cursor');
    let cursorX = -50;
    let cursorY = -50;
    document.addEventListener('mousemove', event => {
      cursorX = event.clientX;
      cursorY = event.clientY;
      if (cursor) {
        cursor.style.transform = `translate(${cursorX - 8}px, ${cursorY - 8}px)`;
        cursor.classList.add('is-visible');
      }
    });
    document.querySelectorAll('a,button,input,select,textarea,.tilt-card').forEach(item => {
      item.addEventListener('mouseenter', () => cursor?.classList.add('is-active'));
      item.addEventListener('mouseleave', () => cursor?.classList.remove('is-active'));
    });

    document.querySelectorAll('.tilt-card').forEach(card => {
      card.addEventListener('mousemove', event => {
        const rect = card.getBoundingClientRect();
        const x = (event.clientX - rect.left) / rect.width - .5;
        const y = (event.clientY - rect.top) / rect.height - .5;
        const base = card.classList.contains('interface-main') ? -4 : card.classList.contains('interface-code') ? 6 : -7;
        card.style.transform = `rotate(${base}deg) rotateX(${-y * 7}deg) rotateY(${x * 8}deg) translateZ(4px)`;
      });
      card.addEventListener('mouseleave', () => { card.style.transform = ''; });
    });

    document.querySelectorAll('.magnetic').forEach(item => {
      item.addEventListener('mousemove', event => {
        const rect = item.getBoundingClientRect();
        const x = event.clientX - rect.left - rect.width / 2;
        const y = event.clientY - rect.top - rect.height / 2;
        item.style.transform = `translate(${x * .08}px, ${y * .12}px)`;
      });
      item.addEventListener('mouseleave', () => { item.style.transform = ''; });
    });
  }
})();
