/**
 * Appy Documentation JavaScript
 * Handles sidebar navigation, dark mode toggle, code copy, and mobile menu
 */

// Import CSS for Vite bundling
import '../css/docs.css';

// Import Flowbite
import { initFlowbite } from 'flowbite';

// Import Highlight.js
import hljs from 'highlight.js/lib/core';
import bash from 'highlight.js/lib/languages/bash';
import xml from 'highlight.js/lib/languages/xml';
import php from 'highlight.js/lib/languages/php';
import javascript from 'highlight.js/lib/languages/javascript';
import json from 'highlight.js/lib/languages/json';
import nginx from 'highlight.js/lib/languages/nginx';
import apache from 'highlight.js/lib/languages/apache';
import dockerfile from 'highlight.js/lib/languages/dockerfile';
import yaml from 'highlight.js/lib/languages/yaml';
import plaintext from 'highlight.js/lib/languages/plaintext';

// Register languages
hljs.registerLanguage('bash', bash);
hljs.registerLanguage('shell', bash);
hljs.registerLanguage('sh', bash);
hljs.registerLanguage('xml', xml);
hljs.registerLanguage('html', xml);
hljs.registerLanguage('php', php);
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('js', javascript);
hljs.registerLanguage('json', json);
hljs.registerLanguage('nginx', nginx);
hljs.registerLanguage('apache', apache);
hljs.registerLanguage('dockerfile', dockerfile);
hljs.registerLanguage('docker', dockerfile);
hljs.registerLanguage('yaml', yaml);
hljs.registerLanguage('yml', yaml);
hljs.registerLanguage('plaintext', plaintext);
hljs.registerLanguage('text', plaintext);

// Initialize Flowbite on page load
document.addEventListener('DOMContentLoaded', () => {
    initFlowbite();
    initDarkMode();
    initSidebarNavigation();
    initCodeHighlighting();
    initCodeCopy();
    initMobileSidebar();
    initSmoothScroll();
});

/**
 * Dark Mode Toggle
 * Persists preference to localStorage
 */
