(function () {
  "use strict";

  if (!window.LiveLangSettings) {
    return;
  }

  // Prevent initialization if loaded inside Page Builder Editors / Preview Iframes
  if (
    document.body.classList.contains("elementor-editor-active") || 
    document.body.classList.contains("elementor-editor-preview") || 
    window.location.search.indexOf("elementor-preview=") !== -1 ||
    window.location.search.indexOf("action=elementor") !== -1 ||
    document.body.classList.contains("fl-builder-edit") ||
    window.location.search.indexOf("ct_builder=") !== -1
  ) {
    return;
  }

  class LiveLangHighProductivityEditor {
    constructor(settings) {
      this.settings = settings;
      this.enabled = !!settings.enabled;
      this.currentElement = null;
      this.saveBar = null;
      this.currentAlignment = '';
      this.fastMode = true; // Enabled by default for high productivity
      this.editableList = [];
      this.currentIndex = -1;

      this.handleClick = this.handleClick.bind(this);
      this.onEditableKeydown = this.onEditableKeydown.bind(this);
      this.onMouseOver = this.onMouseOver.bind(this);
      this.onMouseOut = this.onMouseOut.bind(this);
      this.updateBarPosition = this.updateBarPosition.bind(this);
      this.showToast = this.showToast.bind(this);
      this.handleGlobalKeydown = this.handleGlobalKeydown.bind(this);

      this.init();

      window.addEventListener('scroll', this.updateBarPosition, { passive: true });
      window.addEventListener('resize', this.updateBarPosition, { passive: true });
      document.addEventListener('keydown', this.handleGlobalKeydown, true);
    }

    init() {
      if (this.enabled) {
        this.enableEditing();
        document.documentElement.classList.add("livelang-edit-mode");
      }
      this.initToolbarToggle();
      this.initControlDock();
    }

    initToolbarToggle() {
      const toggleNode = document.querySelector("#wp-admin-bar-livelang-toggle-node");
      if (!toggleNode) return;

      const link = toggleNode.querySelector("a");
      if (!link) return;

      link.addEventListener("click", (e) => {
        e.preventDefault();
        this.toggleEditorState();
      });
    }

    toggleEditorState() {
      this.enabled = !this.enabled;

      const toggleWrapper = document.querySelector(".livelang-toggle-ui");
      const statusLabel = document.querySelector(".livelang-status-label");

      if (this.enabled) {
        if (toggleWrapper) {
          toggleWrapper.classList.remove("is-off");
          toggleWrapper.classList.add("is-on");
        }
        if (statusLabel) statusLabel.innerText = this.settings.i18n.active || "Active";
        this.enableEditing();
        document.documentElement.classList.add("livelang-edit-mode");
      } else {
        if (toggleWrapper) {
          toggleWrapper.classList.remove("is-on");
          toggleWrapper.classList.add("is-off");
        }
        if (statusLabel) statusLabel.innerText = this.settings.i18n.inactive || "Inactive";
        this.disableEditing();
        document.documentElement.classList.remove("livelang-edit-mode");
      }

      // Save preference in cookie
      const state = this.enabled ? "on" : "off";
      document.cookie = `livelang_frontend_editor=${state}; path=/; max-age=${365 * 24 * 60 * 60}`;

      this.updateControlDockState();
    }

    enableEditing() {
      document.removeEventListener("click", this.handleClick, true);
      document.removeEventListener("mouseover", this.onMouseOver, true);
      document.removeEventListener("mouseout", this.onMouseOut, true);

      document.addEventListener("click", this.handleClick, true);
      document.addEventListener("mouseover", this.onMouseOver, true);
      document.addEventListener("mouseout", this.onMouseOut, true);
    }

    disableEditing() {
      document.removeEventListener("click", this.handleClick, true);
      document.removeEventListener("mouseover", this.onMouseOver, true);
      document.removeEventListener("mouseout", this.onMouseOut, true);
      this.cleanPreviousElement(null);

      document.querySelectorAll(".livelang-hovering").forEach((el) => el.classList.remove("livelang-hovering"));
    }

    /* Modern Control Dock */
    initControlDock() {
      if (document.getElementById("livelang-control-dock")) return;

      const currentLang = this.settings.currentLanguage || 'en';
      const langLabel = (this.settings.languages && this.settings.languages[currentLang]) ? this.settings.languages[currentLang] : currentLang.toUpperCase();
      const flagUrl = this.getFlagUrl(currentLang);

      const dock = document.createElement("div");
      dock.id = "livelang-control-dock";
      dock.className = "livelang-control-dock";
      dock.innerHTML = `
        <div class="livelang-dock-content">
          <div class="livelang-dock-drag-handle" title="Drag to move toolbar">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="9" cy="6" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="18" r="1"/></svg>
          </div>
          <div class="livelang-dock-status">
            <span class="livelang-dock-pulse"></span>
            <img src="${flagUrl}" class="livelang-dock-flag" alt="${currentLang}">
            <span class="livelang-dock-lang-code">${langLabel}</span>
          </div>
          <div class="livelang-dock-divider"></div>
          <div class="livelang-dock-counter" title="Translation Coverage">
            <span id="livelang-dock-count-badge" class="livelang-dock-count-badge">0 / 0</span>
          </div>
          <div class="livelang-dock-divider"></div>
          <button type="button" class="livelang-dock-btn livelang-dock-shortcut-btn" title="${this.settings.i18n.shortcuts || 'Keyboard Shortcuts'}">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2" ry="2"/><line x1="6" y1="8" x2="6.01" y2="8"/><line x1="10" y1="8" x2="10.01" y2="8"/><line x1="14" y1="8" x2="14.01" y2="8"/><line x1="18" y1="8" x2="18.01" y2="8"/><line x1="6" y1="12" x2="6.01" y2="12"/><line x1="18" y1="12" x2="18.01" y2="12"/><line x1="7" y1="16" x2="17" y2="16"/></svg>
          </button>
          <button type="button" id="livelang-dock-toggle-btn" class="livelang-dock-btn livelang-dock-toggle-btn ${this.enabled ? 'is-active' : ''}">
            <span>${this.enabled ? (this.settings.i18n.active || 'Active') : (this.settings.i18n.inactive || 'Inactive')}</span>
          </button>
          <button type="button" class="livelang-dock-close" title="Close Translator">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div id="livelang-dock-shortcuts-popover" class="livelang-dock-shortcuts-popover">
          <div class="livelang-shortcuts-header">
            <strong>${this.settings.i18n.shortcuts || 'Keyboard Shortcuts'}</strong>
          </div>
          <ul class="livelang-shortcuts-list">
            <li><kbd>⌘ / Ctrl + Enter</kbd> <span>${this.settings.i18n.saveNext || 'Save & Next'}</span></li>
            <li><kbd>Enter</kbd> <span>Save</span></li>
            <li><kbd>Esc</kbd> <span>Cancel</span></li>
            <li><kbd>Tab</kbd> <span>Next String</span></li>
            <li><kbd>Shift + Tab</kbd> <span>Previous String</span></li>
          </ul>
        </div>
      `;

      document.body.appendChild(dock);

      // Event listeners for dock
      const toggleBtn = dock.querySelector("#livelang-dock-toggle-btn");
      toggleBtn.addEventListener("click", () => this.toggleEditorState());

      const closeBtn = dock.querySelector(".livelang-dock-close");
      closeBtn.addEventListener("click", () => {
        if (this.enabled) this.toggleEditorState();
      });

      const shortcutBtn = dock.querySelector(".livelang-dock-shortcut-btn");
      const shortcutsPopover = dock.querySelector("#livelang-dock-shortcuts-popover");
      shortcutBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        shortcutsPopover.classList.toggle("is-open");
      });

      document.addEventListener("click", (e) => {
        if (!dock.contains(e.target)) {
          shortcutsPopover.classList.remove("is-open");
        }
      });

      this.makeDockDraggable(dock);
      this.updateControlDockState();
      this.scanAndCountEditableElements();
    }

    getFlagUrl(langCode) {
      const countryMap = {
        'en': 'us', 'fr': 'fr', 'de': 'de', 'es': 'es', 'it': 'it', 'pt': 'pt',
        'ru': 'ru', 'zh': 'cn', 'ja': 'jp', 'ko': 'kr', 'ar': 'sa', 'bn': 'bd',
        'hi': 'in', 'nl': 'nl', 'pl': 'pl', 'tr': 'tr', 'uk': 'ua', 'sv': 'se'
      };
      const country = countryMap[langCode] || 'un';
      return `${this.settings.homeUrl}/wp-content/plugins/livelang/assets/images/flags/${country}.webp`;
    }

    makeDockDraggable(host) {
      const handle = host.querySelector(".livelang-dock-drag-handle");
      if (!handle) return;

      let isDragging = false;
      let startX, startY, initialLeft, initialTop;

      handle.addEventListener("pointerdown", (e) => {
        isDragging = true;
        startX = e.clientX;
        startY = e.clientY;

        const rect = host.getBoundingClientRect();
        initialLeft = rect.left;
        initialTop = rect.top;

        host.style.setProperty('right', 'auto', 'important');
        host.style.setProperty('bottom', 'auto', 'important');
        host.style.setProperty('left', initialLeft + 'px', 'important');
        host.style.setProperty('top', initialTop + 'px', 'important');
        host.style.setProperty('transition', 'none', 'important');
        handle.style.cursor = 'grabbing';
        e.preventDefault();
      });

      document.addEventListener("pointermove", (e) => {
        if (!isDragging) return;
        e.preventDefault();

        const dx = e.clientX - startX;
        const dy = e.clientY - startY;

        let newLeft = initialLeft + dx;
        let newTop = initialTop + dy;

        const rect = host.getBoundingClientRect();
        if (newLeft < 10) newLeft = 10;
        if (newTop < 10) newTop = 10;
        if (newLeft + rect.width > window.innerWidth - 10) newLeft = window.innerWidth - rect.width - 10;
        if (newTop + rect.height > window.innerHeight - 10) newTop = window.innerHeight - rect.height - 10;

        host.style.setProperty('left', newLeft + 'px', 'important');
        host.style.setProperty('top', newTop + 'px', 'important');
      });

      document.addEventListener("pointerup", () => {
        if (isDragging) {
          isDragging = false;
          handle.style.cursor = 'grab';
          host.style.removeProperty('transition');
        }
      });
    }

    updateControlDockState() {
      const dock = document.getElementById("livelang-control-dock");
      if (!dock) return;

      if (this.enabled) {
        dock.classList.add("is-visible");
      } else {
        dock.classList.remove("is-visible");
      }

      const toggleBtn = dock.querySelector("#livelang-dock-toggle-btn");
      if (toggleBtn) {
        if (this.enabled) {
          toggleBtn.classList.add("is-active");
          toggleBtn.querySelector("span").textContent = this.settings.i18n.active || 'Active';
        } else {
          toggleBtn.classList.remove("is-active");
          toggleBtn.querySelector("span").textContent = this.settings.i18n.inactive || 'Inactive';
        }
      }
    }

    scanAndCountEditableElements() {
      const badge = document.getElementById("livelang-dock-count-badge");
      if (!badge) return;

      const items = this.getEditableElementsList();
      const total = items.length;
      let translatedCount = 0;

      if (Array.isArray(this.settings.dict) && this.settings.dict.length > 0) {
        items.forEach(el => {
          let text = (el.innerText || el.value || el.placeholder || el.src || "").replace(/\s+/g, " ").trim();
          if (text) {
            const found = this.settings.dict.find(d => d.translated === text || d.original === text);
            if (found && found.translated !== found.original) translatedCount++;
          }
        });
      }

      badge.textContent = `${translatedCount} / ${total}`;
    }

    getEditableElementsList() {
      const builderSelectors = ', .wp-block-paragraph, .wp-block-heading, .wp-block-button__link, .wp-block-navigation-item__content, .wp-block-site-title a, .wp-block-post-title, .wp-block-quote, .wp-block-pullquote, .wp-block-search__label, .wp-block-cover, .elementor-widget-container, .elementor-button, .elementor-heading-title, .et_pb_module, .fl-module-content, .bricks-element, .woocommerce-loop-product__title, .price, .single_add_to_cart_button';
      const candidates = Array.from(document.body.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, button, td, th, li, label, select, input[type="submit"], input[type="button"], input[placeholder], img' + builderSelectors));
      return candidates.filter(el => {
        if (el.closest("#wpadminbar, #livelang-control-dock, #livelang-editor-tooltip-container, #livelang-floating-switcher, script, style, noscript, pre, code")) {
          return false;
        }
        if (el.tagName === "IMG" || el.tagName === "SELECT") return true;
        if (el.tagName === "INPUT" && (el.placeholder || el.type === "submit" || el.type === "button")) return true;
        const text = el.innerText && el.innerText.trim();
        return text && this.isEditableContent(el);
      });
    }

    isEditableContent(el) {
      const allowedTags = ["STRONG", "B", "I", "EM", "A", "SPAN", "BR", "U", "OPTION"];
      const children = el.children;
      if (children.length === 0) return true;

      for (let i = 0; i < children.length; i++) {
        if (!allowedTags.includes(children[i].tagName)) return false;
        if (!this.isEditableContent(children[i])) return false;
      }
      return true;
    }

    onMouseOver(e) {
      if (!this.enabled) return;
      if (e.target.closest("#wpadminbar, #livelang-control-dock, #livelang-editor-tooltip-container, #livelang-floating-switcher, .media-modal")) return;
      if (e.target === this.currentElement) return;

      let node = e.target.closest ? e.target.closest("select") || e.target : e.target;
      if (node.nodeType === Node.TEXT_NODE) node = node.parentElement;
      if (!node || node === document.body || node === document.documentElement) return;

      const hasText = node.innerText && node.innerText.trim() !== "";
      const isInputBtn = (node.tagName === "INPUT" || node.tagName === "BUTTON") && (node.type === "submit" || node.type === "button" || node.type === "reset" || (node.placeholder && node.placeholder.trim()));
      const isImg = node.tagName === "IMG";
      const isSelect = node.tagName === "SELECT";

      if ((hasText && this.isEditableContent(node)) || isInputBtn || isImg || isSelect) {
        document.querySelectorAll(".livelang-hovering").forEach((el) => el.classList.remove("livelang-hovering"));
        node.classList.add("livelang-hovering");
      }
    }

    onMouseOut(e) {
      if (!this.enabled) return;
      let node = e.target.closest ? e.target.closest("select") || e.target : e.target;
      if (node.nodeType === Node.TEXT_NODE) node = node.parentElement;
      if (node) node.classList.remove("livelang-hovering");
    }

    handleClick(e) {
      if (!this.enabled) return;
      if (e.target.closest("#wpadminbar, #livelang-control-dock, #livelang-editor-tooltip-container, #livelang-floating-switcher, .media-modal")) return;

      const selectEl = e.target.closest("select");
      if (selectEl) {
        e.preventDefault();
        e.stopPropagation();
        this.editSelect(selectEl);
        return;
      }

      const link = e.target.closest("a");
      if (link) e.preventDefault();

      const submitBtn = e.target.closest('button[type="submit"], input[type="submit"]');
      if (submitBtn) e.preventDefault();

      let node = e.target;
      if (node.nodeType === Node.TEXT_NODE) node = node.parentElement;

      const isInputButton = (node.tagName === "INPUT" || node.tagName === "BUTTON") && (node.type === "submit" || node.type === "button" || node.type === "reset");
      const hasText = node.innerText && node.innerText.trim() !== "";

      if (isInputButton || (hasText && this.isEditableContent(node))) {
        e.preventDefault();
        e.stopPropagation();
        this.makeEditable(node);
      } else if (node.tagName === "INPUT" && node.placeholder) {
        e.preventDefault();
        e.stopPropagation();
        this.makeEditablePlaceholder(node);
      } else if (node.tagName === "IMG") {
        e.preventDefault();
        e.stopPropagation();
        this.editImage(node);
      } else {
        this.cleanPreviousElement(null);
      }
    }

    makeEditable(el) {
      if (!el || el.getAttribute("contenteditable") === "true") return;
      this.cleanPreviousElement(el);

      this.editableList = this.getEditableElementsList();
      this.currentIndex = this.editableList.indexOf(el);

      if (el.tagName === "INPUT") {
        const temp = document.createElement("input");
        temp.type = "text";
        temp.className = "livelang-temp-input";
        temp.value = el.value || el.getAttribute("value") || "";
        let displayedText = (temp.value || "").replace(/\s+/g, " ").trim();
        temp.dataset.livelangOriginal = this.getTrueOriginal(displayedText);

        try {
          const rect = el.getBoundingClientRect();
          temp.style.width = Math.max(rect.width + 20, 120) + "px";
          temp.style.height = Math.max(rect.height + 10, 36) + "px";
        } catch (err) {}

        el.parentNode.insertBefore(temp, el.nextSibling);
        el.style.display = "none";
        temp._livelang_original_input = el;
        temp.addEventListener("keydown", this.onEditableKeydown);
        temp.focus();
        temp.select();
        this.currentElement = temp;
      } else {
        if (!el.dataset.livelangOriginal) {
          let displayedText = (el.innerHTML || "").replace(/\s+/g, " ").trim();
          el.dataset.livelangOriginal = this.getTrueOriginal(displayedText);
        }
        el.setAttribute("contenteditable", "true");
        el.style.outline = "2px solid #3b82f6";
        el.style.borderRadius = "4px";
        el.addEventListener("keydown", this.onEditableKeydown);
        el.focus();
        this.currentElement = el;
      }

      // Detect existing alignment state
      const blockParent = el.closest('p, h1, h2, h3, h4, h5, h6, div, td, th, li, section, article') || el;
      this.currentAlignment = '';
      if (el.classList.contains('ll-align-center') || blockParent.classList.contains('ll-align-center')) {
        this.currentAlignment = 'center';
      } else if (el.classList.contains('ll-align-right') || blockParent.classList.contains('ll-align-right')) {
        this.currentAlignment = 'right';
      } else if (el.classList.contains('ll-align-left') || blockParent.classList.contains('ll-align-left')) {
        this.currentAlignment = 'left';
      }

      this.showSaveBar();
      this.scrollToElementIfNeeded(this.currentElement);
    }

    makeEditablePlaceholder(el) {
      if (!el || !el.placeholder) return;
      this.cleanPreviousElement(el);

      this.editableList = this.getEditableElementsList();
      this.currentIndex = this.editableList.indexOf(el);

      const temp = document.createElement("input");
      temp.type = "text";
      temp.className = "livelang-temp-placeholder-input";
      temp.value = el.placeholder || "";
      let displayedText = (el.placeholder || "").replace(/\s+/g, " ").trim();
      temp.dataset.livelangOriginal = this.getTrueOriginal(displayedText);

      el.parentNode.insertBefore(temp, el.nextSibling);
      el.style.display = "none";
      temp._livelang_original_input = el;
      temp._livelang_is_placeholder = true;
      temp.addEventListener("keydown", this.onEditableKeydown);
      temp.focus();
      temp.select();
      this.currentElement = temp;

      this.showSaveBar();
      this.scrollToElementIfNeeded(this.currentElement);
    }

    scrollToElementIfNeeded(el) {
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const inView = rect.top >= 80 && rect.bottom <= window.innerHeight - 100;
      if (!inView) {
        el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    }

    showToast(message, type) {
      type = type || "error";
      let host = document.getElementById("livelang-toast-host");
      if (!host) {
        host = document.createElement("div");
        host.id = "livelang-toast-host";
        document.body.appendChild(host);
      }
      const toast = document.createElement("div");
      toast.className = "livelang-toast livelang-toast-" + type;
      toast.innerHTML = `
        <span class="livelang-toast-icon">${type === 'success' ? '✓' : '⚠️'}</span>
        <span>${message}</span>
      `;
      host.appendChild(toast);
      requestAnimationFrame(() => toast.classList.add("is-visible"));
      setTimeout(() => {
        toast.classList.remove("is-visible");
        setTimeout(() => toast.remove(), 250);
      }, 3000);
    }

    handleGlobalKeydown(e) {
      if (!this.enabled || !this.currentElement) return;

      if (e.key === "Escape") {
        e.preventDefault();
        this.cleanPreviousElement(null);
      } else if (e.key === "Tab") {
        e.preventDefault();
        if (e.shiftKey) {
          this.navigateEditable(-1);
        } else {
          this.navigateEditable(1);
        }
      }
    }

    onEditableKeydown(e) {
      if (e.key === "Enter") {
        if (e.metaKey || e.ctrlKey || !e.shiftKey) {
          e.preventDefault();
          this.saveCurrent(true); // Save & Next
        }
      }
    }

    navigateEditable(dir) {
      if (!this.editableList || this.editableList.length === 0) {
        this.editableList = this.getEditableElementsList();
      }
      if (this.editableList.length === 0) return;

      let nextIndex = this.currentIndex + dir;
      if (nextIndex >= this.editableList.length) nextIndex = 0;
      if (nextIndex < 0) nextIndex = this.editableList.length - 1;

      const nextEl = this.editableList[nextIndex];
      if (nextEl) {
        this.cleanPreviousElement(null);
        if (nextEl.tagName === "IMG") {
          this.editImage(nextEl);
        } else if (nextEl.tagName === "INPUT" && nextEl.placeholder) {
          this.makeEditablePlaceholder(nextEl);
        } else {
          this.makeEditable(nextEl);
        }
      }
    }

    showSaveBar() {
      if (this.saveBar) this.saveBar.remove();

      const el = this.currentElement;
      const originalText = el.dataset.livelangOriginal || (el.innerHTML || el.value || "").trim();

      const bar = document.createElement("div");
      bar.id = "livelang-editor-tooltip-container";
      bar.className = "livelang-editor-tooltip";

      const originalEscaped = this.escapeHtml(originalText);
      const currentContent = el._livelang_original_input ? (el._livelang_is_placeholder ? el._livelang_original_input.placeholder : el._livelang_original_input.value) : (el.innerHTML || "").trim();
      const hasNumbers = /\d+/.test(originalText);

      const numHelperHtml = hasNumbers ? `
        <div class="livelang-num-helper-row">
          <span class="livelang-num-badge">🔢 Dynamic Number</span>
          <button type="button" class="livelang-btn-insert-num" title="Convert number to dynamic {NUM} variable">
            + Use {NUM} Variable
          </button>
        </div>
      ` : '';

      bar.innerHTML = `
        <div class="livelang-popover-card">
          <!-- 1. HEADER: All Controllers -->
          <div class="livelang-popover-header">
            <div class="livelang-segmented-control">
              <button type="button" class="livelang-seg-btn active" data-global="0">${this.settings.i18n.pageSpecific || 'Page'}</button>
              <button type="button" class="livelang-seg-btn" data-global="1">${this.settings.i18n.global || 'Global'}</button>
            </div>

            <div class="livelang-align-segmented">
              <button type="button" class="livelang-align-btn ${this.currentAlignment === 'left' ? 'active' : ''}" data-align="left" title="Align Left">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="21" y1="6" x2="3" y2="6"/><line x1="15" y1="12" x2="3" y2="12"/><line x1="17" y1="18" x2="3" y2="18"/></svg>
              </button>
              <button type="button" class="livelang-align-btn ${this.currentAlignment === 'center' ? 'active' : ''}" data-align="center" title="Align Center">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="6"/><line x1="21" y1="12" x2="3" y2="12"/><line x1="18" y1="18" x2="6" y2="18"/></svg>
              </button>
              <button type="button" class="livelang-align-btn ${this.currentAlignment === 'right' ? 'active' : ''}" data-align="right" title="Align Right">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="12" x2="9" y2="12"/><line x1="21" y1="18" x2="7" y2="18"/></svg>
              </button>
            </div>
          </div>

          <!-- 2. BODY: Original Text Reference & Direct Translation Input -->
          <div class="livelang-popover-body">
            <div class="livelang-orig-ref-row">
              <span class="livelang-popover-badge">ORIGINAL</span>
              <span class="livelang-popover-orig-text" title="${originalEscaped}">${originalEscaped}</span>
              <button type="button" class="livelang-btn-code-toggle" title="Toggle Code / HTML Mode">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
              </button>
            </div>

            ${numHelperHtml}

            <div class="livelang-translation-input-wrap">
              <input type="text" class="livelang-translation-input" value="${this.escapeHtml(currentContent)}" placeholder="Type translation here...">
              <textarea class="livelang-code-textarea" rows="3" style="display: none;" placeholder="Enter translation or raw HTML markup...">${this.escapeHtml(currentContent)}</textarea>
            </div>
          </div>

          <!-- 3. FOOTER: Navigation & Action Buttons (Cancel, Save, Save & Next) -->
          <div class="livelang-popover-footer">
            <div class="livelang-footer-nav">
              <button type="button" class="livelang-btn-nav livelang-btn-prev" title="${this.settings.i18n.prevString || 'Previous'}">‹</button>
              <button type="button" class="livelang-btn-nav livelang-btn-next" title="${this.settings.i18n.nextString || 'Next'}">›</button>
            </div>

            <div class="livelang-footer-actions">
              <button type="button" class="livelang-cancel-btn" title="${this.settings.i18n.cancel}">${this.settings.i18n.cancel}</button>
              <button type="button" class="livelang-save-only-btn" title="Save translation">Save</button>
              <button type="button" class="livelang-save-btn livelang-save-next-btn">${this.settings.i18n.saveNext || 'Save & Next ↵'}</button>
            </div>
          </div>
        </div>
        <div class="livelang-tooltip-arrow"></div>
      `;

      document.body.appendChild(bar);
      this.saveBar = bar;

      // Input Elements & Two-Way Sync
      const transInput = bar.querySelector(".livelang-translation-input");
      const codeTextarea = bar.querySelector(".livelang-code-textarea");
      const codeToggleBtn = bar.querySelector(".livelang-btn-code-toggle");
      const insertNumBtn = bar.querySelector(".livelang-btn-insert-num");

      if (insertNumBtn) {
        insertNumBtn.onclick = (e) => {
          e.preventDefault();
          if (transInput && transInput.value) {
            transInput.value = transInput.value.replace(/\d+/g, '{NUM}');
          }
          if (codeTextarea && codeTextarea.value) {
            codeTextarea.value = codeTextarea.value.replace(/\d+/g, '{NUM}');
          }
          const val = transInput ? transInput.value : (codeTextarea ? codeTextarea.value : "");
          if (el._livelang_original_input) {
            if (el._livelang_is_placeholder) el._livelang_original_input.placeholder = val;
            else el._livelang_original_input.value = val;
          } else {
            el.innerHTML = val;
          }
          this.showToast("Converted to dynamic {NUM} variable!", "success");
        };
      }

      if (transInput && codeTextarea && codeToggleBtn) {
        // Code Toggle Mode
        codeToggleBtn.onclick = (e) => {
          e.preventDefault();
          const isCodeView = codeTextarea.style.display === "none";
          codeTextarea.style.display = isCodeView ? "block" : "none";
          transInput.style.display = isCodeView ? "none" : "block";
          codeToggleBtn.classList.toggle("active", isCodeView);
          if (isCodeView) {
            codeTextarea.focus();
          } else {
            transInput.focus();
          }
          this.updateBarPosition();
        };

        // Standard Input Sync -> Page Element & Textarea
        transInput.addEventListener("input", () => {
          const val = transInput.value;
          codeTextarea.value = val;
          if (el._livelang_original_input) {
            if (el._livelang_is_placeholder) el._livelang_original_input.placeholder = val;
            else el._livelang_original_input.value = val;
          } else {
            el.innerHTML = val;
          }
        });

        // HTML Textarea Sync -> Page Element & Input
        codeTextarea.addEventListener("input", () => {
          const val = codeTextarea.value;
          transInput.value = val;
          if (el._livelang_original_input) {
            if (el._livelang_is_placeholder) el._livelang_original_input.placeholder = val;
            else el._livelang_original_input.value = val;
          } else {
            el.innerHTML = val;
          }
        });

        // Page Element Sync -> Popover Inputs
        el.addEventListener("input", () => {
          const val = el._livelang_original_input ? (el._livelang_is_placeholder ? el._livelang_original_input.placeholder : el._livelang_original_input.value) : el.innerHTML;
          transInput.value = val;
          codeTextarea.value = val;
        });

        // Pressing Enter inside input field triggers Save & Next
        transInput.addEventListener("keydown", (e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            this.saveCurrent(true);
          }
        });
      }

      // Action Buttons
      const saveOnlyBtn = bar.querySelector(".livelang-save-only-btn");
      if (saveOnlyBtn) {
        saveOnlyBtn.onclick = () => this.saveCurrent(false);
      }

      const saveNextBtn = bar.querySelector(".livelang-save-next-btn");
      if (saveNextBtn) {
        saveNextBtn.onclick = () => this.saveCurrent(true);
      }

      const cancelBtn = bar.querySelector(".livelang-cancel-btn");
      if (cancelBtn) {
        cancelBtn.onclick = () => this.cleanPreviousElement(null);
      }

      const prevBtn = bar.querySelector(".livelang-btn-prev");
      if (prevBtn) {
        prevBtn.onclick = () => this.navigateEditable(-1);
      }

      const nextBtn = bar.querySelector(".livelang-btn-next");
      if (nextBtn) {
        nextBtn.onclick = () => this.navigateEditable(1);
      }

      // Global vs Page Segmented Control
      const segBtns = bar.querySelectorAll(".livelang-seg-btn");
      segBtns.forEach(btn => {
        btn.onclick = (e) => {
          e.preventDefault();
          segBtns.forEach(b => b.classList.remove("active"));
          btn.classList.add("active");
        };
      });

      // Alignment Selector
      const alignBtns = bar.querySelectorAll(".livelang-align-btn");
      alignBtns.forEach(btn => {
        btn.onclick = (e) => {
          e.preventDefault();
          const align = btn.dataset.align;
          this.currentAlignment = this.currentAlignment === align ? '' : align;

          alignBtns.forEach(b => b.classList.remove("active"));
          if (this.currentAlignment) btn.classList.add("active");

          if (this.currentElement) {
            const target = this.currentElement._livelang_original_input ? this.currentElement._livelang_original_input.parentElement : this.currentElement;
            const blockParent = target.closest('p, h1, h2, h3, h4, h5, h6, div, td, th, li, section, article') || target;

            target.classList.remove('ll-align-left', 'll-align-center', 'll-align-right');
            blockParent.classList.remove('ll-align-left', 'll-align-center', 'll-align-right');

            if (this.currentAlignment) {
              target.classList.add(`ll-align-${this.currentAlignment}`);
              blockParent.classList.add(`ll-align-${this.currentAlignment}`);
            }
          }
        };
      });

      this.updateBarPosition();
    }

    escapeHtml(str) {
      if (!str) return '';
      return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
    }

    updateBarPosition() {
      if (!this.saveBar || !this.currentElement) return;

      const rect = this.currentElement.getBoundingClientRect();
      const barRect = this.saveBar.getBoundingClientRect();

      let top = rect.top + window.scrollY - barRect.height - 14;
      let left = rect.left + window.scrollX + (rect.width / 2) - (barRect.width / 2);

      if (top < window.scrollY + 10) {
        top = rect.bottom + window.scrollY + 14;
        this.saveBar.classList.add('is-bottom');
      } else {
        this.saveBar.classList.remove('is-bottom');
      }

      this.saveBar.style.top = top + "px";
      this.saveBar.style.left = Math.max(10, Math.min(left, window.innerWidth - barRect.width - 20)) + "px";
    }

    hideSaveBar() {
      if (this.saveBar) {
        this.saveBar.remove();
        this.saveBar = null;
      }
    }

    saveCurrent(advanceToNext = false) {
      if (!this.currentElement) return;

      const el = this.currentElement;
      let originalText = el.dataset.livelangOriginal;

      const transInput = this.saveBar ? this.saveBar.querySelector(".livelang-translation-input") : null;
      const codeTextarea = this.saveBar ? this.saveBar.querySelector(".livelang-code-textarea") : null;

      let translatedText = "";
      if (transInput && transInput.style.display !== "none" && transInput.value) {
        translatedText = transInput.value;
      } else if (codeTextarea && codeTextarea.value) {
        translatedText = codeTextarea.value;
      } else {
        translatedText = el.tagName === "INPUT" ? el.value : el.innerHTML;
      }
      translatedText = translatedText.replace(/\s+/g, " ").trim();

      const activeSeg = this.saveBar.querySelector(".livelang-seg-btn.active");
      const isGlobal = (activeSeg && activeSeg.dataset.global === "1") ? 1 : 0;
      const alignment = this.currentAlignment;

      if (!originalText || (translatedText === originalText && !isGlobal && !alignment)) {
        if (translatedText === originalText && !isGlobal && !alignment) {
          if (advanceToNext) {
            this.navigateEditable(1);
          } else {
            this.cleanPreviousElement(null);
          }
          return;
        }
      }

      const saveBtn = this.saveBar.querySelector(".livelang-save-btn");
      saveBtn.disabled = true;
      saveBtn.innerText = this.settings.i18n.saving || 'Saving...';

      fetch(this.settings.restUrl + "/save", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": this.settings.nonce,
        },
        body: JSON.stringify({
          original: originalText,
          translated: translatedText,
          slug: this.settings.slug,
          language: this.settings.currentLanguage,
          is_global: isGlobal,
          alignment: alignment,
        }),
      })
      .then((res) => res.json())
      .then((data) => {
        if (data.success) {
          this.showToast(this.settings.i18n.saved || "Saved successfully!", "success");

          if (Array.isArray(this.settings.dict)) {
            const idx = this.settings.dict.findIndex(item => item.original === originalText);
            if (idx > -1) {
              this.settings.dict[idx].translated = translatedText;
              this.settings.dict[idx].alignment = alignment;
            } else {
              this.settings.dict.push({
                original: originalText,
                translated: translatedText,
                alignment: alignment,
              });
            }
          }

          if (window.LiveLangFrontendInstance && window.LiveLangFrontendInstance.refreshTranslationPairs) {
            window.LiveLangFrontendInstance.refreshTranslationPairs();
          }

          let updatedEl = el;
          let renderText = translatedText;

          // Replace {NUM} placeholder with actual digits from original text for DOM rendering
          if (renderText.indexOf("{NUM}") !== -1) {
            const digits = originalText.match(/\d+/g);
            if (digits && digits.length > 0) {
              let dIndex = 0;
              renderText = renderText.replace(/\{NUM\}/g, () => digits[dIndex++] || "");
            }
          }

          if (el.tagName === "IMG") {
            el.src = renderText;
            el.removeAttribute("srcset");
            el.removeAttribute("data-srcset");
            el.removeAttribute("data-lazy-srcset");
            if (el.hasAttribute("data-src")) el.setAttribute("data-src", renderText);
            if (el.hasAttribute("data-lazy-src")) el.setAttribute("data-lazy-src", renderText);
            if (el.hasAttribute("data-orig-src")) el.setAttribute("data-orig-src", renderText);
          } else if (el._livelang_original_input) {
            const orig = el._livelang_original_input;
            if (el._livelang_is_placeholder) orig.placeholder = renderText;
            else orig.value = renderText;
            updatedEl = orig;
          } else {
            el.innerHTML = renderText;
          }

          // Visual Flash Green Success Pulse
          updatedEl.classList.add("livelang-saved-flash");
          setTimeout(() => updatedEl.classList.remove("livelang-saved-flash"), 1200);

          this.scanAndCountEditableElements();

          if (advanceToNext) {
            this.navigateEditable(1);
          } else {
            this.cleanPreviousElement(null);
          }

          if (window.LiveLangFrontendInstance && window.LiveLangFrontendInstance.markAsAlreadyTranslated) {
            window.LiveLangFrontendInstance.markAsAlreadyTranslated(updatedEl);
          }
        } else {
          this.showToast(this.settings.i18n.saveError || "Error saving translation", "error");
          saveBtn.disabled = false;
          saveBtn.innerText = this.settings.i18n.saveNext || "Save & Next";
        }
      })
      .catch((err) => {
        console.error(err);
        this.showToast("Network error while saving", "error");
        saveBtn.disabled = false;
        saveBtn.innerText = this.settings.i18n.saveNext || "Save & Next";
      });
    }

    getTrueOriginal(currentText) {
      if (!currentText) return '';
      const text = String(currentText).trim();

      if (Array.isArray(this.settings.dict) && this.settings.dict.length > 0) {
        // 1. Exact match for item.translated
        const found = this.settings.dict.find(item => item.translated === text);
        if (found && found.original) {
          if (found.alignment) {
            this.currentAlignment = found.alignment;
          }
          return found.original;
        }

        // 2. Exact match for item.original
        const origFound = this.settings.dict.find(item => item.original === text);
        if (origFound && origFound.original) {
          if (origFound.alignment) {
            this.currentAlignment = origFound.alignment;
          }
          return origFound.original;
        }

        // 3. Fallback: prefix match if text starts with translated string (handles past duplicated text)
        for (let i = 0; i < this.settings.dict.length; i++) {
          const item = this.settings.dict[i];
          if (item && item.original && item.translated) {
            if (text.startsWith(item.translated)) {
              if (item.alignment) this.currentAlignment = item.alignment;
              return item.original;
            }
          }
        }
      }
      return text;
    }

    cleanPreviousElement(nextNode) {
      if (!this.currentElement || this.currentElement === nextNode) return;

      const el = this.currentElement;
      el.removeEventListener("keydown", this.onEditableKeydown);

      if (el._livelang_original_input) {
        el._livelang_original_input.style.display = "";
        el.remove();
      } else {
        el.removeAttribute("contenteditable");
        el.style.outline = "";
        el.style.borderRadius = "";
      }

      document.body.classList.remove('livelang-wp-media-open');
      this.currentElement = null;
      this.currentAlignment = '';
      this.hideSaveBar();
    }

    /* Upgraded Super Clean & Workable Media / Image Translation */
    editImage(el) {
      this.cleanPreviousElement(null);
      this.currentElement = el;

      let originalUrl = el.dataset.livelangOriginalSrc;
      if (!originalUrl) {
        originalUrl = this.getTrueOriginal(el.src) || el.src;
        el.dataset.livelangOriginalSrc = originalUrl;
      }
      let currentTranslatedUrl = el.src;

      let originalAlt = el.dataset.livelangOriginalAlt;
      if (!originalAlt) {
        originalAlt = el.getAttribute("alt") || "";
        el.dataset.livelangOriginalAlt = originalAlt;
      }
      let currentAlt = el.getAttribute("alt") || originalAlt;

      const currentLang = this.settings.currentLanguage || 'en';
      const langLabel = (this.settings.languages && this.settings.languages[currentLang]) ? this.settings.languages[currentLang] : currentLang.toUpperCase();

      if (this.saveBar) this.saveBar.remove();

      const bar = document.createElement("div");
      bar.id = "livelang-editor-tooltip-container";
      bar.className = "livelang-editor-tooltip livelang-media-tooltip";

      bar.innerHTML = `
        <div class="livelang-popover-card livelang-media-popover">
          <div class="livelang-popover-header">
            <span class="livelang-popover-badge">MEDIA TRANSLATOR</span>
            <span class="livelang-media-lang-badge">${langLabel}</span>
          </div>

          <div class="livelang-popover-body">
            <div class="livelang-media-previews">
              <div class="livelang-media-preview-box">
                <span class="livelang-media-preview-label">Original</span>
                <div class="livelang-img-frame">
                  <img src="${originalUrl}" alt="Original">
                </div>
              </div>
              <div class="livelang-media-preview-arrow">➔</div>
              <div class="livelang-media-preview-box">
                <span class="livelang-media-preview-label">Translation</span>
                <div class="livelang-img-frame">
                  <img id="livelang-media-translated-preview" src="${currentTranslatedUrl}" alt="Translated">
                </div>
              </div>
            </div>

            <div class="livelang-media-source-row">
              <button type="button" class="livelang-btn-media-library">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                Choose from Media Library
              </button>
            </div>

            <div class="livelang-media-input-group">
              <label>Image URL:</label>
              <input type="url" id="livelang-media-url-input" class="livelang-media-url-input" value="${currentTranslatedUrl}" placeholder="https://...">
            </div>

            <div class="livelang-media-input-group">
              <label>Image Alt Text (SEO):</label>
              <input type="text" id="livelang-media-alt-input" class="livelang-media-alt-input" value="${this.escapeHtml(currentAlt)}" placeholder="SEO alt description...">
            </div>

            <div class="livelang-media-footer">
              <div class="livelang-segmented-control">
                <button type="button" class="livelang-seg-btn active" data-global="0">Page Specific</button>
                <button type="button" class="livelang-seg-btn" data-global="1">Global</button>
              </div>

              <div class="livelang-popover-actions">
                <button type="button" class="livelang-cancel-btn">Cancel</button>
                <button type="button" class="livelang-save-btn livelang-save-media-btn">Save Media</button>
              </div>
            </div>
          </div>
        </div>
        <div class="livelang-tooltip-arrow"></div>
      `;

      document.body.appendChild(bar);
      this.saveBar = bar;

      const mediaUrlInput = bar.querySelector("#livelang-media-url-input");
      const mediaAltInput = bar.querySelector("#livelang-media-alt-input");
      const previewImg = bar.querySelector("#livelang-media-translated-preview");
      const mediaLibBtn = bar.querySelector(".livelang-btn-media-library");
      const saveMediaBtn = bar.querySelector(".livelang-save-media-btn");
      const cancelBtn = bar.querySelector(".livelang-cancel-btn");
      const segBtns = bar.querySelectorAll(".livelang-seg-btn");

      // Live preview URL input updates
      mediaUrlInput.addEventListener("input", () => {
        const val = mediaUrlInput.value.trim();
        if (val) previewImg.src = val;
      });

      // Media library modal
      mediaLibBtn.addEventListener("click", (e) => {
        e.preventDefault();
        if (!window.wp || !wp.media) {
          this.showToast("WordPress media library not available.", "error");
          return;
        }

        const mediaUploader = wp.media({
          title: 'Select Translated Image',
          button: { text: 'Use Translated Image' },
          multiple: false
        });

        mediaUploader.on('open', () => {
          document.body.classList.add('livelang-wp-media-open');
        });

        mediaUploader.on('select', () => {
          const attachment = mediaUploader.state().get('selection').first().toJSON();
          const translatedUrl = attachment.url;
          mediaUrlInput.value = translatedUrl;
          previewImg.src = translatedUrl;
        });

        mediaUploader.on('close', () => {
          document.body.classList.remove('livelang-wp-media-open');
        });

        mediaUploader.open();
      });

      // Segmented control
      segBtns.forEach(btn => {
        btn.onclick = (e) => {
          e.preventDefault();
          segBtns.forEach(b => b.classList.remove("active"));
          btn.classList.add("active");
        };
      });

      cancelBtn.onclick = () => this.cleanPreviousElement(null);

      // Save Media Translation
      saveMediaBtn.onclick = () => {
        const newUrl = mediaUrlInput.value.trim();
        const newAlt = mediaAltInput.value.trim();
        const activeSeg = bar.querySelector(".livelang-seg-btn.active");
        const isGlobal = (activeSeg && activeSeg.dataset.global === "1") ? 1 : 0;

        if (!newUrl) {
          this.showToast("Please enter an image URL", "error");
          return;
        }

        saveMediaBtn.disabled = true;
        saveMediaBtn.innerText = "Saving...";

        const requests = [];

        const origAttr = el.getAttribute("src") || originalUrl;
        const unscaledOrig = originalUrl.replace(/-[0-9]+x[0-9]+(\.[a-z0-9]+)$/i, "$1");
        const urlsToSave = new Set([originalUrl, origAttr, unscaledOrig]);

        urlsToSave.forEach(u => {
          if (u && (u !== newUrl || isGlobal)) {
            requests.push(
              fetch(this.settings.restUrl + "/save", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  "X-WP-Nonce": this.settings.nonce,
                },
                body: JSON.stringify({
                  original: u,
                  translated: newUrl,
                  slug: this.settings.slug,
                  language: this.settings.currentLanguage,
                  is_global: isGlobal,
                }),
              })
            );
          }
        });

        // Save Alt Text translation if altered
        if (originalAlt && newAlt && originalAlt !== newAlt) {
          requests.push(
            fetch(this.settings.restUrl + "/save", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": this.settings.nonce,
              },
              body: JSON.stringify({
                original: originalAlt,
                translated: newAlt,
                slug: this.settings.slug,
                language: this.settings.currentLanguage,
                is_global: isGlobal,
              }),
            })
          );
        }

        Promise.all(requests)
          .then(() => {
            // Apply DOM changes immediately
            el.src = newUrl;

            // STRIP RESPONSIVE SRCSET & SIZES so browser doesn't override with original thumbnail
            ['srcset', 'data-srcset', 'data-lazy-srcset', 'sizes'].forEach(attr => {
              if (el.hasAttribute(attr)) {
                el.removeAttribute(attr);
              }
            });
            if (el.hasAttribute('data-src')) el.setAttribute('data-src', newUrl);
            if (el.hasAttribute('data-lazy-src')) el.setAttribute('data-lazy-src', newUrl);
            if (el.hasAttribute('data-orig-src')) el.setAttribute('data-orig-src', newUrl);
            if (newAlt) {
              el.setAttribute('alt', newAlt);
            }

            if (Array.isArray(this.settings.dict)) {
              this.settings.dict.push({ original: originalUrl, translated: newUrl });
              if (originalAlt && newAlt) {
                this.settings.dict.push({ original: originalAlt, translated: newAlt });
              }
            }

            if (window.LiveLangFrontendInstance && window.LiveLangFrontendInstance.refreshTranslationPairs) {
              window.LiveLangFrontendInstance.refreshTranslationPairs();
            }

            this.showToast("Media translation saved!", "success");
            el.classList.add("livelang-saved-flash");
            setTimeout(() => el.classList.remove("livelang-saved-flash"), 1200);

            this.cleanPreviousElement(null);
            this.scanAndCountEditableElements();
          })
          .catch((err) => {
            console.error(err);
            this.showToast("Error saving media translation", "error");
            saveMediaBtn.disabled = false;
            saveMediaBtn.innerText = "Save Media";
          });
      };

      this.updateBarPosition();
      this.scrollToElementIfNeeded(el);
    }

    /* Upgraded Dropdown / Select Options Multi-Translator */
    editSelect(el) {
      this.cleanPreviousElement(null);
      this.currentElement = el;

      const options = Array.from(el.querySelectorAll("option"));
      if (options.length === 0) {
        this.showToast("No options found in this dropdown", "warning");
        return;
      }

      const currentLang = this.settings.currentLanguage || 'en';
      const langLabel = (this.settings.languages && this.settings.languages[currentLang]) ? this.settings.languages[currentLang] : currentLang.toUpperCase();

      if (this.saveBar) this.saveBar.remove();

      const bar = document.createElement("div");
      bar.id = "livelang-editor-tooltip-container";
      bar.className = "livelang-editor-tooltip livelang-select-tooltip";

      // Build options rows
      let optionsHtml = '';
      options.forEach((opt, idx) => {
        const rawText = opt.textContent ? opt.textContent.trim() : "";
        if (!rawText) return;

        const origText = opt.dataset.livelangOriginal || rawText;
        if (!opt.dataset.livelangOriginal) {
          opt.dataset.livelangOriginal = origText;
        }
        const escOrig = this.escapeHtml(origText);
        const escTrans = this.escapeHtml(rawText);

        optionsHtml += `
          <div class="livelang-select-option-row" data-index="${idx}">
            <div class="livelang-select-orig-label" title="${escOrig}">${escOrig}</div>
            <div class="livelang-select-arrow">➔</div>
            <input type="text" class="livelang-select-trans-input" value="${escTrans}" placeholder="${escOrig}">
          </div>
        `;
      });

      bar.innerHTML = `
        <div class="livelang-popover-card livelang-select-popover">
          <div class="livelang-popover-header">
            <span class="livelang-popover-badge">DROPDOWN TRANSLATOR</span>
            <span class="livelang-media-lang-badge">${langLabel}</span>
          </div>

          <div class="livelang-popover-body">
            <div class="livelang-select-options-list">
              ${optionsHtml}
            </div>

            <div class="livelang-media-footer" style="margin-top:12px;">
              <div class="livelang-segmented-control">
                <button type="button" class="livelang-seg-btn active" data-global="0">Page Specific</button>
                <button type="button" class="livelang-seg-btn" data-global="1">Global</button>
              </div>

              <div class="livelang-popover-actions">
                <button type="button" class="livelang-cancel-btn">Cancel</button>
                <button type="button" class="livelang-save-btn livelang-save-select-btn">Save Options</button>
              </div>
            </div>
          </div>
        </div>
        <div class="livelang-tooltip-arrow"></div>
      `;

      document.body.appendChild(bar);
      this.saveBar = bar;

      const cancelBtn = bar.querySelector(".livelang-cancel-btn");
      const saveSelectBtn = bar.querySelector(".livelang-save-select-btn");
      const segBtns = bar.querySelectorAll(".livelang-seg-btn");

      segBtns.forEach(btn => {
        btn.onclick = (e) => {
          e.preventDefault();
          segBtns.forEach(b => b.classList.remove("active"));
          btn.classList.add("active");
        };
      });

      cancelBtn.onclick = () => this.cleanPreviousElement(null);

      saveSelectBtn.onclick = () => {
        const activeSeg = bar.querySelector(".livelang-seg-btn.active");
        const isGlobal = (activeSeg && activeSeg.dataset.global === "1") ? 1 : 0;
        const rows = bar.querySelectorAll(".livelang-select-option-row");
        const requests = [];

        saveSelectBtn.disabled = true;
        saveSelectBtn.innerText = "Saving...";

        rows.forEach((row) => {
          const idx = parseInt(row.dataset.index, 10);
          const opt = options[idx];
          if (!opt) return;

          const origText = opt.dataset.livelangOriginal || opt.textContent.trim();
          const transInput = row.querySelector(".livelang-select-trans-input");
          const transVal = transInput ? transInput.value.trim() : '';

          if (origText && transVal && (origText !== transVal || isGlobal)) {
            requests.push(
              fetch(this.settings.restUrl + "/save", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  "X-WP-Nonce": this.settings.nonce,
                },
                body: JSON.stringify({
                  original: origText,
                  translated: transVal,
                  slug: this.settings.slug,
                  language: this.settings.currentLanguage,
                  is_global: isGlobal,
                }),
              })
            );
          }
        });

        Promise.all(requests)
          .then(() => {
            rows.forEach((row) => {
              const idx = parseInt(row.dataset.index, 10);
              const opt = options[idx];
              if (!opt) return;

              const transInput = row.querySelector(".livelang-select-trans-input");
              const transVal = transInput ? transInput.value.trim() : '';
              if (transVal) {
                opt.textContent = transVal;
                if (Array.isArray(this.settings.dict)) {
                  this.settings.dict.push({ original: opt.dataset.livelangOriginal, translated: transVal });
                }
              }
            });

            if (window.LiveLangFrontendInstance && window.LiveLangFrontendInstance.refreshTranslationPairs) {
              window.LiveLangFrontendInstance.refreshTranslationPairs();
            }

            this.showToast("Dropdown options saved successfully!", "success");
            el.classList.add("livelang-saved-flash");
            setTimeout(() => el.classList.remove("livelang-saved-flash"), 1200);

            this.cleanPreviousElement(null);
            this.scanAndCountEditableElements();
          })
          .catch((err) => {
            console.error("Save dropdown options error:", err);
            this.showToast("Failed to save dropdown options", "error");
            saveSelectBtn.disabled = false;
            saveSelectBtn.innerText = "Save Options";
          });
      };

      this.updateBarPosition();
      this.scrollToElementIfNeeded(el);
    }
  }

  window.LiveLangEditorInstance = new LiveLangHighProductivityEditor(window.LiveLangSettings);
})();
