<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{% endblock %}</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="/static/css/pyst.css">
</head>
<body>
    <!-- Header -->
    <header class="header">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center">
                    <a href="/" class="flex items-center">
                        <img src="/static/img/logo.png" alt="PyST Logo" class="logo mr-3">
                        <span class="text-xl font-semibold" style="color: var(--text-color)">PyST</span>
                    </a>
                </div>
                <div class="flex-1 max-w-md mx-4">
                    <form id="searchForm" class="relative" action="/web/search/" method="get">
                        <div class="relative">
                            <input
                                type="text"
                                name="query"
                                placeholder="Search concepts..."
                                class="w-full px-4 py-2 pl-10 pr-20 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                                autocomplete="off"
                            />
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-search text-gray-400"></i>
                            </div>
                            <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
                                <kbd class="hidden md:inline-flex items-center px-2 py-1.5 text-xs font-semibold border rounded shadow-sm" style="color: var(--text-secondary); background-color: var(--nav-bg); border-color: var(--border-color)">
                                    <span id="shortcut-key">Ctrl</span><span class="mx-0.5">+</span>K
                                </kbd>
                            </div>
                            <input type="hidden" name="semantic" value="true" />
                        </div>
                        <div id="suggestions" class="absolute w-full mt-1 border rounded-lg shadow-lg hidden z-50" style="background-color: var(--header-bg); border-color: var(--border-color)">
                            <!-- Suggestions will be populated here -->
                        </div>
                    </form>
                </div>
                <nav class="flex items-center space-x-4">
                    <button id="theme-toggle" class="nav-link" aria-label="Toggle dark mode">
                        <i class="fas fa-moon"></i>
                    </button>
                    <a href="/web/concept_schemes/?language={{ language }}" class="nav-link {% if request.url.path == '/web/concept_schemes/' %}active{% endif %}">
                        <i class="fas fa-list mr-2"></i>Concept Schemes
                    </a>
<!--                     <a href="/web/concept_scheme/create/" class="nav-link disabled opacity-50 cursor-not-allowed" aria-disabled="true">
                        <i class="fas fa-plus mr-2"></i>Create Scheme
                    </a>
-->
                    <a href="https://docs.pyst.dev/" class="nav-link" target="_blank">
                        <i class="fas fa-book mr-2"></i>Documentation
                    </a>
                    <span class="nav-link">
                        <i class="fas fa-globe mr-2" style="color: var(--text-secondary)"></i>
                        <select id="language" class="mt-1 w-24 pl-3 pr-3 py-2 text-base border rounded-md text-sm" style="color: var(--text-color); background-color: var(--header-bg); border-color: var(--border-color)">
                            {% for row in language_selector %}
                            <option value="{{ row.0 }}">{{ row.1 }}</option>
                            {% endfor %}
                        </select>
                    </span>
                </nav>
            </div>
        </div>
    </header>

    <!-- Page Header -->
    <div class="page-header">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            {% block page_header %}{% endblock %}
        </div>
    </div>

    <!-- Main Content -->
    <main class="py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            {% block content %}{% endblock %}
        </div>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-50 border-t border-gray-200 mt-12">
        <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
            <div class="text-center text-sm text-gray-500">
                <p><a href="https://www.cauldron.ch/">Made by Cauldron Solutions</a> | <a href="https://github.com/cauldron/py-semantic-taxonomy/">Code under MIT License</a></p>
            </div>
        </div>
    </footer>
   <script>
        // Theme handling
        const themeToggle = document.getElementById('theme-toggle');
        const themeIcon = themeToggle.querySelector('i');

        // Check for saved theme preference
        const savedTheme = localStorage.getItem('theme') || 'light';
        document.documentElement.setAttribute('data-theme', savedTheme);
        updateThemeIcon(savedTheme);

        themeToggle.addEventListener('click', () => {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateThemeIcon(newTheme);
        });

        function updateThemeIcon(theme) {
            themeIcon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
        }

        // Prevent clicks on disabled links
        document.querySelectorAll('a[aria-disabled="true"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
            });
        });

        // Detect OS and update shortcut key
        const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
        if (isMac) {
            document.getElementById('shortcut-key').textContent = '⌘';
        } else {
            document.getElementById('shortcut-key').textContent = 'Ctrl';
        }

        // Search functionality
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.querySelector('input[name="query"]');
            const suggestionsDiv = document.getElementById('suggestions');
            let debounceTimer;

            // Handle keyboard shortcut
            document.addEventListener('keydown', function(e) {
                // Check for Cmd+K (Mac) or Ctrl+K (Windows/Linux)
                if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
                    e.preventDefault();
                    searchInput.focus();
                }
            });

            // Debounce function
            function debounce(func, delay) {
                return function() {
                    const context = this;
                    const args = arguments;
                    clearTimeout(debounceTimer);
                    debounceTimer = setTimeout(() => func.apply(context, args), delay);
                };
            }

            // Fetch suggestions
            async function fetchSuggestions(query) {
                if (!query) {
                    suggestionsDiv.classList.add('hidden');
                    return;
                }

                try {
                    const response = await fetch(`{{ suggest_api_url }}?query=${encodeURIComponent(query)}&language=en`);
                    const suggestions = await response.json();

                    if (suggestions.length > 0) {
                        const limitedSuggestions = suggestions.slice(0, 5);
                        const hasMore = suggestions.length > 5;

                        suggestionsDiv.innerHTML = `
                            ${limitedSuggestions.map(suggestion => `
                                <div class="p-2 cursor-pointer transition-colors duration-150 hover-row" onclick="selectSuggestion('${suggestion.label}')" style="color: var(--text-color)">
                                    ${suggestion.label}
                                </div>
                            `).join('')}
                            ${hasMore ? `
                                <div class="p-2 text-sm text-center border-t" style="color: var(--text-secondary); border-color: var(--border-color)">
                                    +${suggestions.length - 5} more results
                                </div>
                            ` : ''}
                        `;
                        suggestionsDiv.classList.remove('hidden');
                    } else {
                        suggestionsDiv.classList.add('hidden');
                    }
                } catch (error) {
                    console.error('Error fetching suggestions:', error);
                    suggestionsDiv.classList.add('hidden');
                }
            }

            // Handle input with debounce
            searchInput.addEventListener('input', debounce(function(e) {
                fetchSuggestions(e.target.value);
            }, 300));

            // Handle suggestion selection
            window.selectSuggestion = function(suggestion) {
                searchInput.value = suggestion;
                suggestionsDiv.classList.add('hidden');
                document.getElementById('searchForm').submit();
            };

            // Close suggestions when clicking outside
            document.addEventListener('click', function(e) {
                if (!searchInput.contains(e.target) && !suggestionsDiv.contains(e.target)) {
                    suggestionsDiv.classList.add('hidden');
                }
            });
        });
    </script>
</body>
</html>