function initDarkMode() {
    const themeToggleDarkIcon = document.getElementById('theme-toggle-dark-icon');
    const themeToggleLightIcon = document.getElementById('theme-toggle-light-icon');
    const themeToggleBtn = document.getElementById('theme-toggle');

    if (!themeToggleBtn) return;

    // Set initial icon state
    if (localStorage.getItem('color-theme') === 'dark' ||
        (!('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        themeToggleLightIcon?.classList.remove('hidden');
    } else {
        themeToggleDarkIcon?.classList.remove('hidden');
    }

    // Toggle handler
    themeToggleBtn.addEventListener('click', () => {
        themeToggleDarkIcon?.classList.toggle('hidden');
        themeToggleLightIcon?.classList.toggle('hidden');

        if (localStorage.getItem('color-theme')) {
            if (localStorage.getItem('color-theme') === 'light') {
                document.documentElement.classList.add('dark');
                localStorage.setItem('color-theme', 'dark');
            } else {
                document.documentElement.classList.remove('dark');
                localStorage.setItem('color-theme', 'light');
            }
        } else {
            if (document.documentElement.classList.contains('dark')) {
                document.documentElement.classList.remove('dark');
                localStorage.setItem('color-theme', 'light');
            } else {
                document.documentElement.classList.add('dark');
                localStorage.setItem('color-theme', 'dark');
            }
        }
    });
}

/**
 * Sidebar Navigation
 * Highlights active page and expands parent sections
 */
function initSidebarNavigation() {
    const currentPath = window.location.pathname;
    const navLinks = document.querySelectorAll('.nav-link');

    navLinks.forEach(link => {
        const href = link.getAttribute('href');

        // Check if this link matches current page
        if (href && (currentPath.endsWith(href) || currentPath.includes(href.replace('.html', '')))) {
            link.classList.add('active');

            // If inside a collapsible section, expand it
            const parentCollapse = link.closest('[data-accordion-content]');
            if (parentCollapse) {
                parentCollapse.classList.remove('hidden');
                const trigger = document.querySelector(`[data-accordion-target="#${parentCollapse.id}"]`);
                if (trigger) {
                    trigger.setAttribute('aria-expanded', 'true');
                }
            }
        }
    });
}

/**
 * Code Syntax Highlighting
 * Uses Highlight.js to add syntax highlighting to code blocks
 */
function initCodeHighlighting() {
    // Highlight all code blocks
    document.querySelectorAll('pre code').forEach((el) => {
        hljs.highlightElement(el);
    });
}

/**
 * Code Block Copy Button
 * Adds copy functionality to all code blocks
 */
function initCodeCopy() {
    const codeBlocks = document.querySelectorAll('.code-block');

    codeBlocks.forEach(block => {
        const copyBtn = block.querySelector('.copy-btn');
        const codeElement = block.querySelector('code');

        if (!copyBtn || !codeElement) return;

        copyBtn.addEventListener('click', async () => {
            try {
                await navigator.clipboard.writeText(codeElement.textContent);

                // Show copied state
                const originalText = copyBtn.textContent;
                copyBtn.textContent = 'Copied!';
                copyBtn.classList.add('copied');

                // Reset after 2 seconds
                setTimeout(() => {
                    copyBtn.textContent = originalText;
                    copyBtn.classList.remove('copied');
                }, 2000);
            } catch (err) {
                console.error('Failed to copy:', err);
            }
        });
    });
}

/**
 * Mobile Sidebar Toggle
 * Handles drawer behavior on mobile devices
 */
function initMobileSidebar() {
    const sidebarToggle = document.getElementById('sidebar-toggle');
    const sidebar = document.getElementById('docs-sidebar');
    const backdrop = document.getElementById('sidebar-backdrop');

    if (!sidebarToggle || !sidebar) return;

    // Toggle sidebar
    sidebarToggle.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        backdrop?.classList.toggle('hidden');
        document.body.classList.toggle('overflow-hidden');
    });

    // Close on backdrop click
    backdrop?.addEventListener('click', () => {
        sidebar.classList.add('-translate-x-full');
        backdrop.classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
    });

    // Close on escape key
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && !sidebar.classList.contains('-translate-x-full')) {
            sidebar.classList.add('-translate-x-full');
            backdrop?.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
        }
    });

    // Close sidebar when clicking a link (mobile)
    const navLinks = sidebar.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', () => {
            if (window.innerWidth < 640) {
                sidebar.classList.add('-translate-x-full');
                backdrop?.classList.add('hidden');
                document.body.classList.remove('overflow-hidden');
            }
        });
    });
}

/**
 * Smooth Scroll for Anchor Links
 * Scrolls smoothly to anchor targets with offset for fixed header
 */
function initSmoothScroll() {
    const anchorLinks = document.querySelectorAll('a[href^="#"]');

    anchorLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            const targetId = link.getAttribute('href');
            if (targetId === '#') return;

            const target = document.querySelector(targetId);
            if (target) {
                e.preventDefault();

                // Offset for any fixed header (adjust as needed)
                const offset = 80;
                const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - offset;

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

                // Update URL hash without jumping
                history.pushState(null, null, targetId);
            }
        });
    });
}

/**
 * Table of Contents Generator (optional)
 * Automatically generates TOC from h2/h3 headings
 */
function generateTableOfContents(containerSelector, tocSelector) {
    const container = document.querySelector(containerSelector);
    const toc = document.querySelector(tocSelector);

    if (!container || !toc) return;

    const headings = container.querySelectorAll('h2, h3');
    const tocList = document.createElement('ul');
    tocList.className = 'space-y-2';

    headings.forEach((heading, index) => {
        // Add ID if not present
        if (!heading.id) {
            heading.id = `heading-${index}`;
        }

        const li = document.createElement('li');
        const a = document.createElement('a');

        a.href = `#${heading.id}`;
        a.textContent = heading.textContent;
        a.className = heading.tagName === 'H3'
            ? 'block pl-4 text-sm text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white'
            : 'block text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-300 dark:hover:text-blue-400';

        li.appendChild(a);
        tocList.appendChild(li);
    });

    toc.appendChild(tocList);
}

// Export for potential external use
window.DocsJS = {
    initDarkMode,
    initSidebarNavigation,
    initCodeCopy,
    initMobileSidebar,
    initSmoothScroll,
    generateTableOfContents
};
