(function ($) {
  'use strict';

  if (typeof GT_BOGO_AUTOSAVE === 'undefined') {
    return; // Safety: only run when localized.
  }

  var screenKey = GT_BOGO_AUTOSAVE.screenKey || 'gt_bogo_engine_screen';
  var savingLabel = GT_BOGO_AUTOSAVE.savingLabel || 'Saving draft…';
  var savedLabel = GT_BOGO_AUTOSAVE.savedLabel || 'Draft saved';
  var justNowLabel = GT_BOGO_AUTOSAVE.justNow || 'Just now';

  var $forms;
  var debounceTimer = null;

  /**
   * Create hybrid toast UI (top-right, subtle, branded).
   */
  function createToast() {
    if ($('#gt-bogo-autosave-toast').length) {
      return $('#gt-bogo-autosave-toast');
    }

    // Inject minimal CSS (isolated from your admin.css)
    var css = ''
      + '#gt-bogo-autosave-toast{'
      + 'position:fixed;z-index:99999;top:24px;right:24px;'
      + 'min-width:220px;max-width:320px;padding:10px 14px 10px 12px;'
      + 'border-radius:999px;display:flex;align-items:center;'
      + 'box-shadow:0 18px 40px rgba(15,23,42,.35);'
      + 'background:linear-gradient(120deg,#020617,#111827);'
      + 'color:#e5e7eb;font-size:12px;font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;'
      + 'opacity:0;pointer-events:none;transform:translateY(-10px);'
      + 'transition:opacity .18s ease-out,transform .18s ease-out;'
      + '}'
      + '#gt-bogo-autosave-toast.gt-bogo-visible{opacity:1;pointer-events:auto;transform:translateY(0);}'
      + '#gt-bogo-autosave-toast-dot{width:9px;height:9px;border-radius:999px;margin-right:8px;'
      + 'background:radial-gradient(circle at 30% 30%,#facc15,#f97316);'
      + 'box-shadow:0 0 0 0 rgba(250,204,21,.75);'
      + 'animation:gtBogoPulse 1.1s infinite;flex-shrink:0;}'
      + '#gt-bogo-autosave-toast-dot.gt-bogo-saved{'
      + 'background:radial-gradient(circle at 30% 30%,#22c55e,#4ade80);'
      + 'box-shadow:none;animation:none;}'
      + '#gt-bogo-autosave-toast-main{display:flex;flex-direction:column;}'
      + '#gt-bogo-autosave-toast-title{font-weight:600;font-size:12px;margin-bottom:1px;}'
      + '#gt-bogo-autosave-toast-meta{font-size:11px;color:#9ca3af;}'
      + '@keyframes gtBogoPulse{0%{box-shadow:0 0 0 0 rgba(250,204,21,.70);}70%{box-shadow:0 0 0 10px rgba(250,204,21,0);}100%{box-shadow:0 0 0 0 rgba(250,204,21,0);}}';

    var $style = $('<style>', {
      id: 'gt-bogo-autosave-style',
      type: 'text/css',
      text: css
    });

    $('head').append($style);

    var $toast = $('<div>', { id: 'gt-bogo-autosave-toast' });
    var $dot = $('<div>', { id: 'gt-bogo-autosave-toast-dot' });
    var $main = $('<div>', { id: 'gt-bogo-autosave-toast-main' });
    var $title = $('<div>', { id: 'gt-bogo-autosave-toast-title' });
    var $meta = $('<div>', { id: 'gt-bogo-autosave-toast-meta' });

    $main.append($title).append($meta);
    $toast.append($dot).append($main);
    $('body').append($toast);

    return $toast;
  }

  /**
   * Show toast in a "saving" state.
   */
  function showSavingToast() {
    var $toast = createToast();
    var $dot = $('#gt-bogo-autosave-toast-dot');
    var $title = $('#gt-bogo-autosave-toast-title');
    var $meta = $('#gt-bogo-autosave-toast-meta');

    $toast.addClass('gt-bogo-visible');
    $dot.removeClass('gt-bogo-saved'); // orange pulsing
    $title.text(savingLabel);
    $meta.text(GT_BOGO_AUTOSAVE.pluginName || 'GT BOGO Engine');
  }

  /**
   * Show toast in a "saved" state.
   */
  function showSavedToast() {
    var $toast = createToast();
    var $dot = $('#gt-bogo-autosave-toast-dot');
    var $title = $('#gt-bogo-autosave-toast-title');
    var $meta = $('#gt-bogo-autosave-toast-meta');

    $toast.addClass('gt-bogo-visible');
    $dot.addClass('gt-bogo-saved'); // green solid
    $title.text(savedLabel);
    $meta.text(justNowLabel);

    // Fade out after a short delay
    setTimeout(function () {
      $toast.removeClass('gt-bogo-visible');
    }, 2100);
  }

  /**
   * Serialize all relevant inputs from GT BOGO forms into a plain object.
   */
  function collectFormData() {
    var data = {};
    $forms.each(function () {
      var serialized = $(this).serializeArray();
      serialized.forEach(function (field) {
        if (typeof data[field.name] === 'undefined') {
          data[field.name] = field.value;
        } else {
          // Handle multi-value fields (e.g. checkboxes)
          if (!Array.isArray(data[field.name])) {
            data[field.name] = [data[field.name]];
          }
          data[field.name].push(field.value);
        }
      });
    });
    return data;
  }

  /**
   * Apply form data from stored draft back into inputs.
   */
  function applyDraft(data) {
    if (!data || typeof data !== 'object') {
      return;
    }

    $forms.each(function () {
      var $form = $(this);

      Object.keys(data).forEach(function (name) {
        var value = data[name];
        var $fields = $form.find('[name="' + name.replace(/"/g, '\\"') + '"]');

        if (!$fields.length) {
          return;
        }

        if (Array.isArray(value)) {
          // Multiple values, e.g. checkboxes or multi-select
          $fields.each(function () {
            var $field = $(this);
            if ($field.is(':checkbox') || $field.is(':radio')) {
              $field.prop('checked', value.indexOf($field.val()) !== -1);
            } else {
              $field.val(value);
            }
          });
        } else {
          $fields.each(function () {
            var $field = $(this);

            if ($field.is(':checkbox') || $field.is(':radio')) {
              $field.prop('checked', $field.val() == value); // loose match is OK
            } else {
              $field.val(value);
            }
          });
        }
      });
    });
  }

  /**
   * Save to localStorage with debounce and hybrid toast UI.
   */
  function scheduleAutosave() {
    if (!window.localStorage) {
      return; // Very old browsers (rare in WP admin)
    }

    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }

    showSavingToast();

    debounceTimer = setTimeout(function () {
      var payload = {
        screenKey: screenKey,
        savedAt: new Date().toISOString(),
        data: collectFormData()
      };

      try {
        localStorage.setItem('gt_bogo_engine_autosave_' + screenKey, JSON.stringify(payload));
        showSavedToast();
      } catch (e) {
        // If storage quota exceeded or disabled, just hide the toast after a moment.
        setTimeout(function () {
          $('#gt-bogo-autosave-toast').removeClass('gt-bogo-visible');
        }, 800);
      }
    }, 900); // ~1 second pause after typing stops
  }

  /**
   * Prompt user if a draft exists and apply it automatically.
   */
  function loadDraftIfAny() {
    if (!window.localStorage) {
      return;
    }

    var raw = localStorage.getItem('gt_bogo_engine_autosave_' + screenKey);
    if (!raw) {
      return;
    }

    var payload;
    try {
      payload = JSON.parse(raw);
    } catch (e) {
      return;
    }

    if (!payload || !payload.data) {
      return;
    }

    // Simple UX: auto-apply silently, but show a subtle toast.
    applyDraft(payload.data);
    showSavedToast();
  }

  /**
   * Bind listeners to all GT BOGO admin forms.
   * We assume your admin wrapper uses .gt-bogo-engine-wrap and forms inside it.
   */
  function bindListeners() {
    var $wrap = $('.gt-bogo-engine-wrap');

    if (!$wrap.length) {
      // Fallback: try generic forms on our screen
      $forms = $('form').filter(function () {
        var action = ($(this).attr('action') || '').toString();
        return action.indexOf('gt-bogo-engine') !== -1 ||
               window.location.search.indexOf('gt-bogo-engine') !== -1;
      });
    } else {
      $forms = $wrap.find('form');
    }

    if (!$forms.length) {
      return;
    }

    // On any change/key press, schedule autosave.
    $forms.on('change input keyup', 'input, select, textarea', function (e) {
      // Ignore some noisy keys
      if (e.type === 'keyup') {
        var ignore = [16, 17, 18, 20, 27]; // shift, ctrl, alt, capslock, esc
        if (ignore.indexOf(e.which) !== -1) {
          return;
        }
      }
      scheduleAutosave();
    });
  }

  $(function () {
    // Attach listeners
    bindListeners();

    // Load any stored draft
    loadDraftIfAny();
  });

})(jQuery);
