/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

document.addEventListener('DOMContentLoaded', () => {
    // Smooth scrolling for internal links (primarily for sidebar navigation)
    const internalLinks = document.querySelectorAll('.main-navigation a[href^="#"], .site-title a[href^="#"]');
    internalLinks.forEach(anchor => {
        anchor.addEventListener('click', function (this: HTMLAnchorElement, e: Event) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            if (targetId) {
                const targetElement = document.querySelector(targetId);
                if (targetElement) {
                    // Custom scroll to account for potential fixed header on mobile after stacking
                    // For desktop, with fixed sidebar, standard scrollIntoView is fine.
                    // On mobile, the sidebar becomes static.
                    let offset = 0;
                    if (window.innerWidth <= 768) { // Mobile breakpoint where nav stacks
                        const mobileNav = document.querySelector('.sidebar-nav') as HTMLElement;
                        if (mobileNav && getComputedStyle(mobileNav).position === 'static') {
                           // offset = mobileNav.offsetHeight; // No offset needed if nav is static
                        }
                    }

                    const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset - offset;

                    window.scrollTo({
                        top: targetPosition,
                        behavior: 'smooth'
                    });

                    // If navigation is collapsible on mobile and open, close it
                    // (Add logic here if a collapsible mobile menu is implemented)
                }
            }
        });
    });

    // Dynamic Year for Footer (now in sidebar)
    const currentYearSpan = document.getElementById('currentYear');
    if (currentYearSpan) {
        currentYearSpan.textContent = new Date().getFullYear().toString();
    }

    // Contact Form basic submission handling
    const contactForm = document.getElementById('contactForm');
    if (contactForm) {
        contactForm.addEventListener('submit', (e: Event) => {
            e.preventDefault();
            const formData = new FormData(e.target as HTMLFormElement);
            const data: { [key: string]: FormDataEntryValue } = {};
            formData.forEach((value, key) => {
                data[key] = value;
            });
            console.log('Form Submitted:', data);
            // Basic alert, replace with actual submission logic
            alert('Thank you for your message! (This is a demo - no email sent)');
            (e.target as HTMLFormElement).reset();
        });
    }

    // Sections and Nav Links for active state highlighting
    const sections = Array.from(document.querySelectorAll<HTMLElement>('main.content-area section[id]'));
    const navLiAnchors = document.querySelectorAll<HTMLAnchorElement>('.main-navigation ul li a');

    // IntersectionObserver for active nav link
    // Adjust threshold and rootMargin as needed for the new layout
    // A negative rootMargin top can help trigger "active" slightly before section top hits viewport top
    const observerOptions = {
      root: null, // observing intersections with the viewport
      rootMargin: '0px 0px -40% 0px', // Triggers when section is 60% from top of viewport
      threshold: 0.1 // Small threshold, triggers when even a little bit is visible
    };

    let lastObservedSectionId: string | null = null;

    const observer = new IntersectionObserver((entries) => {
      let currentVisibleSectionId: string | null = null;

      entries.forEach(entry => {
        if (entry.isIntersecting) {
            // Prioritize the section that is most visible or the first one intersecting
            if (!currentVisibleSectionId || entry.intersectionRatio > 0.5) {
                 currentVisibleSectionId = entry.target.id;
            }
        }
      });

      // If multiple sections are "intersecting" due to thresholds,
      // this logic attempts to find the "most current" one.
      // A more robust solution might involve tracking scroll direction or exact positions.
      if (currentVisibleSectionId) {
          lastObservedSectionId = currentVisibleSectionId;
      } else if (entries.length > 0 && !currentVisibleSectionId && lastObservedSectionId === null) {
          // Fallback for initial load if first section is not fully meeting criteria
          // but is the only one observed.
          const firstEntry = entries.find(e => e.target.id === sections[0]?.id);
          if (firstEntry?.isIntersecting || window.scrollY < sections[0]?.offsetHeight * 0.5) {
            lastObservedSectionId = sections[0]?.id;
          }
      }


      navLiAnchors.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('href')?.substring(1) === lastObservedSectionId) {
          link.classList.add('active');
        }
      });

    }, observerOptions);

    sections.forEach(section => {
      observer.observe(section);
    });

    // Initial check in case a section is already in view on load (e.g. from hash URL)
    // For a cleaner initial active state, especially with hashes:
    if (window.location.hash) {
        const initialSectionId = window.location.hash.substring(1);
        const initialLink = document.querySelector(`.main-navigation a[href="#${initialSectionId}"]`);
        if (initialLink) {
            navLiAnchors.forEach(link => link.classList.remove('active'));
            initialLink.classList.add('active');
            lastObservedSectionId = initialSectionId;
        }
    } else if (sections.length > 0) {
        // Default to first nav item if no hash
        navLiAnchors.forEach(link => link.classList.remove('active'));
        const firstNavLink = navLiAnchors[0];
        if (firstNavLink && firstNavLink.getAttribute('href')?.substring(1) === sections[0].id) {
            firstNavLink.classList.add('active');
            lastObservedSectionId = sections[0].id;
        }
    }
});
