/*
 * gate.js — first-visit language gate behaviour for trentpower.fr/.
 *
 * The gate page is server-rendered visible and works with no JavaScript:
 * the two choices are ordinary <a href="/en/"> / <a href="/fr/"> links, and
 * a returning visitor is redirected before paint by the inline head script.
 *
 * This script is pure progressive enhancement:
 *   · remembers the choice in localStorage["tp-lang"] on click, so the next
 *     visit to / skips the gate;
 *   · traps focus within the dialog;
 *   · moves focus to the first choice on load.
 *
 * No string swapping, no runtime i18n — the gate's display language is fixed
 * at parse time by the inline head script (html[data-gate-lang]).
 */
(function () {
  "use strict";

  var overlay = document.getElementById("lang-gate");
  if (!overlay) return;

  var choices = overlay.querySelectorAll("a[data-lang]");

  // Remember the chosen edition, then let the link navigate normally.
  Array.prototype.forEach.call(choices, function (link) {
    link.addEventListener("click", function () {
      var lang = link.getAttribute("data-lang");
      if (lang === "en" || lang === "fr") {
        try { localStorage.setItem("tp-lang", lang); } catch (_) {}
      }
    });
  });

  // Focus trap — the gate must resolve via a choice, so Escape is not bound.
  var focusable = overlay.querySelectorAll("a[href], button, [tabindex]:not([tabindex='-1'])");
  if (!focusable.length) return;
  var first = focusable[0];
  var last = focusable[focusable.length - 1];

  overlay.addEventListener("keydown", function (event) {
    if (event.key !== "Tab") return;
    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  });

  // Move focus into the dialog once the document is interactive.
  window.requestAnimationFrame(function () {
    try { first.focus({ preventScroll: true }); } catch (_) { first.focus(); }
  });
})();
