(function ($) {
  if (window.__afbGlobalFieldMapInitDone) return;
  window.__afbGlobalFieldMapInitDone = true;

  function asDigits(value) {
    return String(value || '').replace(/\D+/g, '');
  }

  function fillSelect($el, rows, selected, placeholder) {
    const safeRows = Array.isArray(rows) ? rows : [];
    const current = asDigits(selected || '');
    $el.empty();
    $el.append($('<option>').val('').text(placeholder || 'Select...'));

    let found = false;
    safeRows.forEach((row) => {
      const gid = asDigits(row && row.gid ? row.gid : '');
      if (!gid) return;
      const label = String((row && row.name ? row.name : gid) + ' • ' + gid);
      const $opt = $('<option>').val(gid).text(label);
      if (gid === current) {
        $opt.prop('selected', true);
        found = true;
      }
      $el.append($opt);
    });

    if (current && !found) {
      $el.append($('<option>').val(current).text('Saved value • ' + current).prop('selected', true));
    }
  }

  function setNotice($status, type, message) {
    const cls = type === 'error' ? 'notice notice-error' : 'notice notice-success';
    $status.html('<div class="' + cls + '"><p>' + String(message || '') + '</p></div>');
  }

  $(function () {
    if (typeof afbGlobalFieldMapCfg === 'undefined' || !afbGlobalFieldMapCfg || !afbGlobalFieldMapCfg.ajaxUrl) {
      return;
    }

    const cfg = afbGlobalFieldMapCfg;
    const initial = window.afbGlobalFieldMapInitial || {};

    let state = {
      pat_id: parseInt(initial.pat_id || cfg.patId || 0, 10) || 0,
      workspace_gid: asDigits(initial.workspace_gid || ''),
      target: String(initial.target || 'workspace') === 'portfolio' ? 'portfolio' : 'workspace',
      portfolio_gid: asDigits(initial.portfolio_gid || ''),
    };

    const $workspace = $('#afb-gf-workspace');
    const $target = $('#afb-gf-target');
    const $portfolio = $('#afb-gf-portfolio');
    const $portfolioRow = $('#afb-gf-portfolio-row');
    const $save = $('#afb-gf-save');
    const $status = $('#afb-gf-status');
    const $note = $('#afb-gf-fields-note');
    let contextRequest = null;
    let contextRequestToken = 0;
    let contextLoading = false;
    let saveLoading = false;

    function hasCompleteScope() {
      if (!state.workspace_gid) return false;
      if (state.target === 'portfolio' && !state.portfolio_gid) return false;
      return true;
    }

    function syncSaveDisabled() {
      $save.prop('disabled', contextLoading || saveLoading || !hasCompleteScope());
    }

    function updateUrl() {
      const params = new URLSearchParams(window.location.search);
      params.set('page', 'afb-global-field-map-edit');
      params.set('pat_id', String(state.pat_id || ''));
      params.set('workspace_gid', String(state.workspace_gid || ''));
      params.set('target', state.target);
      if (state.target === 'portfolio' && state.portfolio_gid) {
        params.set('portfolio_gid', String(state.portfolio_gid));
      } else {
        params.delete('portfolio_gid');
      }
      const next = window.location.pathname + '?' + params.toString();
      window.history.replaceState({}, '', next);
    }

    function pickerValue(selectId) {
      return asDigits($(selectId).val());
    }

    function fillPicker(selectId, rows, selected) {
      fillSelect($(selectId), rows, selected, 'Select detected field (optional)');
    }

    function renderContext(data) {
      const selected = data.selected || {};
      const workspaces = Array.isArray(data.workspaces) ? data.workspaces : [];
      const portfolios = Array.isArray(data.portfolios) ? data.portfolios : [];
      const fields = Array.isArray(data.fields) ? data.fields : [];
      const identity = data.existing_identity || {};
      const gateway = data.existing_gateway || {};
      const debug = data.debug || {};
      const debugNotes = Array.isArray(debug.notes) ? debug.notes.filter(Boolean) : [];

      state.workspace_gid = asDigits(selected.workspace_gid || state.workspace_gid);
      state.target = String(selected.target || state.target) === 'portfolio' ? 'portfolio' : 'workspace';
      state.portfolio_gid = asDigits(selected.portfolio_gid || state.portfolio_gid);

      fillSelect($workspace, workspaces, state.workspace_gid, 'Select workspace');
      $target.val(state.target);

      if (state.target === 'portfolio') {
        $portfolioRow.show();
        fillSelect($portfolio, portfolios, state.portfolio_gid, 'Select portfolio');
      } else {
        $portfolioRow.hide();
        $portfolio.empty();
      }

      fillPicker('#afb-gf-first-select', fields, identity.first_name || '');
      fillPicker('#afb-gf-last-select', fields, identity.last_name || '');
      fillPicker('#afb-gf-email-select', fields, identity.email || '');

      fillPicker('#afb-gf-create-select', fields, gateway.create || '');
      fillPicker('#afb-gf-link-select', fields, gateway.link || '');
      fillPicker('#afb-gf-pin-select', fields, gateway.pin || '');

      if (!fields.length) {
        let msg = 'No text fields discovered for this selection.';
        if (debugNotes.length) {
          msg += ' Diagnostics: ' + debugNotes.join(' | ');
        }
        $note.text(msg);
      } else {
        let msg = 'Discovered ' + fields.length + ' text custom fields for this selection.';
        if (debugNotes.length) {
          msg += ' Diagnostics: ' + debugNotes.join(' | ');
        }
        $note.text(msg);
      }

      updateUrl();
      syncSaveDisabled();
    }

    function loadContext(options) {
      const opts = options || {};
      const requestToken = ++contextRequestToken;

      contextLoading = true;
      syncSaveDisabled();
      if (opts.clearStatus !== false) {
        $status.empty();
      }

      if (contextRequest && typeof contextRequest.abort === 'function' && contextRequest.readyState !== 4) {
        contextRequest.abort();
      }

      contextRequest = $.post(cfg.ajaxUrl, {
        action: 'afb_gf_editor_context',
        nonce: cfg.nonce,
        pat_id: state.pat_id,
        workspace_gid: state.workspace_gid,
        target: state.target,
        portfolio_gid: state.portfolio_gid,
      })
      .done(function (resp) {
        if (requestToken !== contextRequestToken) return;

        if (!resp || !resp.success) {
          setNotice($status, 'error', (resp && resp.data && resp.data.message) ? resp.data.message : 'Failed to load mapping context.');
          return;
        }
        renderContext(resp.data || {});
      })
      .fail(function (_xhr, textStatus) {
        if (requestToken !== contextRequestToken || textStatus === 'abort') return;
        setNotice($status, 'error', 'Failed to load mapping context.');
      })
      .always(function () {
        if (requestToken !== contextRequestToken) return;
        contextLoading = false;
        contextRequest = null;
        syncSaveDisabled();
      });
    }

    $workspace.on('change', function () {
      state.workspace_gid = asDigits($(this).val());
      if (state.target !== 'portfolio') state.portfolio_gid = '';
      loadContext();
    });

    $target.on('change', function () {
      state.target = String($(this).val()) === 'portfolio' ? 'portfolio' : 'workspace';
      if (state.target !== 'portfolio') state.portfolio_gid = '';
      loadContext();
    });

    $portfolio.on('change', function () {
      state.portfolio_gid = asDigits($(this).val());
      loadContext();
    });

    $save.on('click', function (e) {
      e.preventDefault();

      if (saveLoading) return;

      if (!hasCompleteScope()) {
        setNotice($status, 'error', state.target === 'portfolio' ? 'Select a workspace and portfolio before saving.' : 'Select a workspace before saving.');
        return;
      }

      saveLoading = true;
      syncSaveDisabled();
      $status.empty();

      const payload = {
        action: 'afb_gf_editor_save',
        nonce: cfg.nonce,
        pat_id: state.pat_id,
        workspace_gid: state.workspace_gid,
        target: state.target,
        portfolio_gid: state.target === 'portfolio' ? state.portfolio_gid : '',
        first_name_gid: pickerValue('#afb-gf-first-select'),
        last_name_gid: pickerValue('#afb-gf-last-select'),
        email_gid: pickerValue('#afb-gf-email-select'),
        gateway_create_gid: pickerValue('#afb-gf-create-select'),
        gateway_link_gid: pickerValue('#afb-gf-link-select'),
        gateway_pin_gid: pickerValue('#afb-gf-pin-select'),
      };

      $.post(cfg.ajaxUrl, payload)
        .done(function (resp) {
          if (!resp || !resp.success) {
            setNotice($status, 'error', (resp && resp.data && resp.data.message) ? resp.data.message : 'Save failed.');
            return;
          }
          setNotice($status, 'success', (resp.data && resp.data.message) ? resp.data.message : 'Mapping saved.');
          loadContext({ clearStatus: false });
        })
        .fail(function () {
          setNotice($status, 'error', 'Save failed.');
        })
        .always(function () {
          saveLoading = false;
          syncSaveDisabled();
        });
    });

    syncSaveDisabled();
    loadContext();
  });
})(jQuery);
