(function () {
  'use strict';

  var DBG = false;
  function log() {
    if (DBG) {
      try {
        console.log.apply(console, arguments);
      } catch (e) { }
    }
  }

  log('[AWXCT] frontend.js start');

  // -------------------------------------------------------------------
  // Basic helpers
  // -------------------------------------------------------------------
  function esc(s) {
    s = (s == null) ? '' : String(s);
    return s
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  // Root-Container: bevorzugt vom Theme erzeugt, aber mit Fallback
  var root = document.getElementById('awxct-plg-ct-switcher-root');
  if (!root) {
    log('[AWXCT] #awxct-plg-ct-switcher-root missing – creating it (fallback).');
    root = document.createElement('div');
    root.id = 'awxct-plg-ct-switcher-root';
    // Fallback: ganz am Ende von <body>
    (document.body || document.documentElement).appendChild(root);
  }

  if (!window.AWXCT) {
    log('[AWXCT] window.AWXCT missing – not rendering');
    return;
  }

  var data = window.AWXCT;
  var placement = data.placement || 'float-left'; // 'float-left' | 'float-right' | 'menu-end'
  var cfg = data.cfg || {};

  // Debug logging follows WP_DEBUG (provided by PHP via cfg.debug)
  DBG = !!(cfg && cfg.debug);

  // --- PATCH: Nonce for awxct_set_lang links (provided by PHP via wp_localize_script)
  var setLangNonce = data.setLangNonce || cfg.setLangNonce || '';

  // Optional: globale Accent-Farbe aus Config
  if (cfg.ui && cfg.ui.accentColor) {
    document.documentElement.style.setProperty(
      '--awxct-accent',
      String(cfg.ui.accentColor)
    );
  }

  var langs = Array.isArray(data.languages) ? data.languages : [];
  var current = (data.current || '').toLowerCase();
  var def = (data.default || '').toLowerCase();

  // Liste der erlaubten Sprachcodes (klein, mit Bindestrich), z.B. ["en-us","de-de","it-it"]
  var allowedLangs = langs
    .map(function (l) {
      return (l && l.code ? String(l.code) : '').toLowerCase().replace('_', '-');
    })
    .filter(function (c) { return !!c; });

  var allowedLangSet = {};
  allowedLangs.forEach(function (c) {
    allowedLangSet[c] = true;
  });

  // -------------------------------------------------------------------
  // Target URL: build /{homePath}/{lang?}/{slug}/ (root + subdir installs supported)
  // All mapping / fallbacks are handled by PHP routing.
  // -------------------------------------------------------------------

  function normLang(code) {
    return String(code || '').trim().replace(/_/g, '-').toLowerCase();
  }

  function stripSlashes(s) {
    return String(s || '').replace(/^\/+|\/+$/g, '');
  }

  function ensureTrailingSlash(s) {
    return s.endsWith('/') ? s : (s + '/');
  }

  function buildHrefFor(code) {
    var target = normLang(code);

    try {
      // WordPress home path from PHP (e.g. '/' or '/wordpress/')
      var base = data.homePath ? String(data.homePath) : '/';
      base = '/' + stripSlashes(base) + '/';
      // If WP is installed in the root, stripSlashes('/') becomes '' -> base would become '//'.
      // Normalize to '/' to avoid double slashes like "//fr-fr/".
      if (base === '//') {
        base = '/';
      }

      // Current path relative to WP home
      var curPath = '/' + stripSlashes(location.pathname || '/') + '/';
      var rel = curPath;
      if (rel.startsWith(base)) {
        rel = '/' + stripSlashes(rel.slice(base.length)) + '/';
      }

      // Remove existing language prefix (if present)
      var parts = stripSlashes(rel).split('/').filter(Boolean);
      if (parts.length) {
        var first = normLang(parts[0]);
        if (allowedLangSet[first] || /^[a-z]{2}-[a-z]{2}$/i.test(first)) {
          parts.shift();
        }
      }

      var relNoLang = parts.length ? parts.join('/') + '/' : '';

      // Default language (normalized)
      var defCode = normLang(data.default || '');
      if (!defCode && langs.length) {
        defCode = normLang(langs[0].code || '');
      }

      var isDefault = defCode && target === defCode;
      var targetPath = isDefault || !target
        ? base + relNoLang
        : base + target + '/' + relNoLang;

      var u = new URL(location.origin + targetPath);

      // NOTE:
      // When switching to the default language, the URL has no language prefix.
      // We set the language cookie in the click handler (client-side) instead of
      // redirecting via query params. This prevents edge-cases where the cleanup
      // redirect could land on wp-admin for logged-out users.

      log('[AWXCT] buildHrefFor() code=' + target + ' -> ' + u.toString());
      return u.toString();

    } catch (e) {
      // Fallback: set cookie language and let routing handle it
      var baseUrl = location.href.split('#')[0];
      var sep = baseUrl.indexOf('?') === -1 ? '?' : '&';
      var url = baseUrl + sep + 'awxct_set_lang=' + encodeURIComponent(target);
      if (setLangNonce) { url += '&_wpnonce=' + encodeURIComponent(setLangNonce); }
      return url;
    }
  }

  // Normalize default language once
  var defCodeNorm = normLang(data.default || '');
  if (!defCodeNorm && langs.length) {
    defCodeNorm = normLang(langs[0].code || '');
  }

  // Cookie helper (keeps language persistent without server redirects)
  function setLangCookie(code) {
    try {
      var c = normLang(code);
      if (!c) return;
      var days = 30;
      var maxAge = days * 24 * 60 * 60;
      // Match WP install path (root or subdir) if available
      var p = data.homePath ? '/' + stripSlashes(String(data.homePath)) + '/' : '/';
      if (p === '//') p = '/';
      var secure = (location.protocol === 'https:') ? ';Secure' : '';
      document.cookie = 'awxct_lang=' + encodeURIComponent(c) + ';Max-Age=' + maxAge + ';Path=' + p + ';SameSite=Lax' + secure;
    } catch (e) {
      // ignore
    }
  }

  // Delete language cookie (for default language)
  function deleteLangCookie() {
    try {
      var secure = (location.protocol === 'https:') ? ';Secure' : '';

      // Paths to try (root + WP install path)
      var paths = ['/', (data.homePath ? '/' + stripSlashes(String(data.homePath)) + '/' : '/')];
      // De-duplicate and normalize
      var uniq = {};
      paths = paths.map(function (p) {
        p = String(p || '/');
        if (p === '//' || p === '') p = '/';
        return p;
      }).filter(function (p) {
        if (uniq[p]) return false;
        uniq[p] = true;
        return true;
      });

      // Domains to try (unset domain + host + .host)
      var host = String(location.hostname || '');
      var domains = [''];
      if (host) {
        domains.push(host);
        domains.push('.' + host);
      }

      domains.forEach(function (d) {
        paths.forEach(function (p) {
          var domAttr = d ? ';Domain=' + d : '';
          document.cookie = 'awxct_lang=;Max-Age=0;Expires=Thu, 01 Jan 1970 00:00:00 GMT;Path=' + p + domAttr + ';SameSite=Lax' + secure;
        });
      });
    } catch (e) {
      // ignore
    }
  }

  // -------------------------------------------------------------------
  // Keep language context when navigating within the site.
  // If the current URL is /{lang}/..., ensure internal links are also
  // prefixed with /{lang}/... (deterministic from the current request path).
  // This is NOT cookie-based guessing; it only mirrors the current URL.
  // -------------------------------------------------------------------

  function getActiveLangFromPath() {
    try {
      var base = data.homePath ? String(data.homePath) : '/';
      base = '/' + stripSlashes(base) + '/';
      if (base === '//') base = '/';

      var curPath = '/' + stripSlashes(location.pathname || '/') + '/';
      var rel = curPath;
      if (rel.startsWith(base)) {
        rel = '/' + stripSlashes(rel.slice(base.length)) + '/';
      }

      var parts = stripSlashes(rel).split('/').filter(Boolean);
      if (!parts.length) return '';

      var first = normLang(parts[0]);
      if (!first) return '';

      // accept allowed langs (preferred) or a generic xx-xx pattern
      if (!allowedLangSet[first] && !/^[a-z]{2}-[a-z]{2}$/i.test(first)) {
        return '';
      }

      // don't treat default as "active prefix"
      if (defCodeNorm && first === defCodeNorm) {
        return '';
      }

      return first;
    } catch (e) {
      return '';
    }
  }

  function prefixInternalLinksWithActiveLang() {
    var active = getActiveLangFromPath();
    if (!active) return;

    var base = data.homePath ? String(data.homePath) : '/';
    base = '/' + stripSlashes(base) + '/';
    if (base === '//') base = '/';

    var selector = 'a[href]';
    var links = document.querySelectorAll(selector);

    for (var i = 0; i < links.length; i++) {
      var a = links[i];
      var href = a.getAttribute('href');
      if (!href) continue;

      // Never touch WordPress admin bar / toolbar links.
      if (a.closest('#wpadminbar')) continue;

      // ignore anchors and non-http schemes
      if (href[0] === '#') continue;
      if (/^(mailto:|tel:|javascript:)/i.test(href)) continue;

      var url;
      try {
        url = new URL(href, location.origin);
      } catch (e) {
        continue;
      }

      // only same-origin
      if (url.origin !== location.origin) continue;

      var pathName = String(url.pathname || '');

      // Never prefix backend / login / core admin endpoints.
      if (
        /\/wp-admin(?:\/|$)/i.test(pathName) ||
        /\/wp-login\.php(?:\/|$)/i.test(pathName) ||
        /\/wp-signup\.php(?:\/|$)/i.test(pathName) ||
        /\/wp-activate\.php(?:\/|$)/i.test(pathName)
      ) {
        continue;
      }

      var p = '/' + stripSlashes(pathName || '/') + '/';
      var rel = p;
      if (rel.startsWith(base)) {
        rel = '/' + stripSlashes(rel.slice(base.length)) + '/';
      }

      var parts = stripSlashes(rel).split('/').filter(Boolean);
      if (parts.length) {
        var first = normLang(parts[0]);
        // already prefixed with any language
        if (allowedLangSet[first] || /^[a-z]{2}-[a-z]{2}$/i.test(first)) {
          continue;
        }
      }

      // prefix with active
      var newPath = base + active + '/' + (parts.length ? parts.join('/') + '/' : '');
      // keep original trailing slash intent
      if (url.pathname && url.pathname.slice(-1) !== '/') {
        newPath = newPath.replace(/\/+$/, '');
      }

      url.pathname = newPath;
      a.setAttribute('href', url.toString());
    }
  }

  // Run after DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', prefixInternalLinksWithActiveLang);
  } else {
    prefixInternalLinksWithActiveLang();
  }

  // -------------------------------------------------------------------
  // Label / Flag helpers
  // -------------------------------------------------------------------
  var labelStyle = data.labelStyle || 'locale';

  function countryToEmoji(cc) {
    cc = (cc || '').toUpperCase();
    if (!/^[A-Z]{2}$/.test(cc)) return '🏳️';
    var a = cc.charCodeAt(0) - 65 + 0x1F1E6;
    var b = cc.charCodeAt(1) - 65 + 0x1F1E6;
    try { return String.fromCodePoint(a, b); } catch (e) { return '🏳️'; }
  }

  function flagHTML(country) {
    var cc = (country || '').toUpperCase();
    if (!/^[A-Z]{2}$/.test(cc)) {
      return '<span class="awxct-plg-ct-flag-emoji" aria-hidden="true">🏳️</span>';
    }

    // 1) flag-icons (CDN / vendor)
    if (window.AWXCT && AWXCT.flagsLib === 'flag-icons') {
      return '<span class="fi awxct-plg-ct-flag fi-' + cc.toLowerCase() + '" aria-hidden="true"></span>';
    }

    // 2) Eigene SVG-Flags
    var src = (AWXCT.flagsUrl || '').replace(/\/+$/, '') + '/' + cc.toLowerCase() + '.svg';
    var escCC = cc.replace(/"/g, '&quot;');
    return '' +
      '<img class="awxct-plg-ct-flag" src="' + src + '" alt="' + escCC + '" width="18" height="14" loading="lazy"' +
      ' onerror="this.replaceWith(document.createTextNode(\'' + countryToEmoji(cc) + '\'))">';
  }

  function formatLangLabel(langObj) {
    langObj = langObj || {};
    var codeFull = String(langObj.code || '').toLowerCase();
    var parts = codeFull.split(/[-_]/);
    var langShort = (parts[0] || '').toUpperCase();
    var country = (parts[1] || parts[0] || '').toUpperCase();
    var native = esc(langObj.native_name || langObj.name || '');
    var english = esc(langObj.english_name || '');
    var codeUp = esc(codeFull.replace('_', '-').toUpperCase());

    switch (labelStyle) {
      case 'lang': return esc(langShort);
      case 'native': return native || esc(langShort);
      case 'english': return english || esc(langShort);
      case 'flag': return flagHTML(country);
      case 'flag+lang':
        return flagHTML(country) + ' <span class="awxct-plg-ct-label">' + esc(langShort) + '</span>';
      case 'flag+native':
        return flagHTML(country) + ' <span class="awxct-plg-ct-label">' + (native || esc(langShort)) + '</span>';
      case 'flag+english':
        return flagHTML(country) + ' <span class="awxct-plg-ct-label">' + (english || esc(langShort)) + '</span>';
      case 'locale':
      default:
        return codeUp;
    }
  }

  // -------------------------------------------------------------------
  // Switcher-HTML bauen
  // -------------------------------------------------------------------
  function buildSwitcher() {
    if (!langs.length) return null;

    var wrap = document.createElement('div');
    wrap.className = 'awxct-plg-ct-switcher';

    var btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'awxct-plg-ct-btn';
    btn.setAttribute('aria-haspopup', 'true');
    btn.setAttribute('aria-expanded', 'false');

    var cur = langs.find(function (l) {
      return (l && l.code || '').toLowerCase() === current;
    }) || langs[0];

    var btnLabelHTML = cur
      ? formatLangLabel(cur)
      : formatLangLabel({ code: current || 'lang' });

    btn.innerHTML = btnLabelHTML +
      ' <span class="awxct-plg-ct-caret" aria-hidden="true"></span>';

    var list = document.createElement('ul');
    list.className = 'awxct-plg-ct-menu';
    list.setAttribute('role', 'menu');
    list.setAttribute('tabindex', '-1');

    langs.forEach(function (l) {
      var code = (l && l.code ? String(l.code) : '').toLowerCase();
      var nameTxt = (l && (l.native_name || l.name || l.english_name)) ||
        (code ? code.toUpperCase() : 'LANG');
      var href = buildHrefFor(code);

      var li = document.createElement('li');
      li.setAttribute('role', 'none');

      var a = document.createElement('a');
      a.setAttribute('role', 'menuitem');
      a.className = 'awxct-plg-ct-item' + (code === current ? ' is-active' : '');
      a.href = href;
      a.innerHTML = formatLangLabel(l);
      a.setAttribute('aria-label', 'Switch to ' + esc(nameTxt));
      a.setAttribute('data-awxct-lang', code || '');
      a.setAttribute('data-awxct-default', String(code === def));

      li.appendChild(a);
      list.appendChild(li);
    });


    // -------------------------------------------------------------------
    // menu-end dropdown portal (brings dropdown in front if header clips it)
    // Only active when placement === 'menu-end'.
    // -------------------------------------------------------------------
    function getPortalState() {
      if (!list.__awxPortalState) {
        list.__awxPortalState = {
          originalParent: null,
          originalNext: null,
          prevInlineStyle: null,
          savedCss: null,
          bound: false
        };
      }
      return list.__awxPortalState;
    }

    function portalCaptureCss() {
      var st = getPortalState();
      if (st.savedCss || !window.getComputedStyle) return;

      try {
        var cs = window.getComputedStyle(list);
        st.savedCss = {
          backgroundColor: cs.backgroundColor,
          border: cs.border,
          borderRadius: cs.borderRadius,
          boxShadow: cs.boxShadow,
          padding: cs.padding,
          color: cs.color,
          minWidth: cs.minWidth
        };
      } catch (e) { }
    }

    function portalPlaceMenu() {
      if (placement !== 'menu-end') return;
      var st = getPortalState();

      if (!st.originalParent) {
        st.originalParent = list.parentNode;
        st.originalNext = list.nextSibling;
      }
      if (st.prevInlineStyle === null) {
        st.prevInlineStyle = list.getAttribute('style') || '';
      }

      // Capture computed styles before moving (theme styles may depend on menu ancestors)
      portalCaptureCss();

      // Move into body to escape overflow:hidden parents
      if (list.parentNode !== document.body) {
        document.body.appendChild(list);
      }

      var r = btn.getBoundingClientRect();
      list.style.position = 'fixed';
      list.style.left = (r.left) + 'px';
      list.style.top = (r.bottom + 6) + 'px';
      list.style.zIndex = '999999';
      list.style.margin = '0';
      list.style.listStyle = 'none';

      // Re-apply look that might have depended on ancestor selector
      if (st.savedCss) {
        list.style.backgroundColor = st.savedCss.backgroundColor;
        list.style.border = st.savedCss.border;
        list.style.borderRadius = st.savedCss.borderRadius;
        list.style.boxShadow = st.savedCss.boxShadow;
        list.style.padding = st.savedCss.padding;
        if (st.savedCss.color) list.style.color = st.savedCss.color;
        if (st.savedCss.minWidth) list.style.minWidth = st.savedCss.minWidth;
      }
    }

    function portalRestoreMenu() {
      if (placement !== 'menu-end') return;
      var st = getPortalState();
      if (!st.originalParent) return;

      try {
        if (st.originalNext && st.originalNext.parentNode === st.originalParent) {
          st.originalParent.insertBefore(list, st.originalNext);
        } else {
          st.originalParent.appendChild(list);
        }
      } catch (e) { }

      // Restore previous inline style exactly
      try {
        if (st.prevInlineStyle !== null) {
          if (st.prevInlineStyle === '') {
            list.removeAttribute('style');
          } else {
            list.setAttribute('style', st.prevInlineStyle);
          }
        }
      } catch (e) { }
    }

    function bindPortalRepositionOnce() {
      var st = getPortalState();
      if (st.bound) return;
      st.bound = true;

      // Keep position correct while open
      window.addEventListener('scroll', function () {
        if (btn.getAttribute('aria-expanded') === 'true') {
          portalPlaceMenu();
        }
      }, true);

      window.addEventListener('resize', function () {
        if (btn.getAttribute('aria-expanded') === 'true') {
          portalPlaceMenu();
        }
      });
    }

    function openMenu(force) {
      var isOpen = wrap.classList.contains('open');
      var willOpen = (typeof force === 'boolean') ? force : !isOpen;
      wrap.classList.toggle('open', willOpen);
      btn.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
      if (placement === 'menu-end') {
        bindPortalRepositionOnce();
        if (willOpen) {
          setTimeout(function () { portalPlaceMenu(); }, 0);
        } else {
          portalRestoreMenu();
        }
      }
      if (willOpen) list.focus();
    }

    btn.addEventListener('click', function (e) {
      e.preventDefault();
      openMenu();
    });

    document.addEventListener('click', function (e) {
      if (!wrap.contains(e.target) && !list.contains(e.target)) {
        openMenu(false);
      }
    });

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

    list.addEventListener('click', function (e) {
      var a = e.target.closest('a.awxct-plg-ct-item');
      if (!a) return;
      var code = (a.getAttribute('data-awxct-lang') || '').toLowerCase();
      if (!code) return;

      // Persist language selection on the client (prevents redirect edge-cases)
      // IMPORTANT: For default language we must DELETE the cookie (do not store default).
      if (defCodeNorm && normLang(code) === defCodeNorm) {
        deleteLangCookie();
      } else {
        setLangCookie(code);
      }

      if (code === current) {
        e.preventDefault();
        wrap.classList.remove('open');
        btn.setAttribute('aria-expanded', 'false');
        return;
      }
      var rebuilt = buildHrefFor(code);
      if (a.href !== rebuilt) {
        a.href = rebuilt;
      }

    }, true);

    wrap.appendChild(btn);
    wrap.appendChild(list);
    return wrap;
  }

  log('[AWXCT] Language Switcher JS loaded.');

  // -------------------------------------------------------------------
  // Menü finden (Block-Themes + klassische Themes)
  // -------------------------------------------------------------------
  function findMenuUl() {
    // 1) Block-Theme Header-Navigation (Twenty Twenty-Five etc.)
    try {
      var header = document.querySelector('.wp-site-blocks > header');
      if (header) {
        var blockUl = header.querySelector(
          'nav.wp-block-navigation ul.wp-block-navigation__container'
        );
        if (blockUl) {
          return blockUl;
        }
      }
    } catch (e) { }

    // 2) Weitere Block-Navigations (nicht im Footer)
    var blockCandidates = document.querySelectorAll(
      'nav.wp-block-navigation ul.wp-block-navigation__container'
    );
    if (blockCandidates && blockCandidates.length) {
      for (var i = 0; i < blockCandidates.length; i++) {
        var ul = blockCandidates[i];
        if (!ul.closest('footer')) {
          return ul;
        }
      }
      // sonst erste
      return blockCandidates[0];
    }

    // 3) Klassische Themes – typische Selektoren
    var selectors = [
      '.navbar-brand > ul.nav-menu',
      '#menu-primary',
      '#menu-primary.nav-menu',
      '#header .nav-menu',
      '#header nav .navbar-nav',
      'ul.navbar-nav.nav-menu'
    ];
    for (var j = 0; j < selectors.length; j++) {
      var ul2 = document.querySelector(selectors[j]);
      if (!ul2) continue;
      if (ul2.closest('#navbarResponsive')) continue;
      return ul2;
    }

    return null;
  }

  // Wartet (bei Block-Themes) bis das Menü-UL überhaupt existiert
  function waitForMenuUl(callback) {
    var ul = findMenuUl();
    if (ul) {
      callback(ul);
      return;
    }

    if (!('MutationObserver' in window)) {
      log('[AWXCT] MutationObserver not available');
      return;
    }

    var mo = new MutationObserver(function () {
      var ul2 = findMenuUl();
      if (ul2) {
        mo.disconnect();
        callback(ul2);
      }
    });

    mo.observe(document.body || document.documentElement, { childList: true, subtree: true });
  }

  // Doppelte Switcher entfernen (sicherheitshalber)
  function purgeDuplicates(keepSwitcher) {
    var all = Array.prototype.slice.call(
      document.querySelectorAll('.awxct-plg-ct-switcher')
    );

    all.forEach(function (el) {
      if (keepSwitcher && el === keepSwitcher) return;
      var li = el.closest('.menu-item-awxct-lang');
      (li || el).remove();
    });
  }

  // -------------------------------------------------------------------
  // Tastatur-Navigation / Accessibility
  // -------------------------------------------------------------------
  function enhanceKeyboardNav(wrapper) {
    if (!wrapper) return;

    var btn = wrapper.querySelector('.awxct-plg-ct-btn');
    var list = wrapper.querySelector('.awxct-plg-ct-menu');
    if (!btn || !list) return;

    function items() {
      return Array.prototype.slice.call(
        list.querySelectorAll('.awxct-plg-ct-item')
      );
    }

    // Öffnen via ArrowDown / Enter / Space
    btn.addEventListener('keydown', function (e) {
      if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        wrapper.classList.add('open');
        btn.setAttribute('aria-expanded', 'true');
        var it = items()[0];
        if (it) it.focus();
      }
    });

    // Navigation in der Liste
    list.addEventListener('keydown', function (e) {
      var arr = items();
      var i = arr.indexOf(document.activeElement);

      if (e.key === 'Escape') {
        e.preventDefault();
        wrapper.classList.remove('open');
        btn.setAttribute('aria-expanded', 'false');
        btn.focus();
      } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        var n = arr[Math.min(i + 1, arr.length - 1)] || arr[0];
        if (n) n.focus();
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        var p = arr[Math.max(i - 1, 0)] || arr[arr.length - 1];
        if (p) p.focus();
      } else if (e.key === 'Home') {
        e.preventDefault();
        if (arr[0]) arr[0].focus();
      } else if (e.key === 'End') {
        e.preventDefault();
        if (arr[arr.length - 1]) arr[arr.length - 1].focus();
      }
    });

    // Optional: open on hover
    if (cfg.switcher && cfg.switcher.openOnHover) {
      wrapper.addEventListener('mouseenter', function () {
        wrapper.classList.add('open');
        btn.setAttribute('aria-expanded', 'true');
      });
      wrapper.addEventListener('mouseleave', function () {
        wrapper.classList.remove('open');
        btn.setAttribute('aria-expanded', 'false');
      });
    }

    // Optional: Auto-Close nach X ms
    var autoclose = parseInt(cfg.switcher && cfg.switcher.autocloseMs, 10);
    if (!isNaN(autoclose) && autoclose > 0) {
      list.addEventListener('mouseenter', function () {
        clearTimeout(list.__awxT);
      });
      list.addEventListener('mouseleave', function () {
        clearTimeout(list.__awxT);
        list.__awxT = setTimeout(function () {
          wrapper.classList.remove('open');
          btn.setAttribute('aria-expanded', 'false');
        }, autoclose);
      });
    }
  }

  // -------------------------------------------------------------------
  // MAIN: Switcher bauen & platzieren (robust, mit Fallback)
  // -------------------------------------------------------------------
  var desktopSwitcher = buildSwitcher();
  if (!desktopSwitcher) {
    log('[AWXCT] no switcher built – abort placement.');
    return;
  }

  // 1) Immer zuerst ins Root packen (Fallback, falls kein Menü gefunden wird)
  root.textContent = '';
  root.appendChild(desktopSwitcher);

  if (placement === 'float-right') {
    root.classList.add('awxct-plg-ct-pos-right');
  } else {
    root.classList.remove('awxct-plg-ct-pos-right');
  }

  enhanceKeyboardNav(desktopSwitcher);
  log('[AWXCT] initial placement in root (' + placement + ') done');

  // 2) Wenn menu-end gewünscht: versuchen, ins Menü umzuziehen
  if (placement === 'menu-end') {
    // Try to move the whole root container into the menu placeholder.
    // This is more robust than moving only the inner switcher, because the
    // floating positioning is defined on the root container.
    var moved = false;

    function neutralizeFloatingStyles() {
      // Remove floating position classes
      root.classList.remove('awxct-plg-ct-pos-left', 'awxct-plg-ct-pos-right', 'awxct-plg-ct-pos-top', 'awxct-plg-ct-pos-bottom');
      // Neutralize any fixed/absolute positioning rules when inside menu
      root.style.position = 'static';
      root.style.left = 'auto';
      root.style.right = 'auto';
      root.style.top = 'auto';
      root.style.bottom = 'auto';
      root.style.transform = 'none';
      root.style.margin = '0';
      root.style.display = '';
    }

    function tryMoveIntoPlaceholder(menuUl) {
      if (moved) return true;

      var placeholder = document.getElementById('awxct-plg-ct-switcher-placeholder');
      if (placeholder) {
        // Ensure placeholder is in a UL; if menuUl is given, it must match
        if (!menuUl || placeholder.parentNode === menuUl) {
          try {
            placeholder.textContent = '';
            placeholder.appendChild(root);
            neutralizeFloatingStyles();
            moved = true;
            log('[AWXCT] placement menu-end done (moved root into placeholder)');
            return true;
          } catch (e) {
            // ignore
          }
        }
      }
      return false;
    }

    // First try: if placeholder already exists, move immediately (no UL lookup needed)
    tryMoveIntoPlaceholder(null);

    // Second try (and fallback): detect a menu UL, then move (or append a new LI if no placeholder)
    waitForMenuUl(function (menuUl) {
      if (tryMoveIntoPlaceholder(menuUl)) {
        return;
      }

      if (!menuUl) {
        log('[AWXCT] menu-end: no UL found – stay in root.');
        return;
      }

      log('[AWXCT] menu-end: UL detected:', menuUl);

      // Fallback if theme did not include our placeholder for any reason
      var li = document.createElement('li');
      li.className = 'menu-item menu-item-type-custom menu-item-awxct-lang nav-item';
      li.appendChild(root);
      menuUl.appendChild(li);

      neutralizeFloatingStyles();
      moved = true;

      purgeDuplicates(desktopSwitcher);

      log('[AWXCT] placement menu-end done (moved root into menu)');
    });
  }

})();
