document.addEventListener('DOMContentLoaded', function () {
  var picker = document.getElementById('languagePicker');
  if (!picker) return;
  var btn = document.getElementById('langBtn');
  var list = document.getElementById('langList');
  var selectedSpan = picker.querySelector('.lang-selected');

  function openList() {
    btn.setAttribute('aria-expanded', 'true');
    list.setAttribute('aria-hidden', 'false');
    list.classList.add('open');
  }

  function closeList() {
    btn.setAttribute('aria-expanded', 'false');
    list.setAttribute('aria-hidden', 'true');
    list.classList.remove('open');
  }

  btn.addEventListener('click', function (e) {
    e.stopPropagation();
    var isOpen = btn.getAttribute('aria-expanded') === 'true';
    if (isOpen) closeList(); else openList();
  });

  list.addEventListener('click', function (e) {
    var item = e.target.closest('.language-item');
    if (!item) return;
    var lang = item.dataset.lang;
    selectedSpan.textContent = item.textContent;
    localStorage.setItem('preferredLanguage', lang);
    closeList();
    // Hook: here you could trigger i18n change or reload with ?lang=
  });

  document.addEventListener('click', function (e) {
    if (!picker.contains(e.target)) closeList();
  });

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') closeList();
  });

  // initialize from storage
  var saved = localStorage.getItem('preferredLanguage');
  if (saved) {
    var el = list.querySelector('[data-lang="' + saved + '"]');
    if (el) selectedSpan.textContent = el.textContent;
  }
});
