{% load static %}
{% load i18n %}
{% comment %}
  Login page SPA — overlay shell.

  Injected at the end of <body> when AA_CUSTOMIZER.login_spa_enabled is True.

  Page content is read from <section data-route="slug" data-label="Nav Label">
  elements inside #aac-spa-content, which the user provides via the
  "Login Page — Extra Body HTML" admin field.  The plugin automatically wraps
  the field value in <div id="aac-spa-body-src" style="display:none">, so you
  do NOT need display:none on your own wrapper div.  Example:

      <div id="aac-spa-content">
        <section data-route="home" data-label="Home">
          <!-- your hero HTML here -->
        </section>
        <section data-route="about" data-label="About">
          <!-- your about HTML here -->
        </section>
        <section data-route="apply" data-label="Apply">
          <!-- your apply HTML here -->
        </section>
      </div>

  JavaScript hooks (listen on document):
    aac-spa-route-change  — fires after each route is rendered
                             detail: { route: "slug" }
    aac-spa-signin        — fires when the overlay hides for the login card

  Global API:
    window.AAC_SPA.routes      — array of route slugs in order
    window.AAC_SPA.nav(slug)   — navigate to a named route (re-shows overlay)
{% endcomment %}

<div id="aac-spa">

  <nav id="aac-spa-nav">
    <div id="aac-spa-brand">
      <span class="aac-spa-diamond">⬡</span>
      <span id="aac-spa-brand-text">{% if AA_CUSTOMIZER.login_spa_nav_brand %}{{ AA_CUSTOMIZER.login_spa_nav_brand }}{% else %}{{ SITE_NAME }}{% endif %}</span>
    </div>
    <ul id="aac-spa-links">
      {# Nav links are built dynamically by JS from section[data-route] elements #}
    </ul>
    <a href="#signin" id="aac-spa-signin-link">{% translate "Sign In" %} →</a>
    <button id="aac-spa-menu-btn" aria-label="{% translate "Menu" %}"
            onclick="document.getElementById('aac-spa-links').classList.toggle('open')">
      <span></span><span></span><span></span>
    </button>
  </nav>

  <main id="aac-spa-view"></main>

</div>

<script>
!function () {
    /* Body HTML is wrapped in #aac-spa-body-src when SPA is active.
       Support both the wrapper id (current) and the bare #aac-spa-content id
       (backwards-compat if someone inlines it without the wrapper). */
    var src = document.getElementById('aac-spa-body-src') ||
              document.getElementById('aac-spa-content');
    if (!src) return;  // no content source — SPA won't run
    var content = src.querySelector('#aac-spa-content') || src;

    /* ── collect pages from section[data-route] ── */
    var PAGES = {};
    var LABELS = {};
    var ROUTES = [];
    var sections = content.querySelectorAll('[data-route]');
    for (var i = 0; i < sections.length; i++) {
        var s = sections[i];
        var r = s.getAttribute('data-route');
        PAGES[r]  = s.innerHTML;
        LABELS[r] = s.getAttribute('data-label') || r;
        ROUTES.push(r);
    }
    if (!ROUTES.length) return;  // nothing to show

    /* ── build nav links ── */
    var linksList = document.getElementById('aac-spa-links');
    for (var j = 0; j < ROUTES.length; j++) {
        var li = document.createElement('li');
        var a  = document.createElement('a');
        a.href = '#' + ROUTES[j];
        a.setAttribute('data-route', ROUTES[j]);
        a.textContent = LABELS[ROUTES[j]];
        li.appendChild(a);
        linksList.appendChild(li);
    }

    /* ── DOM refs ── */
    var overlay = document.getElementById('aac-spa');
    var view    = document.getElementById('aac-spa-view');

    /* ── expose public API for body-HTML scripts ── */
    window.AAC_SPA = {
        routes: ROUTES,
        /** Navigate to a named route (re-shows the SPA overlay). */
        nav: function (route) {
            window.location.hash = route || ROUTES[0];
        }
    };

    /* ── re-execute <script> tags injected via innerHTML ──
       Browsers silently ignore script elements set through innerHTML;
       we have to clone-and-replace each one so it actually runs. */
    function runScripts(container) {
        var scripts = container.querySelectorAll('script');
        for (var si = 0; si < scripts.length; si++) {
            var old = scripts[si];
            var neo = document.createElement('script');
            for (var ai = 0; ai < old.attributes.length; ai++) {
                neo.setAttribute(old.attributes[ai].name, old.attributes[ai].value);
            }
            neo.textContent = old.textContent;
            old.parentNode.replaceChild(neo, old);
        }
    }

    /* ── router ── */
    function currentRoute() {
        return (window.location.hash || '').replace(/^#/, '') || ROUTES[0];
    }

    function render() {
        var r = currentRoute();

        /* signin hash, or auth redirect (?next=) — hide overlay, show login card */
        if (r === 'signin' || window.location.search.indexOf('next=') !== -1) {
            overlay.style.display = 'none';
            /* close mobile menu before exiting */
            linksList.classList.remove('open');
            /* notify body-HTML scripts (e.g. to open a custom modal overlay) */
            document.dispatchEvent(new CustomEvent('aac-spa-signin'));
            return;
        }

        /* unknown route — fall back to first page */
        if (!PAGES[r]) r = ROUTES[0];

        overlay.style.display = 'flex';
        view.scrollTop = 0;          /* always start at top of the new page */
        view.innerHTML = PAGES[r];
        runScripts(view);            /* execute any <script> tags in the section */

        /* notify body-HTML scripts (e.g. to re-attach IntersectionObserver) */
        document.dispatchEvent(new CustomEvent('aac-spa-route-change', { detail: { route: r } }));

        /* close mobile menu */
        linksList.classList.remove('open');

        /* update active link */
        var links = linksList.querySelectorAll('[data-route]');
        for (var k = 0; k < links.length; k++) {
            if (links[k].getAttribute('data-route') === r) {
                links[k].classList.add('aac-spa-active');
            } else {
                links[k].classList.remove('aac-spa-active');
            }
        }
    }

    window.addEventListener('hashchange', render);
    render();
}();
</script>
