<!DOCTYPE html>
<html lang="{{ current_lang() }}">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    {# Title #}
    <title>{% block title %}{{ (page.title if page is defined and page and page.title is defined else site.config.title)
        }}{% if page is defined and page and page.title is defined %} - {{ site.config.title }}{% endif %}{% endblock %}
    </title>

    {# Meta description - automatically pre-computed by renderer (page.meta_description cached_property) #}
    {% set meta_desc = meta_desc | default(site.config.get('description'), '') %}

    {# Meta Description - Auto-generate if not provided #}
    <meta name="description" content="{{ meta_desc }}">

    {# Meta Keywords - use page.keywords or fallback to tags #}
    {% if page and page.keywords is defined and page.keywords %}
    <meta name="keywords" content="{{ page.keywords | join(', ') }}">
    {% elif page and page.tags is defined and page.tags %}
    <meta name="keywords" content="{{ page.tags | meta_keywords(10) }}">
    {% endif %}

    {# Open Graph / Facebook #}
    <meta property="og:type" content="{% if page %}article{% else %}website{% endif %}">
    <meta property="og:title"
        content="{{ (page.title if page is defined and page and page.title is defined else site.config.title) }}">
    {% if meta_desc %}
    <meta property="og:description" content="{{ meta_desc }}">
    {% endif %}
    {% if site.config.baseurl %}
    <meta property="og:url"
        content="{{ canonical_url((page.url if page is defined and page and page.url is defined else '/')) }}">
    {% endif %}
    {# Open Graph Image #}
    {% if page and page.metadata is defined and page.metadata.get('image') %}
    <meta property="og:image" content="{{ og_image(page.metadata.get('image')) }}">
    {% elif site.config.get('og_image') %}
    <meta property="og:image" content="{{ og_image(site.config.get('og_image')) }}">
    {% endif %}

    {# Twitter Card #}
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title"
        content="{{ (page.title if page is defined and page and page.title is defined else site.config.title) }}">
    {% if meta_desc %}
    <meta name="twitter:description" content="{{ meta_desc }}">
    {% endif %}
    {% if page and page.metadata is defined and page.metadata.get('image') %}
    <meta name="twitter:image" content="{{ og_image(page.metadata.get('image')) }}">
    {% elif site.config.get('og_image') %}
    <meta name="twitter:image" content="{{ og_image(site.config.get('og_image')) }}">
    {% endif %}

    {# Bengal config meta for JS to read without template tags inside scripts #}
    <meta name="bengal:search_preload" content="{{ site.config.get('search_preload', 'smart') }}">

    {# Canonical URL #}
    {% if site.config.baseurl %}
    <link rel="canonical"
        href="{{ canonical_url((page.url if page is defined and page and page.url is defined else '/')) }}">
    {% endif %}

    {# RSS Feed (locale-aware when i18n prefix strategy is enabled) #}
    {% set _lang = current_lang() %}
    {% set _i18n = site.config.get('i18n', {}) %}
    {% set _rss_href = '/rss.xml' %}
    {% if _i18n and _i18n.get('strategy') == 'prefix' %}
    {% set _default_lang = _i18n.get('default_language', 'en') %}
    {% set _default_in_subdir = _i18n.get('default_in_subdir', False) %}
    {% if _lang and (_default_in_subdir or _lang != _default_lang) %}
    {% set _rss_href = '/' ~ _lang ~ '/rss.xml' %}
    {% endif %}
    {% endif %}
    <link rel="alternate" type="application/rss+xml" title="{{ site.config.title }} RSS Feed" href="{{ _rss_href }}">

    {# hreflang alternates for translated pages #}
    {% for alt in alternate_links(page) %}
    <link rel="alternate" hreflang="{{ alt.hreflang }}" href="{{ alt.href }}">
    {% endfor %}

    {# Favicon #}
    {% set favicon_path = site.config.get('site', {}).get('favicon') %}
    {% if favicon_path %}
    <link rel="icon" type="image/png" href="{{ favicon_path }}">
    {% else %}
    <link rel="icon" type="image/svg+xml" href="{{ asset_url('favicon.svg') }}">
    {% endif %}

    {# Stylesheets #}
    <link rel="stylesheet" href="{{ asset_url('css/style.css') }}">

    {# Theme initialization (prevent flash) #}
    <script>
        (function () {
            const theme = localStorage.getItem('bengal-theme') ||
                (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
            document.documentElement.setAttribute('data-theme', theme);
        })();
    </script>

    {% block extra_head %}{% endblock %}
    {# Generator and build meta #}
    {% include 'partials/meta-generator.html' %}

    {# Optional JSON bootstrap for client-side scripts #}
    {% if config.get('expose_metadata_json') %}
    <script id="bengal-bootstrap" type="application/json">{{ bengal | jsonify }}</script>
    <script>
        (function () {
            var el = document.getElementById('bengal-bootstrap');
            if (el) { window.__BENGAL__ = JSON.parse(el.textContent || '{}'); }
        })();
    </script>
    {% endif %}
</head>

<body
    class="page-kind-{{ page.kind if page and page.kind is defined else 'page' }} {% if page and page.draft is defined and page.draft %}draft-page{% endif %} {% if page and page.tags is defined and (page | has_tag('featured')) %}featured-content{% endif %}">
    {# Skip to main content for accessibility #}
    <a href="#main-content" class="skip-link">Skip to main content</a>

    {# Header #}
    <header role="banner">
        <nav role="navigation" aria-label="Main navigation">
            <div class="container">
                {# Logo / Site Title #}
                <a href="/" class="logo">{{ site.config.title }}</a>

                {# Desktop Navigation #}
                <div class="nav-main hidden-mobile">
                    {# Try manual menu config first, fallback to auto-discovery #}
                    {% set main_menu = get_menu_lang('main', current_lang()) %}
                    {% set auto_nav = get_auto_nav() if not main_menu else [] %}

                    {% if main_menu or auto_nav %}
                    <ul>
                        {# Manual menu items (if configured) #}
                        {% if main_menu %}
                        {% for item in main_menu %}
                        <li
                            class="{{ 'active' if item.active else '' }} {{ 'active-trail' if item.active_trail else '' }}">
                            <a href="{{ item.url }}">{{ item.name }}</a>
                            {% if item.children %}
                            <ul class="submenu">
                                {% for child in item.children %}
                                <li class="{{ 'active' if child.active else '' }}">
                                    <a href="{{ child.url }}">{{ child.name }}</a>
                                </li>
                                {% endfor %}
                            </ul>
                            {% endif %}
                        </li>
                        {% endfor %}
                        {% endif %}

                        {# Auto-discovered nav items (if no manual config) #}
                        {% if auto_nav %}
                        {# Always show Home first in auto mode #}
                        <li class="{{ 'active' if page.url == '/' else '' }}">
                            <a href="/">Home</a>
                        </li>
                        {% for item in auto_nav %}
                        <li class="{{ 'active' if page.url.startswith(item.url) and item.url != '/' else '' }}">
                            <a href="{{ item.url }}">{{ item.name }}</a>
                        </li>
                        {% endfor %}
                        {% endif %}

                        {# Search link #}
                        <li>
                            <a href="/search/" title="Search (⌘K)">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                    stroke-width="2">
                                    <circle cx="11" cy="11" r="8"></circle>
                                    <path d="m21 21-4.35-4.35"></path>
                                </svg>
                                <span>Search</span>
                            </a>
                        </li>
                        {% block nav_items %}{% endblock %}
                    </ul>
                    {% endif %}

                    {# Theme Toggle #}
                    <button class="theme-toggle" aria-label="Toggle dark mode" title="Toggle theme">
                        <svg class="icon-sun" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
                        </svg>
                        <svg class="icon-moon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
                        </svg>
                    </button>
                </div>

                {# Mobile Menu Toggle #}
                <button class="mobile-nav-toggle visible-mobile" aria-label="Open menu" aria-expanded="false">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M4 6h16M4 12h16M4 18h16" />
                    </svg>
                </button>
            </div>
        </nav>
    </header>

    {# Mobile Navigation #}
    <nav class="mobile-nav" role="navigation" aria-label="Mobile navigation">
        <div class="mobile-nav-header">
            <span class="logo">{{ site.config.title }}</span>
            <button class="mobile-nav-close" aria-label="Close menu">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>
        {# Try manual menu config first, fallback to auto-discovery #}
        {% set main_menu = get_menu_lang('main', current_lang()) %}
        {% set auto_nav = get_auto_nav() if not main_menu else [] %}

        {% if main_menu or auto_nav %}
        <ul>
            {# Manual menu items (if configured) #}
            {% if main_menu %}
            {% for item in main_menu %}
            <li class="{{ 'has-submenu' if item.children else '' }} {{ 'active' if item.active else '' }}">
                <a href="{{ item.url }}">{{ item.name }}</a>
                {% if item.children %}
                <ul class="submenu">
                    {% for child in item.children %}
                    <li class="{{ 'active' if child.active else '' }}">
                        <a href="{{ child.url }}">{{ child.name }}</a>
                    </li>
                    {% endfor %}
                </ul>
                {% endif %}
            </li>
            {% endfor %}
            {% endif %}

            {# Auto-discovered nav items (if no manual config) #}
            {% if auto_nav %}
            {# Always show Home first in auto mode #}
            <li class="{{ 'active' if page.url == '/' else '' }}">
                <a href="/">Home</a>
            </li>
            {% for item in auto_nav %}
            <li class="{{ 'active' if page.url.startswith(item.url) and item.url != '/' else '' }}">
                <a href="{{ item.url }}">{{ item.name }}</a>
            </li>
            {% endfor %}
            {% endif %}

            {% block mobile_nav_items %}{% endblock %}
        </ul>
        {% endif %}
    </nav>

    {# Main Content #}
    <main id="main-content" role="main">
        <div class="container">
            {% block content %}{% endblock %}
        </div>
    </main>

    {# Footer #}
    <footer role="contentinfo">
        <div class="container">
            {# Popular Tags Widget - dogfooding popular_tags() function #}
            {% from 'partials/content-components.html' import popular_tags_widget with context %}
            {{ popular_tags_widget(limit=10) }}

            <p class="footer-copyright">
                &copy; 2025 {{ site.config.title }} | Built with <a href="https://github.com/bengal-ssg/bengal"
                    rel="noopener">Bengal SSG</a>
            </p>
            {% set footer_menu = get_menu_lang('footer', current_lang()) %}
            {% if footer_menu %}
            <ul class="footer-links">
                {% for item in footer_menu %}
                <li><a href="{{ item.url }}">{{ item.name }}</a></li>
                {% endfor %}
            </ul>
            {% endif %}
        </div>
    </footer>

    {# JavaScript #}
    <script src="{{ asset_url('js/theme-toggle.js') }}"></script>
    <script src="{{ asset_url('js/mobile-nav.js') }}"></script>
    <script src="{{ asset_url('js/tabs.js') }}"></script>
    <script src="{{ asset_url('js/toc.js') }}"></script>
    <script src="{{ asset_url('js/main.js') }}"></script>
    <script src="{{ asset_url('js/interactive.js') }}"></script>
    <script src="{{ asset_url('js/copy-link.js') }}"></script>
    <script src="{{ asset_url('js/lightbox.js') }}"></script>

    {# Tabulator for data tables #}
    <script src="{{ asset_url('js/tabulator.min.js') }}"></script>
    <script src="{{ asset_url('js/data-table.js') }}"></script>

    {# Lunr.js for search (local copy avoids CDN integrity issues) #}
    <script src="{{ asset_url('js/lunr.min.js') }}"></script>
    <script src="{{ asset_url('js/search.js') }}"></script>

    {# Smart search index preloading #}
    <script>
        (function () {
            const preloadMode = (document.querySelector('meta[name="bengal:search_preload"]').content) || 'smart';
            let preloadTriggered = false;

            function preloadSearch() {
                if (preloadTriggered || !window.BengalSearch) return;
                preloadTriggered = true;

                console.log('🔍 Preloading search index...');
                window.BengalSearch.load();
            }

            // Immediate: Load right away (best for small sites <100 pages)
            if (preloadMode === 'immediate') {
                document.addEventListener('DOMContentLoaded', preloadSearch);
            }
            // Smart: Load on user intent signals (default, best for most sites)
            else if (preloadMode === 'smart') {
                document.addEventListener('DOMContentLoaded', function () {
                    // Preload on search link hover (user likely to search)
                    const searchLinks = document.querySelectorAll('a[href="/search/"], a[href*="search"]');
                    searchLinks.forEach(link => {
                        link.addEventListener('mouseenter', preloadSearch, { once: true });
                        link.addEventListener('focus', preloadSearch, { once: true });
                    });

                    // Preload if user presses Cmd/Ctrl (likely ⌘K)
                    document.addEventListener('keydown', function (e) {
                        if (e.metaKey || e.ctrlKey) {
                            preloadSearch();
                        }
                    }, { once: true });
                });
            }
            // Lazy: Only load when search is actually opened (best for large sites >500 pages)
            // No preloading - index loads on first search
        })();
    </script>

    {% block extra_js %}{% endblock %}
</body>

</html>
