(function () {
  'use strict';

  var cfg = window.wppsMagicLoginAdmin || {};
  var root = document.querySelector('.wpps-magic-login-settings');
  if (!root) {
    return;
  }

  /* Accordions (Code Snippets pattern) */
  var accordionStorageKey = 'wpps_ml_accordion_state';
  var accordionDefaults = {
    general: true,
    features: false,
    shortcode: false,
    register: false,
    limits: false,
    security: false,
    error_messages: false,
    stats: false,
  };

  function loadAccordionState() {
    try {
      var stored = localStorage.getItem(accordionStorageKey);
      return stored ? Object.assign({}, accordionDefaults, JSON.parse(stored)) : accordionDefaults;
    } catch (e) {
      return accordionDefaults;
    }
  }

  function saveAccordionState(state) {
    try {
      localStorage.setItem(accordionStorageKey, JSON.stringify(state));
    } catch (e) {
      /* ignore */
    }
  }

  function applyAccordionState(state) {
    document.querySelectorAll('.wpps-cs-accordion[data-accordion-id]').forEach(function (el) {
      var id = el.getAttribute('data-accordion-id');
      if (!id) {
        return;
      }
      var isOpen = !!state[id];
      el.classList.toggle('is-open', isOpen);
      var header = el.querySelector('.wpps-cs-accordion-header');
      if (header) {
        header.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
      }
    });
  }

  var accordionState = loadAccordionState();
  applyAccordionState(accordionState);

  function syncMultiselectAccordionLayers(container) {
    container.querySelectorAll('.wpps-cs-accordion').forEach(function (acc) {
      acc.classList.remove('wpps-ml-accordion--dropdown-open');
    });
    var openTrigger = container.querySelector('.wpps-ct-multiselect__trigger[aria-expanded="true"]');
    if (openTrigger) {
      var accordion = openTrigger.closest('.wpps-cs-accordion');
      if (accordion) {
        accordion.classList.add('wpps-ml-accordion--dropdown-open');
      }
    }
  }

  function closeMultiselectsIn(accordion) {
    if (!accordion) {
      return;
    }
    accordion.querySelectorAll('.wpps-ct-multiselect__dropdown').forEach(function (dropdown) {
      dropdown.setAttribute('hidden', '');
    });
    accordion.querySelectorAll('.wpps-ct-multiselect__trigger').forEach(function (trigger) {
      trigger.setAttribute('aria-expanded', 'false');
    });
    accordion.classList.remove('wpps-ml-accordion--dropdown-open');
  }

  document.querySelectorAll('.wpps-cs-accordion-header').forEach(function (header) {
    header.addEventListener('click', function () {
      var accordion = header.closest('.wpps-cs-accordion');
      if (!accordion) {
        return;
      }
      closeMultiselectsIn(accordion);
      var id = accordion.getAttribute('data-accordion-id');
      if (!id) {
        return;
      }
      var isOpen = accordion.classList.contains('is-open');
      accordion.classList.toggle('is-open', !isOpen);
      header.setAttribute('aria-expanded', !isOpen ? 'true' : 'false');
      accordionState[id] = !isOpen;
      saveAccordionState(accordionState);
    });
  });

  /* Role multiselect */
  function initRoleMultiselects(container) {
    var roots = container.querySelectorAll('.wpps-ct-multiselect');
    roots.forEach(function (msRoot) {
      if (msRoot.getAttribute('data-wpps-multiselect-initialized') === '1') {
        return;
      }
      var prefix = 'wpps-ct-multiselect';
      var trigger = msRoot.querySelector('.' + prefix + '__trigger');
      var triggerText = msRoot.querySelector('.' + prefix + '__trigger-text');
      var dropdown = msRoot.querySelector('.' + prefix + '__dropdown');
      var search = msRoot.querySelector('.' + prefix + '__search');
      var options = msRoot.querySelectorAll('.' + prefix + '__option');
      var hiddenClass = prefix + '__option--hidden';
      if (!trigger || !triggerText || !dropdown || !search) {
        return;
      }

      function countChecked() {
        var n = 0;
        options.forEach(function (o) {
          var cb = o.querySelector('input[type="checkbox"]');
          if (cb && cb.checked) {
            n++;
          }
        });
        return n;
      }

      function updateTriggerText() {
        var n = countChecked();
        var none = msRoot.dataset.labelNone || 'Select roles…';
        var single = msRoot.dataset.labelSingle || '1 selected';
        var multi = (msRoot.dataset.labelMulti || '%d selected').replace('%d', String(n));
        triggerText.textContent = n === 0 ? none : n === 1 ? single : multi;
      }

      function filterOptions(q) {
        q = (q || '').toLowerCase().trim();
        options.forEach(function (o) {
          var label = (o.dataset.label || '').toLowerCase();
          var slug = (o.dataset.slug || '').toLowerCase();
          var show = !q || label.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
          o.classList.toggle(hiddenClass, !show);
        });
      }

      function toggleDropdown(open) {
        var isOpen = open === undefined ? dropdown.hasAttribute('hidden') : !!open;
        if (isOpen) {
          root.querySelectorAll('.wpps-ct-multiselect__dropdown').forEach(function (otherDropdown) {
            if (otherDropdown !== dropdown) {
              otherDropdown.setAttribute('hidden', '');
            }
          });
          root.querySelectorAll('.wpps-ct-multiselect__trigger').forEach(function (otherTrigger) {
            if (otherTrigger !== trigger) {
              otherTrigger.setAttribute('aria-expanded', 'false');
            }
          });
          dropdown.removeAttribute('hidden');
          trigger.setAttribute('aria-expanded', 'true');
          search.value = '';
          filterOptions('');
          setTimeout(function () {
            search.focus();
          }, 50);
        } else {
          dropdown.setAttribute('hidden', '');
          trigger.setAttribute('aria-expanded', 'false');
        }
        syncMultiselectAccordionLayers(root);
      }

      trigger.addEventListener(
        'click',
        function (e) {
          e.preventDefault();
          e.stopPropagation();
          toggleDropdown();
        },
        true
      );
      search.addEventListener('input', function () {
        filterOptions(search.value);
      });
      msRoot.querySelectorAll('.' + prefix + '__action').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
          e.preventDefault();
          var action = btn.dataset.action;
          var visible = Array.prototype.filter.call(options, function (o) {
            return !o.classList.contains(hiddenClass);
          });
          if (action === 'select-all') {
            visible.forEach(function (o) {
              var cb = o.querySelector('input[type="checkbox"]');
              if (cb) {
                cb.checked = true;
              }
            });
          } else if (action === 'clear') {
            options.forEach(function (o) {
              var cb = o.querySelector('input[type="checkbox"]');
              if (cb) {
                cb.checked = false;
              }
            });
          }
          updateTriggerText();
        });
      });
      options.forEach(function (o) {
        var cb = o.querySelector('input[type="checkbox"]');
        if (cb) {
          cb.addEventListener('change', updateTriggerText);
        }
        o.addEventListener('click', function (e) {
          if (e.target.tagName !== 'INPUT') {
            var box = o.querySelector('input[type="checkbox"]');
            if (box) {
              box.checked = !box.checked;
              updateTriggerText();
            }
          }
        });
      });
      document.addEventListener('click', function (e) {
        if (!msRoot.contains(e.target)) {
          toggleDropdown(false);
        }
      });
      updateTriggerText();
      msRoot.setAttribute('data-wpps-multiselect-initialized', '1');
    });
  }

  initRoleMultiselects(root);

  function syncStyleColorInputs(form) {
    form.querySelectorAll('.wpps-color-code-input').forEach(function (hexInp) {
      var hex = (hexInp.value || '').trim();
      if (hex.indexOf('#') !== 0) {
        hex = '#' + hex;
      }
      if (/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(hex)) {
        var colorId = hexInp.getAttribute('data-color-input');
        var circle = colorId ? document.getElementById(colorId) : null;
        if (circle) {
          circle.value = hex.length > 7 ? hex.substring(0, 7) : hex;
        }
      }
    });
  }

  root.querySelectorAll('.wpps-color-reset').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var def = btn.getAttribute('data-default-color');
      var row = btn.closest('.wpps-color-field-row');
      if (!row || !def) {
        return;
      }
      var circle = row.querySelector('.wpps-color-picker-circle');
      var hex = row.querySelector('.wpps-color-code-input');
      if (circle) {
        circle.value = def;
      }
      if (hex) {
        hex.value = def;
      }
    });
  });

  /* Collect settings (same rules as PowerSuite modal) */
  function collectSettings() {
    var form = document.getElementById('wpps-magic-login-settings-form') || root;
    var inputs = form.querySelectorAll('.wp-powersuite-advanced-setting');
    var settingsObj = {};
    var radioGroups = {};

    inputs.forEach(function (input) {
      var key = input.dataset.settingKey;
      if (!key) {
        return;
      }
      if (input.type === 'radio') {
        if (!radioGroups[key]) {
          radioGroups[key] = [];
        }
        radioGroups[key].push(input);
      } else if (input.type === 'checkbox') {
        if (input.name && input.name.indexOf('[]') !== -1) {
          if (!settingsObj[key]) {
            settingsObj[key] = [];
          }
          if (input.checked) {
            settingsObj[key].push(input.value);
          }
        } else if (key.indexOf('.') !== -1) {
          if (input.checked) {
            settingsObj[key] = '1';
          }
        } else {
          settingsObj[key] = input.checked ? '1' : '0';
        }
      } else if (input.tagName === 'TEXTAREA') {
        settingsObj[key] = input.value || '';
      } else {
        settingsObj[key] = input.value || '';
      }
    });

    Object.keys(radioGroups).forEach(function (key) {
      var radios = radioGroups[key];
      var checked = radios.find(function (r) {
        return r.checked;
      });
      if (checked) {
        settingsObj[key] = checked.value || '';
      }
    });

    inputs.forEach(function (input) {
      if (input.type === 'checkbox' && input.name && input.name.indexOf('[]') !== -1) {
        var k = input.dataset.settingKey;
        if (k && !Object.prototype.hasOwnProperty.call(settingsObj, k)) {
          settingsObj[k] = [];
        }
      }
    });

    Object.keys(settingsObj).forEach(function (key) {
      var colorInput = form.querySelector('input[type="color"][data-setting-key="' + key + '"]');
      if (colorInput && colorInput.value) {
        settingsObj[key] =
          colorInput.value.charAt(0) === '#' ? colorInput.value : '#' + colorInput.value;
      }
    });

    var nested = {};
    Object.keys(settingsObj).forEach(function (key) {
      if (key.indexOf('.') !== -1) {
        var keys = key.split('.');
        var current = nested;
        for (var i = 0; i < keys.length - 1; i++) {
          if (!current[keys[i]]) {
            current[keys[i]] = {};
          }
          current = current[keys[i]];
        }
        current[keys[keys.length - 1]] = settingsObj[key];
      } else {
        nested[key] = settingsObj[key];
      }
    });

    return nested;
  }

  function appendToFormData(obj, prefixParts, fd) {
    prefixParts = prefixParts || [];
    Object.keys(obj).forEach(function (key) {
      var value = obj[key];
      var parts = prefixParts.concat([key]);
      var fieldPrefix = 'settings[' + parts.join('][') + ']';
      if (Array.isArray(value)) {
        value.forEach(function (v, i) {
          fd.append(fieldPrefix + '[' + i + ']', v);
        });
        if (value.length === 0) {
          fd.append(fieldPrefix, '');
        }
      } else if (value !== null && typeof value === 'object') {
        appendToFormData(value, parts, fd);
      } else {
        fd.append(fieldPrefix, value == null ? '' : String(value));
      }
    });
  }

  var toastTimer;

  function showToast(message, ok) {
    var toast = document.getElementById('wpps-ml-toast');
    var msg = document.getElementById('wpps-ml-toast-message');
    if (!toast || !msg) {
      return;
    }
    clearTimeout(toastTimer);
    msg.textContent = message;
    toast.className = 'wpps-cs-toast ' + (ok ? 'wpps-cs-toast-success' : 'wpps-cs-toast-error');
    toast.setAttribute('aria-hidden', 'false');
    toast.classList.add('is-visible');
    toastTimer = setTimeout(function () {
      toast.classList.remove('is-visible');
      toast.setAttribute('aria-hidden', 'true');
    }, 3200);
  }

  var saveBtn = document.getElementById('wpps-ml-save-settings');
  if (saveBtn) {
    saveBtn.addEventListener('click', function () {
      if (!cfg.ajaxUrl || !cfg.nonce || !cfg.moduleId) {
        return;
      }
      var form = document.getElementById('wpps-magic-login-settings-form') || root;
      syncStyleColorInputs(form);
      var fd = new FormData();
      fd.append('action', cfg.saveAction || 'wp_powersuite_save_module_settings');
      fd.append('module_id', cfg.moduleId);
      fd.append('nonce', cfg.nonce);
      appendToFormData(collectSettings(), [], fd);

      saveBtn.classList.add('is-loading');
      saveBtn.disabled = true;
      var label = saveBtn.textContent;
      saveBtn.textContent = cfg.saving || 'Saving…';

      fetch(cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
        .then(function (r) {
          return r.json();
        })
        .then(function (res) {
          if (res && res.success) {
            showToast(cfg.savedMessage || 'Settings saved.', true);
          } else {
            var msg =
              (res && res.data && res.data.message) || cfg.saveFailed || 'Could not save settings.';
            showToast(msg, false);
          }
        })
        .catch(function () {
          showToast(cfg.saveFailed || 'Could not save settings.', false);
        })
        .finally(function () {
          saveBtn.classList.remove('is-loading');
          saveBtn.disabled = false;
          saveBtn.textContent = label;
        });
    });
  }
})();
