(function () {
  var ver = 'AWX admin.js v1.2.1';
  // [awxct-build] console.log(ver, 'loaded at', new Date().toISOString());

  // --------------- helpers ----------------
  function $(sel, ctx) { return (ctx || document).querySelector(sel); }
  function post(url, data) {
    var form = new URLSearchParams();
    Object.keys(data).forEach(function (k) { form.append(k, data[k]); });
    return fetch(url, {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      body: form.toString()
    }).then(function (r) { return r.json().catch(function(){ return { raw: r }; }); });
  }
  function ajaxURL() {
    if (window.AWXCTSettings && (AWXCTSettings.ajax || AWXCTSettings.ajaxurl)) return AWXCTSettings.ajax || AWXCTSettings.ajaxurl;
    if (window.ajaxurl) return window.ajaxurl;
    return null;
  }
  function nonce() {
    if (window.AWXCTSettings && AWXCTSettings.nonce) return AWXCTSettings.nonce;
    var n = $('#awxct_translation_nonce'); return n ? n.value : '';
  }
  function postId() {
    var a = $('#awxct_post_id'); if (a && a.value) return a.value;
    var b = $('#post_ID');    if (b && b.value) return b.value;
    return '';
  }

  // Gutenberg data access
  function hasWpData(){ return !!(window.wp && wp.data && wp.data.select && wp.data.dispatch); }
  function gbReadTitle(){
    try { return hasWpData() ? (wp.data.select('core/editor').getEditedPostAttribute('title') || '') : null; }
    catch(e){ return null; }
  }
  function gbWriteTitle(newTitle){
    try {
      if (!hasWpData()) return false;
      wp.data.dispatch('core/editor').editPost({ title: newTitle });
      return true;
    } catch(e){ return false; }
  }

  // --------------- title utils ----------------
  var SUFFIX_RE = /\s*\((Clone|[a-z]{2}(?:-[A-Za-z]{2})?)\)$/i;

  function formatLangBadge(code){
    if (!code) return '';
    var p = String(code).split('-');
    if (p.length === 1) return p[0].toLowerCase() + '-' + p[0].toUpperCase();
    return p[0].toLowerCase() + '-' + p[1].toUpperCase();
  }

  function readTitleState(){
    var gb = gbReadTitle();
    if (gb !== null) return { mode: 'gb', text: gb };

    var el = $('#title');
    if (el && typeof el.value !== 'undefined') return { mode: 'classic', el: el, text: el.value };

    el = $('.editor-post-title__input');
    if (el) return { mode: 'dom', el: el, text: el.textContent || '' };

    return { mode: 'none', el: null, text: '' };
  }

  function writeTitleReliable(newTitle){
    // 1) Try the Gutenberg store
    var storeTried = gbWriteTitle(newTitle);

    // 2) Verify and fall back if needed
    setTimeout(function(){
      var ok = false;
      try { ok = (gbReadTitle() || '') === newTitle; } catch(e){}
      if (!ok) {
        // DOM fallback (Classic + DOM)
        var h1 = $('.editor-post-title__input');
        if (h1) {
          h1.textContent = newTitle;
          h1.dispatchEvent(new Event('input', { bubbles: true }));
          h1.dispatchEvent(new Event('change', { bubbles: true }));
        }
        var classic = $('#title');
        if (classic) {
          classic.value = newTitle;
          classic.dispatchEvent(new Event('input', { bubbles: true }));
          classic.dispatchEvent(new Event('change', { bubbles: true }));
        }
      }
    }, storeTried ? 120 : 0);
  }

  function updateTitleSuffix(selectedLang, defaultLang){
    var st = readTitleState();
    if (st.mode === 'none') return;

    var base = (st.text || '').replace(SUFFIX_RE, '').trimEnd();
    var suffix = ' (Clone)';

    if (selectedLang && defaultLang &&
        selectedLang.toLowerCase() !== defaultLang.toLowerCase()) {
      suffix = ' (' + formatLangBadge(selectedLang) + ')';
    }

    var newTitle = base + suffix;
    writeTitleReliable(newTitle);
    // [awxct-build] console.log('[AWX] title →', newTitle, '(mode:', st.mode + ')');
  }

  // --------------- bootstrap ----------------
  if (!window.ajaxurl && ajaxURL()) window.ajaxurl = ajaxURL();
  var AURL = ajaxURL();
  var NONCE = nonce();
  var PID   = postId();
  var DEFAULT_LANG = ($('#awxct_default_lang') ? $('#awxct_default_lang').value : '').trim();
  // [awxct-build] console.log(ver, { AURL: AURL, NONCE: !!NONCE, PID: PID, DEFAULT_LANG: DEFAULT_LANG, wpData: hasWpData() });

  // Debug ping
  // [awxct-build] if (AURL) post(AURL, { action: 'awxct_ping' }).then(function(r){ console.log('[AWX] ping resp:', r); });

  // --------------- language change -> title + DB ---------------
  function onLangChange(lang){
    updateTitleSuffix(lang, DEFAULT_LANG);

    if (!AURL) return alert('admin-ajax URL missing');
    post(AURL, {
      action: 'awxct_update_translation_meta',
      _ajax_nonce: NONCE,
      post_id: PID,
      language: lang || ''
    }).then(function(resp){
      if (!resp || !resp.success) {
        alert('Update error: ' + (resp && resp.data && resp.data.message || 'unknown'));
      }
    }).catch(function(e){ console.error('[AWX] update fail:', e); });
  }

  document.addEventListener('change', function(ev){
    var t = ev.target;
    if (!t) return;
    if (t.id === 'awxct_translate_language' || t.name === 'awxct_translate_language') {
      onLangChange((t.value || '').trim());
    }
  }, true);

  // --------------- remove mapping ---------------
  document.addEventListener('click', function (ev) {
    var btn = ev.target && ev.target.closest('#awxct_remove_translation, .awxct-remove-translation');
    if (!btn) return;
    ev.preventDefault();

    var msg = (window.AWXCTSettings && AWXCTSettings.i18n && AWXCTSettings.i18n.confirmRemove)
      ? AWXCTSettings.i18n.confirmRemove
      : 'Really remove this entry from translations? The page itself will NOT be deleted.';

    if (!confirm(msg)) return;
    if (!AURL) return alert('admin-ajax URL missing');
    if (!PID)  return alert('post_ID missing');

    btn.disabled = true; btn.classList.add('is-busy');

    post(AURL, { action: 'awxct_remove_translation_entry', _ajax_nonce: NONCE, post_id: PID })
      .then(function (resp) {
        if (resp && resp.success) {
          alert((AWXCTSettings && AWXCTSettings.i18n && AWXCTSettings.i18n.removed) || 'Removed from translations.');
          location.reload();
        } else {
          alert((resp && resp.data && resp.data.message) || (AWXCTSettings && AWXCTSettings.i18n && AWXCTSettings.i18n.error) || 'Unknown error');
          btn.disabled = false; btn.classList.remove('is-busy');
        }
      })
      .catch(function (e) {
        console.error('[AWX] remove fail:', e);
        alert((AWXCTSettings && AWXCTSettings.i18n && AWXCTSettings.i18n.error) || 'An error has occurred.');
        btn.disabled = false; btn.classList.remove('is-busy');
      });
  }, true);

  // --------------- fix on load (if already mismatched) ---------------
  window.addEventListener('load', function(){
    var sel = $('#awxct_translate_language');
    if (!sel) return;
    var lang = (sel.value || '').trim();
    var st = readTitleState();
    if (/\(Clone\)\s*$/.test(st.text || '') && lang && DEFAULT_LANG &&
        lang.toLowerCase() !== DEFAULT_LANG.toLowerCase()) {
      updateTitleSuffix(lang, DEFAULT_LANG);
    }
  });
})();
