// Navigation Handler - Redirect parent window
document.getElementById("navSelect").addEventListener("change", (e) => {
  const version = e.target.value;
  
  // Ignore if placeholder is somehow selected
  if (!version) {
    return;
  }
  
  // Get base URL from parent window
  const parentUrl = new URL(window.parent.location.href);
  const baseUrl = parentUrl.origin + parentUrl.pathname;
  
  // Build clean URL with unencoded brackets
  let cleanUrl;
  if (version === 'unreleased') {
    cleanUrl = baseUrl + '?parameters[route]=/changelog';
  } else {
    cleanUrl = baseUrl + `?parameters[route]=/changelog/${version}`;
  }
  
  // Redirect parent window
  window.parent.location.href = cleanUrl;
});

// Section Toggle (keep for manual expand/collapse)
function toggleSection(header) {
  const content = header.nextElementSibling;
  header.classList.toggle("collapsed");
  content.classList.toggle("collapsed");
}

// Search form handling - redirect parent window
const searchForm = document.querySelector('.search-form');
if (searchForm) {
  searchForm.addEventListener('submit', (e) => {
    e.preventDefault(); // Always prevent default form submission
    
    const searchInput = document.getElementById('searchInput');
    const query = searchInput.value.trim();
    
    // Get base URL from parent window
    const parentUrl = new URL(window.parent.location.href);
    const baseUrl = parentUrl.origin + parentUrl.pathname;
    
    // Build clean URL
    let cleanUrl;
    if (query) {
      // Search always goes to base changelog (no version)
      // The 'q' parameter needs to be inside parameters[] for the middleware
      cleanUrl = baseUrl + '?parameters[route]=/changelog&parameters[q]=' + encodeURIComponent(query);
    } else {
      // Clear search - go to current version
      const currentVersion = getCurrentVersionFromURL();
      if (currentVersion !== 'unreleased') {
        cleanUrl = baseUrl + `?parameters[route]=/changelog/${currentVersion}`;
      } else {
        cleanUrl = baseUrl + '?parameters[route]=/changelog';
      }
    }
    
    // Redirect parent window
    window.parent.location.href = cleanUrl;
  });
}

// Helper function to get current version from URL
function getCurrentVersionFromURL() {
  const path = window.location.pathname;
  const match = path.match(/\/changelog\/([^\/]+)$/);
  return match ? match[1] : 'unreleased';
}

// Highlight search results if query exists
function highlightSearchResults(query) {
  if (!query) return;
  
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    null,
    false
  );

  const textNodes = [];
  while (walker.nextNode()) {
    textNodes.push(walker.currentNode);
  }

  textNodes.forEach((node) => {
    const text = node.textContent;
    const regex = new RegExp(`(${escapeRegex(query)})`, "gi");
    if (regex.test(text)) {
      const span = document.createElement("span");
      span.innerHTML = text.replace(regex, '<span class="highlight">$1</span>');
      node.parentNode.replaceChild(span, node);
    }
  });
}

function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// Initialize duplicate toggle functionality
function initDuplicateToggles() {
  // Find all duplicate controls that were rendered by the server
  document.querySelectorAll('.duplicate-controls').forEach(control => {
    const toggleArrow = control.querySelector('.duplicate-toggle-arrow');
    const duplicateCount = parseInt(control.dataset.duplicateCount, 10);
    
    // Add click handler
    control.addEventListener('click', (e) => {
      e.stopPropagation();
      toggleDuplicateRowsForControl(control, toggleArrow, duplicateCount);
    });
  });
}

function toggleDuplicateRowsForControl(control, toggleArrow, duplicateCount) {
  const isCollapsed = toggleArrow.classList.contains('collapsed');
  const groupId = control.dataset.duplicateGroup;
  
  // Find all cells that belong to this duplicate group
  const duplicateCells = document.querySelectorAll(`[data-duplicate-group="${groupId}"]`);
  
  if (isCollapsed) {
    // Expand - show duplicate rows
    duplicateCells.forEach(cell => {
      cell.classList.remove('duplicate-hidden');
    });
    toggleArrow.classList.remove('collapsed');
    toggleArrow.classList.remove('fa-chevron-right');
    toggleArrow.classList.add('fa-chevron-down');
  } else {
    // Collapse - hide duplicate rows
    duplicateCells.forEach(cell => {
      cell.classList.add('duplicate-hidden');
    });
    toggleArrow.classList.add('collapsed');
    toggleArrow.classList.remove('fa-chevron-down');
    toggleArrow.classList.add('fa-chevron-right');
  }
}


