/* global jQuery, WPSNDriftMonitor */
(function () {
  'use strict';

  function qs(sel, root) {
    return (root || document).querySelector(sel);
  }

  function qsa(sel, root) {
    return Array.prototype.slice.call((root || document).querySelectorAll(sel));
  }

  function setHtml(el, html) {
    if (!el) return;
    el.innerHTML = html;
  }

  function showInlineNotice(container, type, msg) {
    if (!container) return;
    var cls = 'notice notice-' + (type || 'info');
    var html = '<div class="' + cls + '"><p>' + String(msg || '') + '</p></div>';
    setHtml(container, html + container.innerHTML);
  }

  function scrollToEl(el) {
    if (!el || !el.getBoundingClientRect) return;
    var rect = el.getBoundingClientRect();
    var y = rect.top + (window.pageYOffset || document.documentElement.scrollTop || 0);
    var offset = 18;
    var bar = document.getElementById('wpadminbar');
    if (bar && bar.offsetHeight) {
      offset += bar.offsetHeight;
    }
    try {
      window.scrollTo({ top: Math.max(0, y - offset), behavior: 'smooth' });
    } catch (err) {
      window.scrollTo(0, Math.max(0, y - offset));
    }
  }

  function flashEl(el) {
    if (!el || !el.classList) return;
    // Restart animation if it already ran.
    el.classList.remove('wpsn-flash');
    // Force reflow so CSS animation restarts reliably.
    // eslint-disable-next-line no-unused-expressions
    el.offsetWidth;
    el.classList.add('wpsn-flash');
    window.setTimeout(function () {
      try {
        el.classList.remove('wpsn-flash');
      } catch (err) {
        // ignore
      }
    }, 1600);
  }

  function scrollToDupeNotice() {
    var mgr = document.getElementById('wpsn-drift-dupe-manager');
    if (!mgr) return;
    var notice = mgr.querySelector('.notice');
    var target = notice || mgr;
    scrollToEl(target);
    // Give smooth scroll a moment, then highlight the target so the result is obvious.
    window.setTimeout(function () {
      flashEl(target);
    }, 450);
  }

  function ajaxPost(action, data) {
    var fd = data instanceof FormData ? data : new FormData();
    fd.set('action', action);
    fd.set('nonce', (WPSNDriftMonitor && WPSNDriftMonitor.nonce) ? WPSNDriftMonitor.nonce : '');

    return fetch((WPSNDriftMonitor && WPSNDriftMonitor.ajaxUrl) ? WPSNDriftMonitor.ajaxUrl : ajaxurl, {
      method: 'POST',
      credentials: 'same-origin',
      body: fd
    }).then(function (r) {
      return r.json();
    });
  }

  function isLiveModeEnabled() {
    var cb = qs('#wpsn-drift-dupe-live-mode');
    return !!(cb && cb.checked);
  }

  function initLiveModeToggle() {
    var cb = qs('#wpsn-drift-dupe-live-mode');
    if (!cb) return;

    try {
      if (window.localStorage) {
        cb.checked = window.localStorage.getItem('wpsn_drift_dupe_live_mode') === '1';
      }
    } catch (err) {
      // ignore
    }

    if (cb.getAttribute('data-wpsn-bound') === '1') {
      return;
    }
    cb.setAttribute('data-wpsn-bound', '1');
    cb.addEventListener('change', function () {
      try {
        if (window.localStorage) {
          window.localStorage.setItem('wpsn_drift_dupe_live_mode', cb.checked ? '1' : '0');
        }
      } catch (err) {
        // ignore
      }
    });
  }

  function initDupesAjax() {
    if (!window.WPSNDriftMonitor || !window.fetch || !window.FormData) {
      return;
    }

    var form = qs('#wpsn-drift-dupe-form');
    var previewBtn = qs('#wpsn-drift-dupe-preview-btn');
    var applyBtn = qs('#wpsn-drift-dupe-apply-btn');
    var previewContainer = qs('#wpsn-drift-dupe-preview-container');

    initLiveModeToggle();

    if (!form || !previewBtn || !previewContainer) {
      return;
    }

    // Avoid double-binding if this block gets replaced via AJAX.
    if (form.getAttribute('data-wpsn-ajax-bound') === '1') {
      return;
    }
    form.setAttribute('data-wpsn-ajax-bound', '1');

    previewBtn.addEventListener('click', function (e) {
      if (!isLiveModeEnabled()) {
        return;
      }

      // Progressive enhancement: without live mode the form will submit normally.
      e.preventDefault();

      // Build FormData from the existing form (keeps groups + keep_id choices).
      var fd = new FormData(form);

      // Replace admin-post action with admin-ajax action.
      fd.set('action', 'wpsn_drift_dupe_preview');
      fd.set('nonce', WPSNDriftMonitor.nonce);

      setHtml(previewContainer, '<div class="notice notice-info"><p>' + (WPSNDriftMonitor.i18n && WPSNDriftMonitor.i18n.previewing ? WPSNDriftMonitor.i18n.previewing : 'Generating preview…') + '</p></div>');

      fetch(WPSNDriftMonitor.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        body: fd
      }).then(function (r) {
        return r.json();
      }).then(function (json) {
        if (!json || !json.success) {
          var msg = (json && json.data && json.data.message) ? json.data.message : 'Failed to generate preview.';
          setHtml(previewContainer, '<div class="notice notice-error"><p>' + String(msg) + '</p></div>');
          return;
        }
        var html = (json.data && json.data.html) ? json.data.html : '';
        setHtml(previewContainer, html);
        // Scroll into view so the user sees the preview immediately.
        try {
          previewContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } catch (err) {
          // ignore
        }
      }).catch(function (err) {
        setHtml(previewContainer, '<div class="notice notice-error"><p>' + String(err && err.message ? err.message : err) + '</p></div>');
      });
    });

    if (applyBtn) {
      applyBtn.addEventListener('click', function (e) {
        // If the inline onclick confirm returned false, default will already be prevented.
        if (e.defaultPrevented) {
          return;
        }
        if (!isLiveModeEnabled()) {
          return;
        }

        // Progressive enhancement: without live mode the form will submit normally.
        e.preventDefault();

        // Build FormData from the existing form (keeps groups + keep_id choices).
        var fd = new FormData(form);
        // Ensure server-side handler treats it as "apply".
        fd.set('wpsn_apply', '1');
        fd.delete('wpsn_preview');

        setHtml(previewContainer, '<div class="notice notice-info"><p>' + ((WPSNDriftMonitor.i18n && WPSNDriftMonitor.i18n.applying_selection) ? WPSNDriftMonitor.i18n.applying_selection : 'Applying selection…') + '</p></div>');

        ajaxPost('wpsn_drift_dupe_apply_selection', fd).then(function (json) {
          if (!json || !json.success) {
            var msg = (json && json.data && json.data.message) ? json.data.message : 'Failed to apply selection.';
            showInlineNotice(previewContainer, 'error', msg);
            return;
          }

          // Replace page sections without full reload.
          if (json.data) {
            if (json.data.summary_html) {
              var summaryEl = qs('#wpsn-drift-dupe-summary');
              if (summaryEl) {
                summaryEl.outerHTML = String(json.data.summary_html);
              }
            }
            if (json.data.items_html) {
              var itemsEl = qs('#wpsn-drift-items-table');
              if (itemsEl) {
                itemsEl.outerHTML = String(json.data.items_html);
              }
            }
            if (json.data.manager_html) {
              var mgrEl = qs('#wpsn-drift-dupe-manager');
              if (mgrEl) {
                mgrEl.outerHTML = String(json.data.manager_html);
              }
            }
          }

          // Re-bind handlers on the newly replaced markup.
          setTimeout(function () {
            initDupesAjax();
            // After applying, scroll to the updated notice/manager so the user sees the result.
            scrollToDupeNotice();
          }, 0);
        }).catch(function (err) {
          showInlineNotice(previewContainer, 'error', String(err && err.message ? err.message : err));
        });
      });
    }

    // Delegate apply/discard inside preview container.
    previewContainer.addEventListener('click', function (e) {
      var target = e.target;
      if (!target) return;

      var btn = target.closest('[data-wpsn-dupe-action]');
      if (!btn) return;

      if (!isLiveModeEnabled()) {
        return;
      }

      e.preventDefault();

      var action = btn.getAttribute('data-wpsn-dupe-action');
      var token = btn.getAttribute('data-wpsn-token') || '';

      if (action === 'apply') {
        var ok = window.confirm((WPSNDriftMonitor.i18n && WPSNDriftMonitor.i18n.apply_confirm) ? WPSNDriftMonitor.i18n.apply_confirm : 'Apply this preview now?');
        if (!ok) return;

        var fd = new FormData();
        fd.set('token', token);

        // Show a lightweight inline notice while applying.
        showInlineNotice(previewContainer, 'info', (WPSNDriftMonitor.i18n && WPSNDriftMonitor.i18n.applying_preview) ? WPSNDriftMonitor.i18n.applying_preview : 'Applying preview…');

        ajaxPost('wpsn_drift_dupe_apply_preview', fd).then(function (json) {
          if (!json || !json.success) {
            var msg = (json && json.data && json.data.message) ? json.data.message : 'Failed to apply preview.';
            showInlineNotice(previewContainer, 'error', msg);
            return;
          }

          // Replace page sections without full reload.
          if (json.data) {
            if (json.data.summary_html) {
              var summaryEl = qs('#wpsn-drift-dupe-summary');
              if (summaryEl) {
                summaryEl.outerHTML = String(json.data.summary_html);
              }
            }
            if (json.data.items_html) {
              var itemsEl = qs('#wpsn-drift-items-table');
              if (itemsEl) {
                itemsEl.outerHTML = String(json.data.items_html);
              }
            }
            if (json.data.manager_html) {
              var mgrEl = qs('#wpsn-drift-dupe-manager');
              if (mgrEl) {
                mgrEl.outerHTML = String(json.data.manager_html);
              }
            }
          }

          // Re-bind handlers on the newly replaced markup.
          setTimeout(function () {
            initDupesAjax();
            // After applying, scroll to the updated notice/manager so the user sees the result.
            scrollToDupeNotice();
          }, 0);
        }).catch(function (err) {
          showInlineNotice(previewContainer, 'error', String(err && err.message ? err.message : err));
        });
        return;
      }

      if (action === 'discard') {
        ajaxPost('wpsn_drift_dupe_discard_preview', new FormData()).then(function (json) {
          if (!json || !json.success) {
            var msg = (json && json.data && json.data.message) ? json.data.message : 'Failed to discard preview.';
            showInlineNotice(previewContainer, 'error', msg);
            return;
          }
          setHtml(previewContainer, '<div class="notice notice-info"><p>' + ((WPSNDriftMonitor.i18n && WPSNDriftMonitor.i18n.discard_ok) ? WPSNDriftMonitor.i18n.discard_ok : 'Preview discarded.') + '</p></div>');
        }).catch(function (err) {
          showInlineNotice(previewContainer, 'error', String(err && err.message ? err.message : err));
        });
      }
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initDupesAjax);
  } else {
    initDupesAjax();
  }
})();
