(function(){
  'use strict';

  function escapeHtml(s){
    return (''+s)
      .replace(/&/g,'&amp;')
      .replace(/</g,'&lt;')
      .replace(/>/g,'&gt;')
      .replace(/"/g,'&quot;')
      .replace(/'/g,'&#039;');
  }

  function escapeRegExp(s){
    return (''+s).replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
  }

  function cssEscape(s){
    if(window.CSS && typeof window.CSS.escape === 'function'){
      return window.CSS.escape(s);
    }
    return (''+s).replace(/[^a-zA-Z0-9_-]/g, function(ch){
      return '\\' + ch;
    });
  }

  function buildCssPath(el){
    if(!el || el === document || el === document.documentElement){
      return '';
    }
    if(el.id){
      return '#' + cssEscape(el.id);
    }
    var path = [];
    var cur = el;
    while(cur && cur.nodeType === 1 && cur !== document.body){
      if(cur.id){
        path.unshift('#' + cssEscape(cur.id));
        break;
      }
      var tag = (cur.tagName || '').toLowerCase();
      if(!tag){break;}
      var idx = 1;
      var sib = cur;
      while((sib = sib.previousElementSibling)){
        if((sib.tagName || '').toLowerCase() === tag){ idx++; }
      }
      path.unshift(tag + ':nth-of-type(' + idx + ')');
      cur = cur.parentElement;
    }
    return path.join(' > ');
  }

  function getContentElement(){
    try{
      var savedSel = localStorage.getItem('wpsnInspectorContentSel');
      if(savedSel){
        var el = document.querySelector(savedSel);
        if(el){ return el; }
      }
    }catch(e){}

    var selectors = [
      '.wp-block-post-content',
      '.entry-content',
      '.entry',
      '.post-content',
      '.content-area',
      'article',
      'main',
      '#content',
      '#primary',
      '.site-content'
    ];
    for(var i=0;i<selectors.length;i++){
      var cand = document.querySelector(selectors[i]);
      var txt = cand ? (cand.innerText || cand.textContent || '') : '';
      if(cand && txt.trim().length > 80){
        return cand;
      }
    }
    return document.body;
  }

  function getText(el){
    if(!el){return '';}
    var t = el.innerText || el.textContent || '';
    return (''+t).replace(/\s+/g,' ').trim();
  }

  function countOcc(text, needle){
    if(!needle){return 0;}
    var n = (''+needle).trim();
    if(!n){return 0;}

    // Prefer unicode properties if available; avoid lookbehind for Safari/older.
    try{
      var re = new RegExp('(^|[^\\p{L}\\p{N}_])' + escapeRegExp(n) + '(?=[^\\p{L}\\p{N}_]|$)', 'giu');
      var c = 0;
      var m;
      while((m = re.exec(text)) !== null){
        c++;
        if(m.index === re.lastIndex){ re.lastIndex++; }
      }
      return c;
    }catch(e){
      var re2 = new RegExp('\\b' + escapeRegExp(n) + '\\b', 'gi');
      var m2 = text.match(re2);
      return m2 ? m2.length : 0;
    }
  }

  function makeSnippets(text, keyword, maxSnippets){
    maxSnippets = maxSnippets || 1;
    if(!keyword){return [];}
    var t = text;
    var k = (''+keyword).trim();
    if(!k){return [];}
    var lower = t.toLowerCase();
    var kl = k.toLowerCase();
    var out = [];
    var from = 0;
    while(out.length < maxSnippets){
      var idx = lower.indexOf(kl, from);
      if(idx === -1){break;}
      var start = Math.max(0, idx - 60);
      var end = Math.min(t.length, idx + k.length + 60);
      var snippet = t.slice(start, end);
      var re = new RegExp(escapeRegExp(k), 'ig');
      var html = escapeHtml(snippet).replace(re, function(m){
        return '<mark class="wpsn-inspector__mark">' + escapeHtml(m) + '</mark>';
      });
      if(start > 0){ html = '… ' + html; }
      if(end < t.length){ html = html + ' …'; }
      out.push(html);
      from = idx + k.length;
    }
    return out;
  }

  function init(){
    var root = document.getElementById('wpsn-inspector');
    if(!root){
      return false;
    }
    if(root.__wpsnInspectorInit){
      return true;
    }
    root.__wpsnInspectorInit = true;

    function isOpen(){return root.getAttribute('data-open') === '1';}
    function setOpen(v){
      root.setAttribute('data-open', v ? '1' : '0');
      try{ localStorage.setItem('wpsnInspectorOpen', v ? '1' : '0'); }catch(e){}
    }

    // Restore open state.
    try{
      if(!isOpen()){
        var saved = localStorage.getItem('wpsnInspectorOpen');
        if(saved === '1'){ setOpen(true); }
      }
    }catch(e){}

    var toggle = root.querySelector('.wpsn-inspector__toggle');
    var closeBtn = root.querySelector('.wpsn-inspector__close');

    var keywordsBox = root.querySelector('.wpsn-inspector__keywords');
    var keywordsData = [];
    try{
      var json = root.getAttribute('data-keywords') || '[]';
      keywordsData = JSON.parse(json);
      if(!Array.isArray(keywordsData)){ keywordsData = []; }
    }catch(e){ keywordsData = []; }

    var seoTitle = root.getAttribute('data-seo-title') || '';
    var seoDesc  = root.getAttribute('data-seo-desc') || '';

    // Keep keyword counts in sync with current input values (when editing in the panel).
    var titleInput = root.querySelector('input[name="fields[_wpsn_seo_title]"]');
    var descInput  = root.querySelector('textarea[name="fields[_wpsn_meta_description]"]');
    function syncSeoFromInputs(){
      if(titleInput) seoTitle = titleInput.value || '';
      if(descInput) seoDesc = descInput.value || '';
    }
    if(titleInput){
      titleInput.addEventListener('input', function(){
        syncSeoFromInputs();
        try{ renderKeywords(); }catch(e0){}
      });
    }
    if(descInput){
      descInput.addEventListener('input', function(){
        syncSeoFromInputs();
        try{ renderKeywords(); }catch(e1){}
      });
    }

    function renderKeywords(){
      if(!keywordsBox){ return; }
      var targetEl = getContentElement();
      var text = getText(targetEl);
      var words = text ? text.split(/\s+/).filter(Boolean).length : 0;

      var rows = [];
      for(var i=0;i<keywordsData.length;i++){
        var item = keywordsData[i] || {};
        var kw = (item.k || item.keyword || '').toString().trim();
        if(!kw){ continue; }
        var src = (item.srcLabel || item.sourceLabel || item.src || item.source || '').toString();
        var inPage = countOcc(text, kw);
        var inTitle = countOcc(seoTitle, kw);
        var inDesc = countOcc(seoDesc, kw);
        var density = (words > 0) ? ((inPage / words) * 100) : 0;
        var snippets = (inPage > 0) ? makeSnippets(text, kw, 1) : [];
        rows.push({kw:kw, src:src, inPage:inPage, inTitle:inTitle, inDesc:inDesc, density:density, snippet:(snippets[0]||'')});
      }

      rows.sort(function(a,b){
        if(a.inPage === 0 && b.inPage > 0){ return -1; }
        if(b.inPage === 0 && a.inPage > 0){ return 1; }
        return (b.inPage - a.inPage);
      });

      var html = '';
      html += '<div class="wpsn-inspector__muted">Analyzed: <strong>' + escapeHtml((targetEl===document.body)?'whole page':(targetEl.tagName||'content')) + '</strong> · words: ' + words + '</div>';

      if(rows.length === 0){
        html += '<div class="wpsn-inspector__muted">No keywords found (set Focus keyword or add taxonomies/tags).</div>';
        keywordsBox.innerHTML = html;
        return;
      }

      html += '<table class="wpsn-inspector__table">';
      html += '<thead><tr><th>Keyword</th><th>Page</th><th>Title</th><th>Desc</th><th>Density</th><th>Source</th></tr></thead><tbody>';
      for(var r=0;r<rows.length;r++){
        var row = rows[r];
        var cls = row.inPage === 0 ? ' class="is-missing"' : '';
        html += '<tr'+cls+'>';
        html += '<td><strong>' + escapeHtml(row.kw) + '</strong>';
        if(row.snippet){ html += '<div class="wpsn-inspector__snippet">' + row.snippet + '</div>'; }
        html += '</td>';
        html += '<td>' + row.inPage + '</td>';
        html += '<td>' + row.inTitle + '</td>';
        html += '<td>' + row.inDesc + '</td>';
        html += '<td>' + (row.density ? row.density.toFixed(2) + '%' : '0%') + '</td>';
        html += '<td>' + escapeHtml(row.src || '') + '</td>';
        html += '</tr>';
      }
      html += '</tbody></table>';

      keywordsBox.innerHTML = html;
    }

    function togglePanel(){
      setOpen(!isOpen());
      if(toggle){ toggle.setAttribute('aria-expanded', isOpen() ? 'true' : 'false'); }
      if(isOpen()){
        try{ renderKeywords(); }catch(e){}
      }
    }

    if(toggle){
      toggle.addEventListener('click', function(){ togglePanel(); });
    }
    if(closeBtn){
      closeBtn.addEventListener('click', function(){ setOpen(false); if(toggle){toggle.setAttribute('aria-expanded','false');} });
    }

    // Fill inputs with computed values.
    var fillBtn = root.querySelector('.wpsn-inspector__fill');
    if(fillBtn){
      fillBtn.addEventListener('click', function(){
        var fields = root.querySelectorAll('[data-computed]');
        for(var i2=0;i2<fields.length;i2++){
          var el2 = fields[i2];
          var c = el2.getAttribute('data-computed') || '';
          var tag = (el2.tagName||'').toUpperCase();
          if(tag === 'TEXTAREA' || tag === 'INPUT'){
            el2.value = c;
          }
        }
      });
    }

    // Clear overrides.
    var clearBtn = root.querySelector('.wpsn-inspector__clear');
    if(clearBtn){
      clearBtn.addEventListener('click', function(){
        var inputs = root.querySelectorAll('input[type="text"], textarea');
        for(var i3=0;i3<inputs.length;i3++){
          inputs[i3].value = '';
        }
        var selects = root.querySelectorAll('select');
        for(var i4=0;i4<selects.length;i4++){
          selects[i4].selectedIndex = 0;
        }
      });
    }

    // AI generate (non-AJAX): reuse the same form and switch the admin-post action.
    var aiBtns = root.querySelectorAll('.wpsn-inspector__ai_gen');
    if(aiBtns && aiBtns.length){
      for(var b=0;b<aiBtns.length;b++){
        (function(btn){
          btn.addEventListener('click', function(){
            var form = root.querySelector('form.wpsn-inspector__form');
            if(!form) return;

            // Scope
            var scope = (btn.getAttribute('data-scope') || 'all').toString();
            var scopeInput = form.querySelector('input.wpsn-inspector__ai_scope');
            if(scopeInput){ scopeInput.value = scope; }

            // Keywords hint
            var hintInput = form.querySelector('input.wpsn-inspector__keywords_hint');
            if(hintInput){
              try{
                var kd = JSON.parse(root.getAttribute('data-keywords') || '[]');
                var parts = [];
                kd.forEach(function(x){ if(x && x.k) parts.push(String(x.k)); });
                hintInput.value = parts.slice(0, 12).join(', ');
              }catch(e){}
            }

            // Page text (plain) from selected content area.
            var ta = form.querySelector('textarea.wpsn-inspector__page_text');
            var contentEl = getContentElement();
            if(ta){
              var txt = getText(contentEl);
              if(txt && txt.length > 12000) txt = txt.slice(0, 12000);
              ta.value = txt || '';
            }

            // H1 text (for duplicate checks)
            var h1Input = form.querySelector('input.wpsn-inspector__h1_text');
            if(h1Input){
              var h1El = null;
              try{
                h1El = (contentEl && contentEl.querySelector) ? contentEl.querySelector('h1') : null;
              }catch(e2){}
              if(!h1El){
                try{ h1El = document.querySelector('h1'); }catch(e3){}
              }
              h1Input.value = h1El ? getText(h1El) : '';
            }

            var actionInput = form.querySelector('input[name="action"]');
            if(actionInput) actionInput.value = 'wpsn_frontend_seo_ai_fill';
            form.submit();
          });
        })(aiBtns[b]);
      }
    }

    var discardBtn = root.querySelector('.wpsn-inspector__ai_discard');
    if(discardBtn){
      discardBtn.addEventListener('click', function(){
        var form = root.querySelector('form.wpsn-inspector__form');
        if(!form) return;
        var actionInput = form.querySelector('input[name="action"]');
        if(actionInput) actionInput.value = 'wpsn_frontend_seo_ai_discard';
        form.submit();
      });
    }

    // Apply AI suggestion per field (no AJAX). Works for input/textarea/select.
    root.addEventListener('click', function(ev){
      var btn = ev.target && ev.target.closest ? ev.target.closest('.wpsn-inspector__ai-apply') : null;
      if(!btn){ return; }
      ev.preventDefault();
      var suggestion = (btn.getAttribute('data-suggestion') || '').toString();
      var field = btn.closest ? btn.closest('.wpsn-inspector__field') : null;
      if(!field){ return; }
      var control = field.querySelector('input[type="text"], textarea, select');
      if(!control){ return; }
      control.value = suggestion;
      try{ control.dispatchEvent(new Event('input', {bubbles:true})); }catch(e1){}
      try{ control.dispatchEvent(new Event('change', {bubbles:true})); }catch(e2){}

      // Update highlight and hint.
      field.classList.remove('wpsn-inspector__field--ai-suggested');
      field.classList.add('wpsn-inspector__field--ai-applied');
      var hint = btn.closest ? btn.closest('.wpsn-inspector__ai-hint') : null;
      if(hint){
        hint.textContent = 'AI applied.';
      }
    });

    // Admin bar shortcut (if present)
    document.addEventListener('click', function(e){
      var t = e.target;
      if(!t){return;}
      var li = t.closest ? t.closest('li.wpsn-frontend-inspector-link') : null;
      if(!li){return;}
      e.preventDefault();
      setOpen(true);
      try{ root.scrollIntoView({behavior:'smooth', block:'end'}); }catch(err){}
      try{ renderKeywords(); }catch(e2){}
    });

    // Manual analyze button.
    var analyzeBtn = root.querySelector('.wpsn-inspector__analyze');
    if(analyzeBtn){
      analyzeBtn.addEventListener('click', function(){
        renderKeywords();
      });
    }

    // Pick content area.
    var pickBtn = root.querySelector('.wpsn-inspector__pick');
    var resetBtn = root.querySelector('.wpsn-inspector__pick_reset');
    if(pickBtn){
      pickBtn.addEventListener('click', function(){
        pickBtn.disabled = true;
        var prevText = pickBtn.textContent;
        pickBtn.textContent = 'Click an area…';

        var handler = function(ev){
          try{
            // Avoid selecting the inspector itself.
            if(ev.target && ev.target.closest && ev.target.closest('#wpsn-inspector')){
              return;
            }
            ev.preventDefault();
            ev.stopPropagation();
            var target = ev.target;
            if(!target){return;}
            var cand = target.closest ? target.closest('article, main, .entry-content, .wp-block-post-content, section, div') : target;
            var sel = buildCssPath(cand);
            if(sel){
              try{ localStorage.setItem('wpsnInspectorContentSel', sel); }catch(e3){}
            }
          }finally{
            document.removeEventListener('click', handler, true);
            pickBtn.disabled = false;
            pickBtn.textContent = prevText;
            renderKeywords();
          }
        };

        document.addEventListener('click', handler, true);
      });
    }
    if(resetBtn){
      resetBtn.addEventListener('click', function(){
        try{ localStorage.removeItem('wpsnInspectorContentSel'); }catch(e4){}
        renderKeywords();
      });
    }

    // If already open (via ?wpsn_inspector=1), render once.
    if(isOpen()){
      try{ renderKeywords(); }catch(e5){}
    }

    // Auto-run AI generation (one-click actions from admin tools).
    // Example:
    //   ?wpsn_inspector=1&wpsn_ai_gen=snippet&wpsn_ai_mode=auto&wpsn_ai_lang=en&wpsn_ai_tone=professional&wpsn_ai_only_empty=1
    try{
      var params = new URLSearchParams(window.location.search || '');
      var autoScope = (params.get('wpsn_ai_gen') || '').toString();
      if(autoScope){
        var allowed = {all:1,snippet:1,title:1,description:1,keywords:1};
        if(allowed[autoScope]){
          // Ensure panel is open.
          setOpen(true);
          if(toggle){ toggle.setAttribute('aria-expanded', 'true'); }

          // Apply optional defaults.
          var form0 = root.querySelector('form.wpsn-inspector__form');
          if(form0){
            var mode = (params.get('wpsn_ai_mode') || '').toString();
            var lang = (params.get('wpsn_ai_lang') || '').toString();
            var tone = (params.get('wpsn_ai_tone') || '').toString();
            var onlyEmpty = (params.get('wpsn_ai_only_empty') || '').toString();

            var selMode = form0.querySelector('select[name="ai_mode"]');
            if(selMode && mode){ selMode.value = mode; }
            var selLang = form0.querySelector('select[name="ai_language"]');
            if(selLang && lang){ selLang.value = lang; }
            var selTone = form0.querySelector('select[name="ai_tone"]');
            if(selTone && tone){ selTone.value = tone; }
            var chk = form0.querySelector('input[type="checkbox"][name="ai_only_empty"]');
            if(chk && (onlyEmpty === '0' || onlyEmpty === '1')){ chk.checked = (onlyEmpty === '1'); }
          }

          // Clean URL to avoid repeated triggers.
          try{
            var u = new URL(window.location.href);
            ['wpsn_ai_gen','wpsn_ai_mode','wpsn_ai_lang','wpsn_ai_tone','wpsn_ai_only_empty'].forEach(function(k){
              try{ u.searchParams.delete(k); }catch(e0){}
            });
            if(!u.searchParams.get('wpsn_inspector')){
              u.searchParams.set('wpsn_inspector', '1');
            }
            history.replaceState({}, '', u.toString());
          }catch(e1){}

          // Trigger the correct AI button.
          setTimeout(function(){
            var btnSel = '.wpsn-inspector__ai_gen[data-scope="' + cssEscape(autoScope) + '"]';
            var btn0 = root.querySelector(btnSel);
            if(!btn0 && autoScope === 'snippet'){
              btn0 = root.querySelector('.wpsn-inspector__ai_gen[data-scope="all"]');
            }
            if(btn0 && typeof btn0.click === 'function'){
              btn0.click();
            }
          }, 50);
        }
      }
    }catch(e6){}

    return true;
  }

  // Init now; if markup is printed AFTER scripts in footer, init again on DOMContentLoaded.
  if(!init()){
    if(document.readyState === 'loading'){
      document.addEventListener('DOMContentLoaded', function(){ init(); }, {once:true});
    }else{
      setTimeout(function(){ init(); }, 0);
    }
  }

})();