// Initialize hover tooltips with dynamic positioning
function initHoverTooltips() {
  // Handle message tooltips
  document.querySelectorAll('.message-wrapper').forEach(wrapper => {
    wrapper.addEventListener('mouseenter', function(e) {
      const tooltip = this.querySelector('.message-full');
      if (tooltip) {
        const rect = this.getBoundingClientRect();
        const viewportHeight = window.innerHeight;
        const viewportWidth = window.innerWidth;
        
        // Position below the element by default
        tooltip.style.left = rect.left + 'px';
        tooltip.style.top = (rect.bottom + 4) + 'px';
        
        // Adjust if it would go off screen
        setTimeout(() => {
          const tooltipRect = tooltip.getBoundingClientRect();
          
          // If tooltip goes below viewport, position above
          if (tooltipRect.bottom > viewportHeight - 20) {
            tooltip.style.top = (rect.top - tooltipRect.height - 4) + 'px';
          }
          
          // If tooltip goes off right edge, align to right
          if (tooltipRect.right > viewportWidth - 20) {
            tooltip.style.left = (viewportWidth - tooltipRect.width - 20) + 'px';
          }
        }, 0);
      }
    });
  });
  
  // Handle file list tooltips
  document.querySelectorAll('.files-wrapper').forEach(wrapper => {
    wrapper.addEventListener('mouseenter', function(e) {
      const tooltip = this.querySelector('.files-list');
      if (tooltip) {
        const rect = this.getBoundingClientRect();
        const viewportHeight = window.innerHeight;
        const viewportWidth = window.innerWidth;
        
        // Position below and right-aligned by default
        tooltip.style.right = (viewportWidth - rect.right) + 'px';
        tooltip.style.top = (rect.bottom + 4) + 'px';
        
        // Adjust if it would go off screen
        setTimeout(() => {
          const tooltipRect = tooltip.getBoundingClientRect();
          
          // If tooltip goes below viewport, position above
          if (tooltipRect.bottom > viewportHeight - 20) {
            tooltip.style.top = (rect.top - tooltipRect.height - 4) + 'px';
          }
          
          // If tooltip goes off left edge, align to left
          if (tooltipRect.left < 20) {
            tooltip.style.right = 'auto';
            tooltip.style.left = '20px';
          }
        }, 0);
      }
    });
  });
}

// Convert timestamps to local timezone
function convertTimestampsToLocal() {
  const elements = document.querySelectorAll('[data-timestamp]');
  console.log(`Found ${elements.length} timestamp elements to convert`);
  
  elements.forEach(element => {
    const timestamp = element.getAttribute('data-timestamp');
    console.log('Processing timestamp:', timestamp);
    
    if (!timestamp) {
      console.warn('Empty timestamp for element:', element);
      return;
    }
    
    try {
      // Parse the timestamp (handles both ISO format and date-only)
      const date = new Date(timestamp);
      if (isNaN(date.getTime())) {
        console.warn('Invalid date for timestamp:', timestamp);
        element.textContent = 'Invalid Date';
        return;
      }
      
      // Format date and time separately for responsive stacking
      const dateOptions = {
        year: 'numeric',
        month: '2-digit', 
        day: '2-digit'
      };
      
      const timeOptions = {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      };
      
      const localDate = date.toLocaleDateString(undefined, dateOptions);
      const localTime = date.toLocaleTimeString(undefined, timeOptions);
      
      console.log(`Converted ${timestamp} to ${localDate} ${localTime}`);
      
      // Replace content with separate date and time elements for responsive stacking
      element.innerHTML = `<div class="timestamp-wrapper"><div class="timestamp-date">${localDate}</div><div class="timestamp-time">${localTime}</div></div>`;
      
      // Add tooltip with original timestamp
      element.title = `Original: ${timestamp}`;
      
    } catch (error) {
      console.error('Failed to parse timestamp:', timestamp, error);
      element.textContent = 'Error';
    }
  });
}

// Initialize
document.addEventListener("DOMContentLoaded", () => {
  // Convert timestamps to local timezone
  convertTimestampsToLocal();
  
  // Initialize hover tooltips
  initHoverTooltips();
  
  // Initialize duplicate toggle controls
  initDuplicateToggles();
  
  // Highlight search results if search query exists
  const urlParams = new URLSearchParams(window.location.search);
  const searchQuery = urlParams.get('q');
  if (searchQuery) {
    highlightSearchResults(searchQuery);
  }
});