// Markdown navigation system
(function initMarkdownNav() {
  let currentFile = 'FAQ.md';
  const defaultFile = 'FAQ.md';
  
  // Available markdown files for navigation
  const availableFiles = [
    'FAQ.md',
    'README.md',
    'FEATURES.md',
    'QUICK-REFERENCE.md',
    'ORDER-PERSISTENCE.md',
    'IMPLEMENTATION-SUMMARY.md'
  ];

  async function loadMarkdown(filename) {
    const container = document.getElementById('readme-content');
    
    try {
      const response = await fetch(`/${filename}`, {cache: 'no-cache'});
      if (!response.ok) throw new Error(`${filename} not found`);
      
      const markdown = await response.text();
      let html = marked.parse(markdown);
      
      // Convert .md links to clickable navigation
      html = html.replace(/href="([^"]+\.md)"/g, (match, mdFile) => {
        const basename = mdFile.split('/').pop();
        if (availableFiles.includes(basename)) {
          return `href="#" data-md-file="${basename}"`;
        }
        return match;
      });
      
      container.innerHTML = html;
      currentFile = filename;
      
      // Update home button visibility
      updateHomeButton();
      
      // Add click handlers to markdown links
      attachMarkdownLinks();
      
    } catch (err) {
      console.error('Error loading markdown:', err);
      container.innerHTML = `<p>❌ Documentation unavailable: ${filename}</p>`;
    }
  }

  function updateHomeButton() {
    let homeBtn = document.getElementById('md-home-btn');
    
    if (currentFile === defaultFile) {
      // Hide home button on default page
      if (homeBtn) homeBtn.style.display = 'none';
    } else {
      // Show/create home button on other pages
      if (!homeBtn) {
        homeBtn = document.createElement('button');
        homeBtn.id = 'md-home-btn';
        homeBtn.className = 'md-nav-btn';
        homeBtn.innerHTML = `
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
            <polyline points="9 22 9 12 15 12 15 22"></polyline>
          </svg>
          <span>Back to FAQ</span>
        `;
        homeBtn.title = 'Back to FAQ';
        homeBtn.addEventListener('click', () => loadMarkdown(defaultFile));
        
        const readmeSection = document.getElementById('readme-section');
        readmeSection.insertBefore(homeBtn, readmeSection.firstChild);
      }
      homeBtn.style.display = 'flex';
    }
  }

  function attachMarkdownLinks() {
    const links = document.querySelectorAll('#readme-content a[data-md-file]');
    links.forEach(link => {
      link.addEventListener('click', (e) => {
        e.preventDefault();
        const mdFile = link.getAttribute('data-md-file');
        if (mdFile && availableFiles.includes(mdFile)) {
          loadMarkdown(mdFile);
          // Scroll to readme section
          document.getElementById('readme-section').scrollIntoView({ behavior: 'smooth' });
        }
      });
    });
  }

  // Initial load
  loadMarkdown(defaultFile);
})();
