/**
 * View Transitions API implementation
 * This file handles smooth transitions between pages using the View Transitions API
 */

// Check if the View Transitions API is supported
// Prevent multiple declarations
if (typeof window.supportsViewTransitions === 'undefined') {
    window.supportsViewTransitions = !!document.startViewTransition;
}

// Function to handle same-document transitions (for SPAs)
function handleSameDocumentTransition(updateDOM) {
  // Fallback for browsers that don't support the API
  if (!window.supportsViewTransitions) {
    updateDOM();
    return;
  }

  // With View Transitions API
  document.startViewTransition(() => updateDOM());
}

// Initialize cross-document transitions
function initCrossDocumentTransitions() {
  // Only proceed if the browser supports the API
  if (!window.supportsViewTransitions) {
    return;
  }

  // Add event listeners to all internal links
  document.addEventListener('click', (e) => {
    // Find the closest anchor element
    const link = e.target.closest('a');
    
    // Skip if no link was clicked or if it's an external link or has a target attribute
    if (!link || link.target || link.hostname !== window.location.hostname) {
      return;
    }

    // Skip if the link has a download attribute or uses a different protocol
    if (link.hasAttribute('download') || 
        (link.getAttribute('href')?.startsWith('#')) ||
        link.getAttribute('href')?.startsWith('mailto:') ||
        link.getAttribute('href')?.startsWith('tel:')) {
      return;
    }

    // Let the View Transitions API handle the navigation
    // The browser will automatically create the transition
    // No need to call any API here as the @view-transition CSS rule handles it
  });
}

// Initialize when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  initCrossDocumentTransitions();
});

// Export functions for use in other scripts
window.viewTransitions = {
  handleSameDocumentTransition,
  supportsViewTransitions: window.supportsViewTransitions
};
