(function () {
  'use strict';

  const form        = document.getElementById('readjutsu-settings-form');
  const saveBtn     = document.querySelector('[name="readjutsu_submit_ajax"]');
  const toast       = document.getElementById('readjutsu-toast');
  const toastOk     = document.getElementById('readjutsu-toast-success');
  const toastErr    = document.getElementById('readjutsu-toast-error');
  const loadingMask = document.getElementById('readjutsu-loading-mask');

  // ── Tab navigation ──────────────────────────────────────────────────────────
  const menuItems = document.querySelectorAll('.readjutsu-settings__menu [data-menu]');
  const panels    = document.querySelectorAll('.readjutsu-settings__menu-content');

  menuItems.forEach(function (item) {
    item.addEventListener('click', function () {
      menuItems.forEach(function (i) { i.classList.remove('active'); });
      panels.forEach(function (p)    { p.classList.remove('active'); });
      item.classList.add('active');
      var target = document.getElementById(item.dataset.menu);
      if (target) target.classList.add('active');
    });
  });

  // ── AJAX Save ───────────────────────────────────────────────────────────────
  function saveSettings() {
    var data = new FormData(form);
    data.append('action', 'readjutsu_save');
    data.append('_ajax_nonce', READJUTSUADMIN.nonce);

    loadingMask.style.display = 'block';

    fetch(READJUTSUADMIN.ajaxUrl, { method: 'POST', body: data })
      .then(function (r) { return r.json(); })
      .then(function (json) {
        loadingMask.style.display = 'none';
        showToast(json.success === true);
      })
      .catch(function () {
        loadingMask.style.display = 'none';
        showToast(false);
      });
  }

  function showToast(success) {
    toast.classList.remove('active', 'readjutsu-toast--success', 'readjutsu-toast--error');
    toastOk.style.display  = 'none';
    toastErr.style.display = 'none';

    if (success) {
      toast.classList.add('readjutsu-toast--success');
      toastOk.style.display = 'block';
    } else {
      toast.classList.add('readjutsu-toast--error');
      toastErr.style.display = 'block';
    }
    void toast.offsetWidth; // force reflow → restart animation
    toast.classList.add('active');
  }

  if (saveBtn) {
    saveBtn.addEventListener('click', function (e) {
      e.preventDefault();
      saveSettings();
    });
  }

  document.addEventListener('keydown', function (e) {
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
      e.preventDefault();
      saveSettings();
    }
  });

  // ── Display mode: Auto shows placement options, Manual shows the block/SC tip ─
  function bindDisplayToggle(name, autoId, manualId) {
    var radios   = document.querySelectorAll('[name="' + name + '"]');
    var autoEl   = document.getElementById(autoId);
    var manualEl = document.getElementById(manualId);

    function sync() {
      var checked  = document.querySelector('[name="' + name + '"]:checked');
      var isManual = checked && checked.value === 'manual';
      if (autoEl)   autoEl.style.display   = isManual ? 'none' : '';
      if (manualEl) manualEl.style.display = isManual ? '' : 'none';
    }

    radios.forEach(function (r) { r.addEventListener('change', sync); });
    sync();
  }

  bindDisplayToggle('readjutsu_badge_display',    'readjutsu-badge-auto',    'readjutsu-badge-placement-tip');
  bindDisplayToggle('readjutsu_progress_display', 'readjutsu-progress-auto', 'readjutsu-progress-placement-tip');

  // ── Show/hide gradient secondary color ──────────────────────────────────────
  var barStyleRadios = document.querySelectorAll('[name="readjutsu_progress_style"]');
  var color2row      = document.getElementById('readjutsu-progress-color2-row');

  function syncColor2() {
    var checked = document.querySelector('[name="readjutsu_progress_style"]:checked');
    if (color2row) {
      color2row.style.display = (checked && checked.value === 'gradient') ? '' : 'none';
    }
  }

  function syncDonutPosition() {
    var checked = document.querySelector('[name="readjutsu_progress_style"]:checked');
    var show    = (checked && checked.value === 'donut') ? '' : 'none';
    ['readjutsu-donut-position-row', 'readjutsu-donut-size-row'].forEach(function (id) {
      var row = document.getElementById(id);
      if (row) row.style.display = show;
    });
  }

  barStyleRadios.forEach(function (r) {
    r.addEventListener('change', syncColor2);
    r.addEventListener('change', syncDonutPosition);
  });
  syncColor2();
  syncDonutPosition();

  // ── Show/hide floating badge position ───────────────────────────────────────
  var badgeStyleRadios = document.querySelectorAll('[name="readjutsu_badge_style"]');

  function syncFloatPosition() {
    var checked  = document.querySelector('[name="readjutsu_badge_style"]:checked');
    var floatRow = document.getElementById('readjutsu-float-position-row');
    if (floatRow) floatRow.style.display = (checked && checked.value === 'floating') ? '' : 'none';
  }

  badgeStyleRadios.forEach(function (r) {
    r.addEventListener('change', syncFloatPosition);
  });
  syncFloatPosition();

  // ── Analytics: period selector (panels are pre-rendered server-side) ────────
  var periodBtns = document.querySelectorAll('.readjutsu-analytics-period [data-period]');
  periodBtns.forEach(function (btn) {
    btn.addEventListener('click', function () {
      periodBtns.forEach(function (b) { b.classList.remove('button-primary'); });
      btn.classList.add('button-primary');
      document.querySelectorAll('.readjutsu-analytics-panel').forEach(function (panel) {
        panel.style.display = (panel.id === 'readjutsu-analytics-' + btn.dataset.period) ? '' : 'none';
      });
    });
  });

  // ── Live color preview ───────────────────────────────────────────────────────

  function syncBadgePreviews() {
    var colorEl     = document.querySelector('[name="readjutsu_badge_color"]');
    var textColorEl = document.querySelector('[name="readjutsu_badge_text_color"]');
    if (!colorEl || !textColorEl) return;
    var c  = colorEl.value;
    var tc = textColorEl.value;

    document.querySelectorAll('.readjutsu-preview-badge--pill').forEach(function (el) {
      el.style.background = c;
      el.style.color = tc;
    });
    document.querySelectorAll('.readjutsu-preview-badge--floating').forEach(function (el) {
      if (el.closest('.readjutsu-locked-card')) return;
      el.style.background = c;
      el.style.color = tc;
    });
    document.querySelectorAll('.readjutsu-preview-badge--minimal').forEach(function (el) {
      el.style.color = c;
    });
    document.querySelectorAll('.readjutsu-preview-badge--inline').forEach(function (el) {
      el.style.color = c;
    });
    document.querySelectorAll('.readjutsu-preview-badge--bordered').forEach(function (el) {
      if (el.closest('.readjutsu-locked-card')) return;
      el.style.color = c;
      el.style.borderColor = c;
    });
    document.querySelectorAll('.readjutsu-preview-badge--glass').forEach(function (el) {
      if (el.closest('.readjutsu-locked-card')) return;
      el.style.background = hexToRgba(c, 0.18);
      el.style.borderColor = hexToRgba(c, 0.35);
      el.style.color = tc;
    });
  }

  function hexToRgba(hex, alpha) {
    hex = (hex || '').replace('#', '');
    if (hex.length === 3) hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
    if (hex.length !== 6) hex = 'ffffff';
    var r = parseInt(hex.slice(0, 2), 16),
        g = parseInt(hex.slice(2, 4), 16),
        b = parseInt(hex.slice(4, 6), 16);
    return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
  }

  function syncBarPreviews() {
    var colorEl  = document.querySelector('[name="readjutsu_progress_color"]');
    var color2El = document.querySelector('[name="readjutsu_progress_color2"]');
    if (!colorEl) return;
    var c  = colorEl.value;
    var c2 = color2El ? color2El.value : c;

    var solidBar = document.querySelector('#bar-solid + label .readjutsu-preview-bar');
    if (solidBar) solidBar.style.background = c;

    var gradBar = document.querySelector('#bar-gradient + label .readjutsu-preview-bar');
    if (gradBar) gradBar.style.background = 'linear-gradient(to right,' + c + ',' + c2 + ')';

    var animBar = document.querySelector('#bar-animated + label .readjutsu-preview-bar');
    if (animBar) animBar.style.background = c;

    // All percent bars (premium unlocked + locked upsell card)
    document.querySelectorAll('.readjutsu-preview-bar').forEach(function (bar) {
      var pctLabel = bar.querySelector('.readjutsu-preview-bar__pct');
      if (!pctLabel) return;
      bar.style.background = c;
      pctLabel.style.background = c;
    });

    // All donuts (premium unlocked + locked upsell card)
    document.querySelectorAll('.readjutsu-preview-donut').forEach(function (donut) {
      var arcs = donut.querySelectorAll('circle');
      if (arcs.length >= 2) arcs[1].setAttribute('stroke', c);
      var txt = donut.querySelector('text');
      if (txt) txt.setAttribute('fill', c);
    });
  }

  document.querySelectorAll('[name="readjutsu_badge_color"], [name="readjutsu_badge_text_color"]').forEach(function (el) {
    el.addEventListener('input', syncBadgePreviews);
  });

  document.querySelectorAll('[name="readjutsu_progress_color"], [name="readjutsu_progress_color2"], [name="readjutsu_progress_bg"]').forEach(function (el) {
    el.addEventListener('input', syncBarPreviews);
  });

  syncBadgePreviews();
  syncBarPreviews();

  // ── Ready ────────────────────────────────────────────────────────────────────
  var wrapper = document.getElementById('readjutsu-settings');
  if (wrapper) wrapper.classList.add('readjutsu-is-ready');
})();
