/**
 * AppForge Documentation v1.2.0
 * Common JavaScript functionality for documentation pages
 */

// Theme Management
function toggleTheme() {
  const current = document.documentElement.getAttribute('data-theme');
  const next = current === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', next);
  localStorage.setItem('docs-theme', next);
}

// Initialize theme on page load
function initTheme() {
  const stored = localStorage.getItem('docs-theme');
  if (stored) {
    document.documentElement.setAttribute('data-theme', stored);
  } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.documentElement.setAttribute('data-theme', 'dark');
  }
}

// Sidebar Management
function toggleSidebar() {
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebarOverlay');
  if (sidebar) sidebar.classList.toggle('open');
  if (overlay) overlay.classList.toggle('open');
}

// Close sidebar when clicking outside on mobile
function closeSidebar() {
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebarOverlay');
  if (sidebar) sidebar.classList.remove('open');
  if (overlay) overlay.classList.remove('open');
}

// FAQ Accordion
function toggleFAQ(element) {
  const answer = element.nextElementSibling;
  const arrow = element.querySelector('.faq-arrow');
  
  if (answer) {
    answer.classList.toggle('open');
  }
  
  if (arrow) {
    arrow.style.transform = answer && answer.classList.contains('open') 
      ? 'rotate(180deg)' 
      : 'rotate(0)';
  }
}

// FAQ Search/Filter
function filterFAQs() {
  const searchInput = document.getElementById('searchInput');
  if (!searchInput) return;
  
  const query = searchInput.value.toLowerCase();
  const faqItems = document.querySelectorAll('.faq-item');
  
  faqItems.forEach(item => {
    const text = item.textContent.toLowerCase();
    item.style.display = text.includes(query) ? 'block' : 'none';
  });
}

// Smooth Scroll to Section
function scrollToSection(id) {
  const element = document.getElementById(id);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
}

// Copy Code to Clipboard
function copyCode(button) {
  const codeBlock = button.closest('.code-block');
  const code = codeBlock ? codeBlock.querySelector('code') : null;
  
  if (code) {
    navigator.clipboard.writeText(code.textContent).then(() => {
      const originalText = button.textContent;
      button.textContent = 'Copied!';
      button.classList.add('copied');
      
      setTimeout(() => {
        button.textContent = originalText;
        button.classList.remove('copied');
      }, 2000);
    }).catch(err => {
      console.error('Failed to copy:', err);
    });
  }
}

// Tab Navigation
function switchTab(tabGroup, tabId) {
  const group = document.querySelector(`[data-tab-group="${tabGroup}"]`);
  if (!group) return;
  
  // Update tab buttons
  group.querySelectorAll('.tab-btn').forEach(btn => {
    btn.classList.remove('active');
    if (btn.dataset.tab === tabId) {
      btn.classList.add('active');
    }
  });
  
  // Update tab content
  group.querySelectorAll('.tab-content').forEach(content => {
    content.classList.remove('active');
    if (content.id === tabId) {
      content.classList.add('active');
    }
  });
}

// Highlight current section in sidebar based on scroll position
function updateActiveSidebarLink() {
  const sections = document.querySelectorAll('section[id], h2[id], h3[id]');
  const sidebarLinks = document.querySelectorAll('.sidebar-link-sub');
  
  let currentSection = '';
  
  sections.forEach(section => {
    const rect = section.getBoundingClientRect();
    if (rect.top <= 100) {
      currentSection = section.id;
    }
  });
  
  sidebarLinks.forEach(link => {
    const href = link.getAttribute('href');
    if (href && href.includes('#' + currentSection)) {
      link.classList.add('active');
    } else {
      link.classList.remove('active');
    }
  });
}

// Debounce utility
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', () => {
  // Set up scroll listener for sidebar highlighting
  const debouncedUpdate = debounce(updateActiveSidebarLink, 50);
  window.addEventListener('scroll', debouncedUpdate, { passive: true });
  
  // Initial sidebar highlight
  updateActiveSidebarLink();
  
  // Add keyboard shortcut for search (Ctrl/Cmd + K)
  document.addEventListener('keydown', (e) => {
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
      e.preventDefault();
      const searchInput = document.getElementById('searchInput');
      if (searchInput) {
        searchInput.focus();
      }
    }
  });
  
  // Close sidebar on escape key
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      closeSidebar();
    }
  });
});

// Run theme initialization immediately
initTheme();
