/**
 * Vareon Calculator Suite Lite - Admin Settings interactions.
 */

(function ($, __) {
  'use strict';

  var adminSettingsCfg = window.VAREONCALC_ADMIN_SETTINGS || {};
  var settingsTipNoticeCfg = adminSettingsCfg.settingsTipNotice || null;
  var tabUrls = adminSettingsCfg.tabUrls || {};
  var shortcodeBuilderCfg = adminSettingsCfg.shortcodeBuilder || {};

  function sanitizeCurrencySymbol(raw) {
    var s = String(raw || '');
    s = s.replace(/[0-9]/g, '').replace(/\s+/g, '');
    if (s.length > 4) {
      s = s.slice(0, 4);
    }
    return s || '$';
  }

  var FORMAT_PRESETS = {
    us: {
      currency_code: 'USD',
      currency_position: 'before',
      thousand_separator: 'comma',
      decimal_separator: 'dot',
      measurement_system: 'imperial'
    },
    eu: {
      currency_code: 'EUR',
      currency_position: 'after',
      thousand_separator: 'dot',
      decimal_separator: 'comma',
      measurement_system: 'metric'
    },
    uk: {
      currency_code: 'GBP',
      currency_position: 'before',
      thousand_separator: 'comma',
      decimal_separator: 'dot',
      measurement_system: 'mixed'
    }
  };

  var THEME_PRESETS = {
    light: {
      button_bg: '#3b82f6',
      button_hover: '#2563eb',
      button_text: '#ffffff',
      card_bg: '#ffffff',
      card_border: '#e5e7eb',
      accent: '#3b82f6',
      input_bg: '#f9fafb',
      input_border: '#d1d5db'
    },
    dark: {
      button_bg: '#2563eb',
      button_hover: '#1d4ed8',
      button_text: '#ffffff',
      card_bg: '#1f2937',
      card_border: '#374151',
      accent: '#60a5fa',
      input_bg: '#111827',
      input_border: '#4b5563',
      card_text: '#f9fafb',
      muted_text: '#9ca3af'
    },
    modern: {
      button_bg: '#1e293b',
      button_hover: '#334155',
      button_text: '#ffffff',
      card_bg: '#ffffff',
      card_border: '#cbd5e1',
      accent: '#475569',
      input_bg: '#f8fafc',
      input_border: '#94a3b8'
    },
    ocean: {
      button_bg: '#0891b2',
      button_text: '#ffffff',
      card_bg: '#f0fdfa',
      card_border: '#99f6e4',
      accent: '#06b6d4',
      input_bg: '#ecfeff',
      input_border: '#5eead4'
    },
    forest: {
      button_bg: '#059669',
      button_text: '#ffffff',
      card_bg: '#f0fdf4',
      card_border: '#bbf7d0',
      accent: '#10b981',
      input_bg: '#ecfdf5',
      input_border: '#86efac'
    },
    sunset: {
      button_bg: '#f59e0b',
      button_text: '#ffffff',
      card_bg: '#fffbeb',
      card_border: '#fde68a',
      accent: '#f59e0b',
      input_bg: '#fef3c7',
      input_border: '#fbbf24'
    },
    purple: {
      button_bg: '#8b5cf6',
      button_text: '#ffffff',
      card_bg: '#faf5ff',
      card_border: '#e9d5ff',
      accent: '#a855f7',
      input_bg: '#f3e8ff',
      input_border: '#c084fc'
    }
  };

  var VareonCalcAdmin = {
    init: function () {
      this.cacheDOM();
      this.bindEvents();
      this.initColorPickers();
      this.checkTipNotice();
      this.initShortcodeBuilder();
      this.initDocsSidebarNav();
    },

    cacheDOM: function () {
      this.$tabs = $('.vareoncalc-tabs button');
      this.$tabContents = $('.vareoncalc-tab-content');
      this.$layout = $('.vareoncalc-settings-layout');
      this.$formatPresetSelect = $('#vareoncalc-format-preset');
      this.$brandingCheckbox = $("input[name='vareoncalc_lite_options[branding]']");
      this.$themePresetSelect = $('#vareoncalc_theme_preset');
      this.$themePresetField = $("select[name='vareoncalc_lite_options[theme_preset]']");
      this.$colorPickers = $('.vareoncalc-color-picker');
      this.$measurementSelect = $("select[name='vareoncalc_lite_options[measurement_system]']");
      this.$tipNotice = $('.vareoncalc-tip-notice');
      this.$thousandSeparator = $("select[name='vareoncalc_lite_options[thousand_separator]']");
      this.$decimalSeparator = $("select[name='vareoncalc_lite_options[decimal_separator]']");
      this.$currencySelect = $('#currency_symbol_select');
      this.$currencyCustomWrapper = $('#currency_symbol_custom_wrapper');
      this.$currencyCustomInput = $('#currency_symbol_custom');
      this.$currencyCodeHidden = $('#currency_code');
      this.$currencySymbolHidden = $('#currency_symbol');
      this.$currencyPositionSelect = $("select[name='vareoncalc_lite_options[currency_position]']");
      this.$settingsSubmit = $('#vareoncalc-settings-submit');
      this.$settingsSecondary = $('#vareoncalc-settings-secondary');
      this.$shortcodeBuilder = $('[data-shortcode-builder]');
      this.$shortcodeBuilderType = this.$shortcodeBuilder.find('[data-builder-field="type"]');
      this.$shortcodeBuilderTheme = this.$shortcodeBuilder.find('[data-builder-field="theme"]');
      this.$shortcodeBuilderWidth = this.$shortcodeBuilder.find('[data-builder-field="width"]');
      this.$shortcodeBuilderBranding = this.$shortcodeBuilder.find('[data-builder-field="branding"]');
      this.$shortcodeBuilderOutput = this.$shortcodeBuilder.find('[data-builder-output]');
      this.$shortcodeBuilderSummary = this.$shortcodeBuilder.find('[data-builder-summary]');
      this.$shortcodeBuilderWidthNote = this.$shortcodeBuilder.find('[data-builder-width-note]');
      this.$shortcodeBuilderCopy = this.$shortcodeBuilder.find('[data-builder-copy]');
      this.$shortcodeBuilderReset = this.$shortcodeBuilder.find('[data-builder-reset]');
      this.$docsSidebarLinks = $('.vareoncalc-docs-sidebar__nav a[href^="#"]');
      this._docsSidebarTicking = false;
    },

    bindEvents: function () {
      var self = this;

      $(document).on('click', '.vareoncalc-btn', function (event) {
        if (this.type !== 'submit') {
          event.preventDefault();
        }
      });

      this.$tabs.on('click', function () {
        self.switchTab($(this).data('tab'));
      });

      this.$formatPresetSelect.on('change', function () {
        self.handleFormatPresetChange($(this).val());
      });

      this.$themePresetSelect.on('change', function () {
        self.handleThemePresetChange($(this).val());
      });

      this.$brandingCheckbox.on('change', function () {
        self.handleBrandingChange();
      });

      this.$measurementSelect.on('change', function () {
        var newSystem = $(this).val();

        if (typeof window.VAREONCALC_CFG !== 'undefined') {
          window.VAREONCALC_CFG.measurement = window.VAREONCALC_CFG.measurement || {};
          window.VAREONCALC_CFG.measurement.system = newSystem;
        }
        self.syncFormatPreset();
      });

      $(document).on('click', '.vareoncalc-tip-notice-close', function (e) {
        self.dismissTipNotice(e);
      });

      this.$thousandSeparator.on('change', function () {
        self.updateSeparatorConflicts();
        self.syncFormatPreset();
      });
      this.$decimalSeparator.on('change', function () {
        self.updateSeparatorConflicts();
        self.syncFormatPreset();
      });
      this.updateSeparatorConflicts();

      this.$currencySelect.on('change', function () {
        self.handleCurrencyChange();
        self.syncFormatPreset();
      });

      this.$currencyPositionSelect.on('change', function () {
        self.syncFormatPreset();
      });
      this.$currencyCustomInput.on('input', function () {
        var symbol = sanitizeCurrencySymbol($(this).val());
        if ($(this).val() !== symbol) {
          $(this).val(symbol);
        }
        self.$currencySymbolHidden.val(symbol);
        self.$currencyCodeHidden.val('CUSTOM');

        var formattingSnapshot = self.collectFormattingConfig();
        formattingSnapshot.currencySymbol = symbol;
        formattingSnapshot.currencyCode = 'CUSTOM';
        self.pushFormattingToGlobal(formattingSnapshot);
      });
      this.initializeCurrencyControl();

      if (this.$shortcodeBuilder.length) {
        this.$shortcodeBuilderType.on('change', function () {
          self.renderShortcodeBuilder();
        });
        this.$shortcodeBuilderTheme.on('change', function () {
          self.renderShortcodeBuilder();
        });
        this.$shortcodeBuilderWidth.on('input', function () {
          self.renderShortcodeBuilder();
        });
        this.$shortcodeBuilderBranding.on('change', function () {
          self.renderShortcodeBuilder();
        });
        this.$shortcodeBuilderCopy.on('click', function (event) {
          self.copyShortcodeBuilderOutput(event);
        });
        this.$shortcodeBuilderReset.on('click', function (event) {
          self.resetShortcodeBuilder(event);
        });
      }

      if (this.$docsSidebarLinks.length) {
        this.$docsSidebarLinks.on('click', function () {
          var href = $(this).attr('href');
          self.setActiveDocsSidebarLink(href);
          window.setTimeout(function () {
            self.syncDocsSidebarActiveLink();
          }, 80);
        });

        $(window).on('scroll resize', function () {
          self.requestDocsSidebarSync();
        });
      }
    },

    /**
     * Initialize scroll-based active state for the Docs tab sidebar.
     */
    initDocsSidebarNav: function () {
      if (!this.$docsSidebarLinks.length) {
        return;
      }

      this.syncDocsSidebarActiveLink();
    },

    /**
     * Throttle docs sidebar sync work during scroll and resize.
     */
    requestDocsSidebarSync: function () {
      var self = this;

      if (this._docsSidebarTicking) {
        return;
      }

      this._docsSidebarTicking = true;
      window.requestAnimationFrame(function () {
        self._docsSidebarTicking = false;
        self.syncDocsSidebarActiveLink();
      });
    },

    /**
     * Mark the matching docs sidebar link as active.
     * @param {string} href
     */
    setActiveDocsSidebarLink: function (href) {
      if (!this.$docsSidebarLinks.length || !href) {
        return;
      }

      this.$docsSidebarLinks.removeClass('active');
      this.$docsSidebarLinks.filter('[href="' + href + '"]').addClass('active');
    },

    /**
     * Sync the docs sidebar active state with the current scroll position.
     */
    syncDocsSidebarActiveLink: function () {
      if (!this.$docsSidebarLinks.length) {
        return;
      }

      var $docsTab = $('#tab-docs');
      if (!$docsTab.length || !$docsTab.hasClass('active')) {
        return;
      }

      var viewportOffset = 150;
      var activeHref = null;
      var firstHref = null;
      var fallbackHref = null;
      var lastHref = null;

      this.$docsSidebarLinks.each(function () {
        var href = $(this).attr('href');
        var section = href ? document.querySelector(href) : null;

        if (!href || !section) {
          return;
        }

        if (!firstHref) {
          firstHref = href;
        }

        lastHref = href;

        var rect = section.getBoundingClientRect();
        if (!fallbackHref && rect.top > viewportOffset) {
          fallbackHref = href;
        }

        if (rect.top <= viewportOffset) {
          activeHref = href;
        }
      });

      if ((window.innerHeight + window.scrollY) >= (document.documentElement.scrollHeight - 8) && lastHref) {
        activeHref = lastHref;
      }

      if (!activeHref) {
        activeHref = fallbackHref || firstHref;
      }

      this.setActiveDocsSidebarLink(activeHref);
    },

    /**
     * Initialize currency control based on stored value
     */
    initializeCurrencyControl: function () {
      if (!this.$currencySelect.length) {
        return;
      }

      var storedCode = this.$currencyCodeHidden.val() || 'USD';
      if (storedCode === 'CUSTOM') {
        this.$currencySelect.val('custom');
        this.$currencyCustomWrapper.removeClass('vareoncalc-is-hidden');
      } else {
        var $matchOption = this.$currencySelect.find('option[value="' + storedCode + '"]');
        if ($matchOption.length) {
          this.$currencySelect.val(storedCode);
          this.$currencyCustomWrapper.addClass('vareoncalc-is-hidden');
        } else {
          this.$currencySelect.val('USD');
          this.$currencyCustomWrapper.addClass('vareoncalc-is-hidden');
        }
      }
    },

    /**
     * Initialize the Docs tab shortcode builder.
     */
    initShortcodeBuilder: function () {
      if (!this.$shortcodeBuilder.length) {
        return;
      }

      var defaults = shortcodeBuilderCfg.defaults || {};

      if (this.$shortcodeBuilderType.length) {
        this.$shortcodeBuilderType.val(defaults.type || 'loan');
      }
      if (this.$shortcodeBuilderTheme.length) {
        this.$shortcodeBuilderTheme.val(defaults.theme || 'default');
      }
      if (this.$shortcodeBuilderWidth.length) {
        this.$shortcodeBuilderWidth.val(defaults.width || '');
      }
      if (this.$shortcodeBuilderBranding.length) {
        this.$shortcodeBuilderBranding.val(defaults.branding || 'default');
      }

      this.renderShortcodeBuilder();
    },

    /**
     * Match the width sanitization rules used by the shortcode handler.
     * @param {string} rawWidth
     * @returns {string}
     */
    sanitizeShortcodeBuilderWidth: function (rawWidth) {
      if (typeof rawWidth !== 'string') {
        return '';
      }

      var width = rawWidth.trim();
      if (!width) {
        return '';
      }

      if (/^(\d+(?:\.\d+)?)(px|%|em|rem|vw|vh|ch|fr|pt)$/i.test(width)) {
        return width.toLowerCase();
      }

      width = width.toLowerCase();
      if (['auto', 'inherit', 'initial'].indexOf(width) !== -1) {
        return width;
      }

      return '';
    },

    /**
     * Get the current shortcode builder state.
     * @returns {Object}
     */
    getShortcodeBuilderState: function () {
      var rawWidth = this.$shortcodeBuilderWidth.length ? String(this.$shortcodeBuilderWidth.val() || '') : '';

      return {
        type: this.$shortcodeBuilderType.length ? String(this.$shortcodeBuilderType.val() || 'loan') : 'loan',
        theme: this.$shortcodeBuilderTheme.length ? String(this.$shortcodeBuilderTheme.val() || 'default') : 'default',
        branding: this.$shortcodeBuilderBranding.length ? String(this.$shortcodeBuilderBranding.val() || 'default') : 'default',
        rawWidth: rawWidth,
        width: this.sanitizeShortcodeBuilderWidth(rawWidth)
      };
    },

    /**
     * Join summary fragments with natural language separators.
     * @param {Array<string>} items
     * @returns {string}
     */
    joinSummaryParts: function (items) {
      if (!items.length) {
        return '';
      }

      if (items.length === 1) {
        return items[0];
      }

      if (items.length === 2) {
        return items[0] + ' ' + __('and', 'vareon-calculator-suite-lite') + ' ' + items[1];
      }

      return items.slice(0, -1).join(', ') + ', ' + __('and', 'vareon-calculator-suite-lite') + ' ' + items[items.length - 1];
    },

    /**
     * Build a friendly width phrase for the live summary.
     * @param {string} width
     * @returns {string}
     */
    getShortcodeBuilderWidthSummary: function (width) {
      if (!width) {
        return '';
      }

      if (/px$/i.test(width)) {
        return width + ' ' + __('max width', 'vareon-calculator-suite-lite');
      }

      return __('a width of', 'vareon-calculator-suite-lite') + ' ' + width;
    },

    /**
     * Build the shortcode and summary text from the current state.
     * @returns {Object}
     */
    buildShortcodeBuilderOutput: function () {
      var state = this.getShortcodeBuilderState();
      var calculators = shortcodeBuilderCfg.calculators || {};
      var calculatorTitle = calculators[state.type] || this.$shortcodeBuilderType.find('option:selected').text() || __('Loan Calculator', 'vareon-calculator-suite-lite');
      var shortcodeAttributes = ['type="' + state.type + '"'];
      var summaryParts = [];
      var usesGlobalTheme = state.theme === 'default';
      var usesGlobalBranding = state.branding === 'default';
      var themeLabels = {
        light: __('Light', 'vareon-calculator-suite-lite'),
        dark: __('Dark', 'vareon-calculator-suite-lite'),
        modern: __('Modern', 'vareon-calculator-suite-lite')
      };
      var brandingLabels = {
        '1': __('visible branding', 'vareon-calculator-suite-lite'),
        '0': __('hidden branding', 'vareon-calculator-suite-lite')
      };

      if (!usesGlobalTheme && themeLabels[state.theme]) {
        shortcodeAttributes.push('theme="' + state.theme + '"');
        summaryParts.push(__('the', 'vareon-calculator-suite-lite') + ' ' + themeLabels[state.theme] + ' ' + __('preset', 'vareon-calculator-suite-lite'));
      } else {
        summaryParts.push(__('your global theme setting', 'vareon-calculator-suite-lite'));
      }

      if (!usesGlobalBranding && typeof brandingLabels[state.branding] === 'string') {
        shortcodeAttributes.push('branding="' + state.branding + '"');
        summaryParts.push(brandingLabels[state.branding]);
      } else {
        summaryParts.push(__('your global branding setting', 'vareon-calculator-suite-lite'));
      }

      if (state.width) {
        shortcodeAttributes.push('width="' + state.width + '"');
        summaryParts.push(this.getShortcodeBuilderWidthSummary(state.width));
      }

      return {
        shortcode: '[vareon ' + shortcodeAttributes.join(' ') + ']',
        summary: usesGlobalTheme && usesGlobalBranding && !state.width
          ? __('Adds the', 'vareon-calculator-suite-lite') + ' ' + calculatorTitle + ' ' + __('using your global theme and branding settings.', 'vareon-calculator-suite-lite')
          : __('Adds the', 'vareon-calculator-suite-lite') + ' ' + calculatorTitle + ' ' + __('with', 'vareon-calculator-suite-lite') + ' ' + this.joinSummaryParts(summaryParts) + '.',
        hasInvalidWidth: state.rawWidth.trim() !== '' && !state.width
      };
    },

    /**
     * Render the current shortcode builder output.
     */
    renderShortcodeBuilder: function () {
      if (!this.$shortcodeBuilder.length) {
        return;
      }

      var result = this.buildShortcodeBuilderOutput();

      if (this.$shortcodeBuilderOutput.length) {
        this.$shortcodeBuilderOutput.val(result.shortcode);
      }

      if (this.$shortcodeBuilderSummary.length) {
        this.$shortcodeBuilderSummary.text(result.summary);
      }

      if (this.$shortcodeBuilderWidthNote.length) {
        if (result.hasInvalidWidth) {
          this.$shortcodeBuilderWidthNote.text(__('Width was ignored because it is invalid. Use values like 100%, 620px, 40rem, or auto.', 'vareon-calculator-suite-lite'));
          this.$shortcodeBuilderWidthNote.removeAttr('hidden');
        } else {
          this.$shortcodeBuilderWidthNote.attr('hidden', 'hidden').text('');
        }
      }
    },

    /**
     * Reset the shortcode builder back to the default values.
     * @param {Event} event
     */
    resetShortcodeBuilder: function (event) {
      if (event) {
        event.preventDefault();
      }

      var defaults = shortcodeBuilderCfg.defaults || {};

      if (this.$shortcodeBuilderType.length) {
        this.$shortcodeBuilderType.val(defaults.type || 'loan');
      }
      if (this.$shortcodeBuilderTheme.length) {
        this.$shortcodeBuilderTheme.val(defaults.theme || 'default');
      }
      if (this.$shortcodeBuilderWidth.length) {
        this.$shortcodeBuilderWidth.val(defaults.width || '');
      }
      if (this.$shortcodeBuilderBranding.length) {
        this.$shortcodeBuilderBranding.val(defaults.branding || 'default');
      }

      this.renderShortcodeBuilder();
    },

    /**
     * Copy the generated shortcode to the clipboard.
     * @param {Event} event
     */
    copyShortcodeBuilderOutput: function (event) {
      if (event) {
        event.preventDefault();
      }

      if (!this.$shortcodeBuilderOutput.length || !this.$shortcodeBuilderCopy.length) {
        return;
      }

      var self = this;
      var outputEl = this.$shortcodeBuilderOutput.get(0);
      var copyButton = this.$shortcodeBuilderCopy.get(0);
      var value = outputEl ? String(outputEl.value || '') : '';
      var originalText = copyButton ? copyButton.textContent : '';
      var setCopiedState = function () {
        if (!copyButton) {
          return;
        }

        copyButton.textContent = __('Copied!', 'vareon-calculator-suite-lite');
        window.setTimeout(function () {
          if (copyButton) {
            copyButton.textContent = originalText;
          }
        }, 1800);
      };
      var fallbackCopy = function () {
        if (!outputEl) {
          return false;
        }

        outputEl.focus();
        outputEl.select();
        outputEl.setSelectionRange(0, value.length);

        try {
          return document.execCommand('copy');
        } catch (error) {
          return false;
        }
      };

      if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
        navigator.clipboard.writeText(value).then(function () {
          setCopiedState();
        }).catch(function () {
          if (fallbackCopy()) {
            setCopiedState();
            return;
          }

          self.$shortcodeBuilderWidthNote.text(__('Could not copy the shortcode to the clipboard.', 'vareon-calculator-suite-lite')).removeAttr('hidden');
        });
        return;
      }

      if (fallbackCopy()) {
        setCopiedState();
        return;
      }

      this.$shortcodeBuilderWidthNote.text(__('Could not copy the shortcode to the clipboard.', 'vareon-calculator-suite-lite')).removeAttr('hidden');
    },

    /**
     * Apply a format preset (Quick Setup) to all formatting fields and refresh preview.
     * @param {string} presetKey - One of the FORMAT_PRESETS keys or "custom".
     */
    handleFormatPresetChange: function (presetKey) {
      if (!presetKey || presetKey === 'custom' || !FORMAT_PRESETS[presetKey]) {
        return;
      }

      var preset = FORMAT_PRESETS[presetKey];
      this._applyingFormatPreset = true;

      if (this.$currencySelect.length) {
        this.$currencySelect.val(preset.currency_code);
        this.$currencyCustomWrapper.addClass('vareoncalc-is-hidden');

        var selectedOpt = this.$currencySelect.find('option:selected');
        var symbol = selectedOpt.attr('data-symbol') || '$';
        this.$currencyCodeHidden.val(preset.currency_code);
        this.$currencySymbolHidden.val(symbol);
      }

      if (this.$currencyPositionSelect.length) {
        this.$currencyPositionSelect.val(preset.currency_position);
      }

      if (this.$thousandSeparator.length) {
        this.$thousandSeparator.val(preset.thousand_separator);
      }
      if (this.$decimalSeparator.length) {
        this.$decimalSeparator.val(preset.decimal_separator);
      }
      this.updateSeparatorConflicts();

      if (this.$measurementSelect.length) {
        this.$measurementSelect.val(preset.measurement_system);
        if (typeof window.VAREONCALC_CFG !== 'undefined') {
          window.VAREONCALC_CFG.measurement = window.VAREONCALC_CFG.measurement || {};
          window.VAREONCALC_CFG.measurement.system = preset.measurement_system;
        }
      }

      var formattingSnapshot = this.collectFormattingConfig();
      this.pushFormattingToGlobal(formattingSnapshot);

      this._applyingFormatPreset = false;

      this.$currencySelect.trigger('change');
    },

    /**
     * Reverse-sync: when individual formatting fields change, switch the Quick
     * Setup dropdown to the matching preset or "Custom".
     */
    syncFormatPreset: function () {
      if (this._applyingFormatPreset || !this.$formatPresetSelect.length) {
        return;
      }

      var currencyCode = this.$currencyCodeHidden.val() || 'USD';
      var currencyPosition = this.$currencyPositionSelect.val() || 'before';
      var thousandSep = this.$thousandSeparator.val() || 'comma';
      var decimalSep = this.$decimalSeparator.val() || 'dot';
      var measureSystem = this.$measurementSelect.val() || 'mixed';

      var matched = 'custom';
      for (var key in FORMAT_PRESETS) {
        if (!FORMAT_PRESETS.hasOwnProperty(key)) {
          continue;
        }
        var p = FORMAT_PRESETS[key];
        if (
          p.currency_code === currencyCode &&
          p.currency_position === currencyPosition &&
          p.thousand_separator === thousandSep &&
          p.decimal_separator === decimalSep &&
          p.measurement_system === measureSystem
        ) {
          matched = key;
          break;
        }
      }

      this.$formatPresetSelect.val(matched);
    },

    /**
     * Handle currency select change
     */
    handleCurrencyChange: function () {
      var selected = this.$currencySelect.find('option:selected');
      var code = selected.val();
      var attrSymbol = selected.attr('data-symbol');
      var symbol;

      if (code === 'custom') {
        this.$currencyCustomWrapper.removeClass('vareoncalc-is-hidden');
        this.$currencyCodeHidden.val('CUSTOM');
        if (!this.$currencyCustomInput.val()) {
          this.$currencyCustomInput.focus();
        }
        symbol = sanitizeCurrencySymbol(this.$currencyCustomInput.val());
        this.$currencyCustomInput.val(symbol);
      } else {
        this.$currencyCustomWrapper.addClass('vareoncalc-is-hidden');
        this.$currencyCodeHidden.val(code);
        // Use .attr() instead of .data() to get the raw attribute value
        // jQuery's .data() can have caching/parsing issues with special characters
        symbol = attrSymbol;
        if (typeof symbol === 'undefined' || symbol === '' || symbol === null) {
          var nativeOption = selected && selected.length ? selected[0] : null;
          var datasetSymbol = nativeOption && nativeOption.dataset ? nativeOption.dataset.symbol : null;
          if (!datasetSymbol && nativeOption && nativeOption.textContent) {
            var txt = nativeOption.textContent.trim();
            var parts = txt.split('-');
            if (parts.length > 0) {
              var candidate = parts[0].trim();
              if (candidate.length <= 6) {
                datasetSymbol = candidate;
              }
            }
          }
          symbol = datasetSymbol || '$';
        }
      }

      this.$currencySymbolHidden.val(symbol);

      var formattingSnapshot = this.collectFormattingConfig();
      formattingSnapshot.currencySymbol = symbol;
      formattingSnapshot.currencyCode = code === 'custom' ? 'CUSTOM' : code;
      this.pushFormattingToGlobal(formattingSnapshot);
    },

    /**
     * Prevent thousand and decimal separators from having conflicting values
     */
    updateSeparatorConflicts: function () {
      if (!this.$thousandSeparator.length || !this.$decimalSeparator.length) {
        return;
      }

      var thousandVal = this.$thousandSeparator.val();
      var decimalVal = this.$decimalSeparator.val();
      var conflictMsg = __('Cannot match the other separator', 'vareon-calculator-suite-lite');

      this.$thousandSeparator.find('option:not(:disabled)').prop('disabled', false).removeAttr('title');
      this.$decimalSeparator.find('option').prop('disabled', false).removeAttr('title');

      if (decimalVal === 'comma' || decimalVal === 'dot') {
        var $conflictInThousand = this.$thousandSeparator.find('option[value="' + decimalVal + '"]');
        if ($conflictInThousand.length && $conflictInThousand.val() !== thousandVal) {
          $conflictInThousand.prop('disabled', true).attr('title', conflictMsg);
        }
      }

      if (thousandVal === 'comma' || thousandVal === 'dot') {
        var $conflictInDecimal = this.$decimalSeparator.find('option[value="' + thousandVal + '"]');
        if ($conflictInDecimal.length && $conflictInDecimal.val() !== decimalVal) {
          $conflictInDecimal.prop('disabled', true).attr('title', conflictMsg);
        }
      }

      if (thousandVal && decimalVal && thousandVal === decimalVal) {
        var newDecimal = decimalVal === 'dot' ? 'comma' : 'dot';
        this.$decimalSeparator.val(newDecimal);
        this.updateSeparatorConflicts();
      }
    },

    /**
     * Initialize color pickers (Pro only, handled gracefully)
     */
    initColorPickers: function () {
      if (this.$colorPickers.length === 0) {
        return;
      }

      this.$colorPickers.wpColorPicker({
        change: function () {},
        clear: function () {}
      });
    },

    /**
     * Keep branding preference mirrored in runtime config used by settings controls.
     */
    handleBrandingChange: function () {
      if (typeof window.VAREONCALC_CFG !== 'undefined') {
        window.VAREONCALC_CFG.branding = this.$brandingCheckbox.is(':checked');
      }
    },

    /**
     * Check if tip notice should be shown or hidden
     */
    checkTipNotice: function () {
      if (!this.$tipNotice.length) {
        return;
      }
    },

    /**
     * Dismiss the tip notice and persist user preference
     * @param {Event} e - Click event
     */
    dismissTipNotice: function (e) {
      e.preventDefault();
      this.$tipNotice.slideUp();

      if (!settingsTipNoticeCfg || !settingsTipNoticeCfg.ajaxUrl || !settingsTipNoticeCfg.action || !settingsTipNoticeCfg.nonce) {
        return;
      }

      $.post(settingsTipNoticeCfg.ajaxUrl, {
        action: settingsTipNoticeCfg.action,
        nonce: settingsTipNoticeCfg.nonce
      });
    },

    /**
     * Switch to a specific tab
     * @param {string} tabId - The tab ID to activate
     */
    switchTab: function (tabId) {
      if (!tabId || $('#' + tabId).length === 0) {
        return;
      }

      var isWaitlistTab = tabId === 'tab-pro-waitlist';

      this.$tabs.removeClass('active');
      this.$tabs.filter('[data-tab="' + tabId + '"]').addClass('active');
      this.$tabContents.removeClass('active');
      $('#' + tabId).addClass('active');

      if (this.$layout && this.$layout.length) {
        this.$layout.toggleClass('is-docs-tab', tabId === 'tab-docs');
      }

      if (this.$settingsSubmit.length) {
        this.$settingsSubmit.toggleClass('vareoncalc-is-hidden', isWaitlistTab);
      }

      if (this.$settingsSecondary.length) {
        this.$settingsSecondary.toggleClass('vareoncalc-is-hidden', isWaitlistTab);
      }

      if (typeof tabUrls[tabId] === 'string' &&
        window.history &&
        window.history.replaceState) {
        window.history.replaceState({}, document.title, tabUrls[tabId]);
      }

      if (tabId === 'tab-docs') {
        this.requestDocsSidebarSync();
      }
    },

    /**
     * Handle theme preset selection changes
     * @param {string} preset - The selected preset name
     */
    handleThemePresetChange: function (preset) {
      if (!preset || preset === 'custom' || !THEME_PRESETS[preset]) {
        return;
      }

      var colors = THEME_PRESETS[preset];

      if ($('#button_bg_color').length === 0) {
        return;
      }

      $('#button_bg_color').wpColorPicker('color', colors.button_bg);
      $('#button_text_color').wpColorPicker('color', colors.button_text);
      $('#card_bg_color').wpColorPicker('color', colors.card_bg);
      $('#card_border_color').wpColorPicker('color', colors.card_border);
      $('#accent_color').wpColorPicker('color', colors.accent);
      $('#input_bg_color').wpColorPicker('color', colors.input_bg);
      $('#input_border_color').wpColorPicker('color', colors.input_border);
    },


    /**
     * Collect current formatting selections from the settings UI
     * @returns {Object}
     */
    collectFormattingConfig: function () {
      var formatting = {};
      var symbol = null;
      var code = null;
      if (this.$currencySelect && this.$currencySelect.length) {
        var selectedOption = this.$currencySelect.find('option:selected');
        var selectedCode = selectedOption.val();

        if (selectedCode === 'custom') {
          if (this.$currencyCustomInput && this.$currencyCustomInput.length) {
            symbol = this.$currencyCustomInput.val() || '$';
          }
          code = 'CUSTOM';
        } else if (selectedCode) {
          symbol = selectedOption.attr('data-symbol');
          code = selectedCode;
        }
      }

      if (!symbol && this.$currencySymbolHidden && this.$currencySymbolHidden.length) {
        symbol = this.$currencySymbolHidden.val();
      }
      if (!code && this.$currencyCodeHidden && this.$currencyCodeHidden.length) {
        code = this.$currencyCodeHidden.val();
      }

      if (!symbol) {
        var globalFormatting = (typeof window.VAREONCALC_CFG !== 'undefined' && window.VAREONCALC_CFG.formatting) || {};
        symbol = globalFormatting.currencySymbol || '$';
      }
      if (!code) {
        var globalFormatting = (typeof window.VAREONCALC_CFG !== 'undefined' && window.VAREONCALC_CFG.formatting) || {};
        code = globalFormatting.currencyCode || 'USD';
      }

      formatting.currencySymbol = symbol;
      formatting.currencyCode = code;

      var $currencyPosition = $("select[name='vareoncalc_lite_options[currency_position]']");
      if ($currencyPosition.length) {
        formatting.currencyPosition = $currencyPosition.val() || 'before';
      }

      var $currencySpacing = $("select[name='vareoncalc_lite_options[currency_spacing]']");
      if ($currencySpacing.length) {
        formatting.currencySpacing = $currencySpacing.val() || 'none';
      }

      if (this.$thousandSeparator.length) {
        formatting.thousandSeparator = this.$thousandSeparator.val() || 'comma';
      }
      if (this.$decimalSeparator.length) {
        formatting.decimalSeparator = this.$decimalSeparator.val() || 'dot';
      }

      return formatting;
    },

    /**
     * Push a formatting object into the global preview config
     * @param {Object} formatting
     */
    pushFormattingToGlobal: function (formatting) {
      if (typeof window === 'undefined') {
        return;
      }
      window.VAREONCALC_CFG = window.VAREONCALC_CFG || {};
      window.VAREONCALC_CFG.formatting = {
        ...(window.VAREONCALC_CFG.formatting || {}),
        ...(formatting || {})
      };
    }
  };

  $(document).ready(function () {
    VareonCalcAdmin.init();
  });

})(jQuery, wp.i18n.__);
