<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#6366f1">
  <title>{{ page_title }} — {{ project_name }}</title>
  <style>{{ default_css | safe }}</style>
  {% if css_overrides %}
  <style>:root { {{ css_overrides }} }</style>
  {% endif %}
  {% if favicon_path %}
  <link rel="icon" href="{{ favicon_path }}">
  {% endif %}
  {% if custom_css_path %}
  <link rel="stylesheet" href="{{ base_url }}{{ custom_css_path }}">
  {% endif %}
  {% block head %}{% endblock %}
</head>
<body>
  {% block header %}
  <header class="top-header">
    <div class="top-header-left">
      {% if logo_path %}
      <img class="top-header-logo" src="{{ logo_path }}" alt="{{ project_name }} logo">
      {% endif %}
      <span class="top-header-name">{{ project_name }}</span>
    </div>
    {% if search_enabled %}
    <div class="search-wrapper">
      <input type="text" class="search-input" placeholder="Search docs..." aria-label="Search documentation">
      <div class="search-results" role="listbox"></div>
    </div>
    {% endif %}
  </header>
  {% endblock %}

  {% block sidebar %}
  <nav class="sidebar">
    <div class="nav-filter-wrapper">
      <input type="text" class="nav-filter" placeholder="Filter pages..." aria-label="Filter navigation">
    </div>
    {{ nav_html | safe }}
  </nav>
  {% endblock %}

  <main class="content">
    {% block content %}
    {{ content | safe }}
    {% endblock %}

    {% block footer %}
    <div class="footer">
      Built with <a href="https://github.com/docanvil/docanvil">DocAnvil</a>
    </div>
    {% endblock %}
  </main>

  {% block scripts %}
  <script>
  // Tab switching
  document.querySelectorAll('.tab-header').forEach(btn => {
    btn.addEventListener('click', () => {
      const container = btn.closest('.tabs, .code-group');
      const tab = btn.dataset.tab;
      container.querySelectorAll('.tab-header').forEach(b => b.classList.remove('active'));
      container.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
      btn.classList.add('active');
      container.querySelector(`.tab-content[data-tab="${tab}"]`).classList.add('active');
    });
  });

  // Sidebar collapse/expand
  document.querySelectorAll('.nav-group-toggle').forEach(btn => {
    btn.addEventListener('click', () => {
      const group = btn.closest('.nav-group');
      const expanded = group.classList.toggle('open');
      btn.setAttribute('aria-expanded', expanded);
    });
  });

  // Sidebar filter
  (function() {
    const filterInput = document.querySelector('.nav-filter');
    if (!filterInput) return;
    filterInput.addEventListener('input', () => {
      const query = filterInput.value.toLowerCase().trim();
      document.querySelectorAll('.sidebar .nav-item').forEach(item => {
        const text = item.textContent.toLowerCase();
        item.style.display = text.includes(query) || !query ? '' : 'none';
      });
      document.querySelectorAll('.sidebar .nav-group').forEach(group => {
        const visibleChildren = group.querySelectorAll('.nav-item:not([style*="display: none"])');
        group.style.display = visibleChildren.length || !query ? '' : 'none';
        if (query) group.classList.add('open');
      });
      document.querySelectorAll('.sidebar .nav-separator').forEach(sep => {
        sep.style.display = query ? 'none' : '';
      });
    });
  })();

  // Popover edge-avoidance
  document.querySelectorAll('.popover-trigger').forEach(trigger => {
    const popover = trigger.querySelector('.popover-content');
    if (!popover) return;

    function reposition() {
      // Reset positioning classes
      popover.classList.remove('popover-flipped');
      popover.style.left = '';
      popover.style.transform = '';

      const triggerRect = trigger.getBoundingClientRect();
      const popoverRect = popover.getBoundingClientRect();

      // Flip below if overflowing top
      if (popoverRect.top < 0) {
        popover.classList.add('popover-flipped');
      }

      // Shift horizontally if overflowing edges
      const updated = popover.getBoundingClientRect();
      if (updated.left < 8) {
        const shift = 8 - updated.left;
        popover.style.left = `calc(50% + ${shift}px)`;
      } else if (updated.right > window.innerWidth - 8) {
        const shift = updated.right - (window.innerWidth - 8);
        popover.style.left = `calc(50% - ${shift}px)`;
      }
    }

    trigger.addEventListener('mouseenter', reposition);
    trigger.addEventListener('focusin', reposition);
  });
  </script>
  {% endblock %}

  {% if search_enabled %}
  <script>
  (function() {
    const input = document.querySelector('.search-input');
    const resultsContainer = document.querySelector('.search-results');
    if (!input || !resultsContainer) return;

    let miniSearch = null;
    let loaded = false;

    function getSnippet(body, query, maxLen) {
      if (!body) return '';
      var lower = body.toLowerCase();
      var terms = query.toLowerCase().split(/\s+/).filter(Boolean);
      var pos = -1;
      for (var t = 0; t < terms.length; t++) {
        pos = lower.indexOf(terms[t]);
        if (pos >= 0) break;
      }
      if (pos < 0) return body.slice(0, maxLen) + (body.length > maxLen ? '...' : '');
      var start = Math.max(0, pos - 40);
      var end = Math.min(body.length, pos + maxLen - 40);
      var snippet = (start > 0 ? '...' : '') + body.slice(start, end) + (end < body.length ? '...' : '');
      for (var t = 0; t < terms.length; t++) {
        var re = new RegExp('(' + terms[t].replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
        snippet = snippet.replace(re, '<mark>$1</mark>');
      }
      return snippet;
    }

    function escapeHtml(s) {
      return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    function loadSearch() {
      if (loaded) return;
      loaded = true;

      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/minisearch@7/dist/umd/index.min.js';
      script.onload = function() {
        fetch('{{ base_url | safe }}search-index.json')
          .then(r => r.json())
          .then(data => {
            miniSearch = new MiniSearch({
              fields: ['title', 'heading', 'body'],
              storeFields: ['title', 'heading', 'url', 'body'],
              searchOptions: {
                boost: { title: 3, heading: 2 },
                prefix: true,
                fuzzy: 0.2
              }
            });
            miniSearch.addAll(data);
            doSearch(input.value);
          });
      };
      document.head.appendChild(script);
    }

    let selectedIndex = -1;
    let lastQuery = '';

    function doSearch(query) {
      selectedIndex = -1;
      lastQuery = query;
      if (!miniSearch || !query.trim()) {
        resultsContainer.innerHTML = '';
        resultsContainer.style.display = 'none';
        return;
      }
      const results = miniSearch.search(query).slice(0, 8);
      if (results.length === 0) {
        resultsContainer.innerHTML = '<div class="search-no-results">No results found</div>';
        resultsContainer.style.display = 'block';
        return;
      }
      resultsContainer.innerHTML = results.map((r, i) => {
        var titleText = escapeHtml(r.title);
        if (r.heading) titleText += ' &rsaquo; ' + escapeHtml(r.heading);
        var snippet = getSnippet(r.body || '', query, 80);
        return '<a class="search-result-item" href="' + r.url + '" role="option" data-index="' + i + '">' +
          '<div class="search-result-title">' + titleText + '</div>' +
          (snippet ? '<div class="search-result-snippet">' + snippet + '</div>' : '') +
          '</a>';
      }).join('');
      resultsContainer.style.display = 'block';
    }

    function updateSelection() {
      const items = resultsContainer.querySelectorAll('.search-result-item');
      items.forEach((item, i) => {
        item.classList.toggle('selected', i === selectedIndex);
      });
    }

    input.addEventListener('focus', loadSearch);
    input.addEventListener('input', () => doSearch(input.value));

    input.addEventListener('keydown', (e) => {
      const items = resultsContainer.querySelectorAll('.search-result-item');
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
        updateSelection();
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        selectedIndex = Math.max(selectedIndex - 1, 0);
        updateSelection();
      } else if (e.key === 'Enter' && selectedIndex >= 0 && items[selectedIndex]) {
        e.preventDefault();
        items[selectedIndex].click();
      } else if (e.key === 'Escape') {
        resultsContainer.innerHTML = '';
        resultsContainer.style.display = 'none';
        input.blur();
      }
    });

    document.addEventListener('click', (e) => {
      if (!e.target.closest('.search-wrapper')) {
        resultsContainer.innerHTML = '';
        resultsContainer.style.display = 'none';
      }
    });
  })();
  </script>
  {% endif %}

  {% if mermaid_enabled %}
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@{{ mermaid_version }}/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true, theme: 'default' });
  </script>
  {% endif %}

  {% if live_reload %}
  <script>
  (function() {
    const ws = new WebSocket(`ws://${location.host}/__docanvil_ws`);
    ws.onmessage = () => location.reload();
    ws.onclose = () => setTimeout(() => location.reload(), 1000);
  })();
  </script>
  {% endif %}
</body>
</html>
