/* WP SEO Next — Universal Metabox overlay (Divi/Beaver front-end builders)
   No dependencies. Uses WPSN Automation REST meta endpoint.
*/
(function () {
  function qs(sel, root) {
    return (root || document).querySelector(sel);
  }
  function qsa(sel, root) {
    return Array.prototype.slice.call((root || document).querySelectorAll(sel));
  }
  function escHtml(s) {
    s = (s === null || s === undefined) ? '' : String(s);
    return s
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  var cfg = window.WPSN_UMETA;
  var root = document.getElementById('wpsn-universal-metabox-root');
  if (!cfg || !root) return;

  var label = cfg.label || 'SEO';

  root.innerHTML = ''
    + '<button id="wpsn-umeta-btn" type="button">'
    + '  <span class="wpsn-umeta-btn-label">' + escHtml(label) + '</span>'
    + '  <span id="wpsn-umeta-btn-badges" class="wpsn-umeta-btn-badges"></span>'
    + '</button>'
    + '<div id="wpsn-umeta-panel" aria-hidden="true">'
    + '  <div class="wpsn-umeta-header">'
    + '    <div class="wpsn-umeta-title-wrap">'
    + '      <div class="wpsn-umeta-title">' + escHtml(label) + '</div>'
    + '      <div id="wpsn-umeta-badges" class="wpsn-umeta-badges"></div>'
    + '    </div>'
    + '    <button type="button" id="wpsn-umeta-close" class="wpsn-umeta-close" aria-label="Close">×</button>'
    + '  </div>'
    + '  <div class="wpsn-umeta-tabs">'
    + '    <button type="button" data-tab="seo" class="is-active">SEO</button>'
    + '    <button type="button" data-tab="social">Social</button>'
    + '    <button type="button" data-tab="schema">Schema</button>'
    + '  </div>'
    + '  <div class="wpsn-umeta-quicklinks" id="wpsn-umeta-quicklinks" style="display:none"></div>'
    + '  <div class="wpsn-umeta-body">'
    + '    <div class="wpsn-umeta-tab is-active" data-tab="seo">'
    + '      <div class="wpsn-umeta-field"><label>SEO title</label><input type="text" id="wpsn-umeta-title" /></div>'
    + '      <div class="wpsn-umeta-field"><label>Meta description</label><textarea id="wpsn-umeta-desc"></textarea></div>'
    + '      <div class="wpsn-umeta-field"><label>Canonical URL</label><input type="text" id="wpsn-umeta-canon" /></div>'
    + '      <div class="wpsn-umeta-field"><label>Robots index</label>'
    + '        <select id="wpsn-umeta-robots-index">'
    + '          <option value="default">Inherit defaults</option>'
    + '          <option value="index">Index</option>'
    + '          <option value="noindex">Noindex</option>'
    + '        </select>'
    + '      </div>'
    + '      <div class="wpsn-umeta-field"><label>Robots follow</label>'
    + '        <select id="wpsn-umeta-robots-follow">'
    + '          <option value="default">Inherit defaults</option>'
    + '          <option value="follow">Follow</option>'
    + '          <option value="nofollow">Nofollow</option>'
    + '        </select>'
    + '      </div>'
    + '      <div class="wpsn-umeta-preview">'
    + '        <div class="row"><strong>Resolved title:</strong> <span id="wpsn-umeta-prev-title"></span></div>'
    + '        <div class="row"><strong>Resolved description:</strong> <span id="wpsn-umeta-prev-desc"></span></div>'
    + '        <div class="row"><strong>Resolved canonical:</strong> <span id="wpsn-umeta-prev-canon"></span></div>'
    + '      </div>'
    + '    </div>'
    + '    <div class="wpsn-umeta-tab" data-tab="social">'
    + '      <div class="wpsn-umeta-field"><label>OG title</label><input type="text" id="wpsn-umeta-og-title" /></div>'
    + '      <div class="wpsn-umeta-field"><label>OG description</label><textarea id="wpsn-umeta-og-desc"></textarea></div>'
    + '      <div class="wpsn-umeta-field"><label>OG image URL</label><input type="text" id="wpsn-umeta-og-img" /></div>'
    + '      <hr style="border:0;border-top:1px solid rgba(0,0,0,.08);margin:12px 0;" />'
    + '      <div class="wpsn-umeta-field"><label>Twitter title</label><input type="text" id="wpsn-umeta-tw-title" /></div>'
    + '      <div class="wpsn-umeta-field"><label>Twitter description</label><textarea id="wpsn-umeta-tw-desc"></textarea></div>'
    + '      <div class="wpsn-umeta-field"><label>Twitter image URL</label><input type="text" id="wpsn-umeta-tw-img" /></div>'
    + '      <div class="wpsn-umeta-help">Twitter fields fall back to OpenGraph when empty (same as front-end output).</div>'
    + '    </div>'
    + '    <div class="wpsn-umeta-tab" data-tab="schema">'
    + '      <div class="wpsn-umeta-field"><label>Schema type</label>'
    + '        <select id="wpsn-umeta-schema">'
    + '          <option value="default">Default</option>'
    + '          <option value="none">None</option>'
    + '          <option value="article">Article</option>'
    + '          <option value="webpage">WebPage</option>'
    + '          <option value="product">Product</option>'
    + '        </select>'
    + '        <div class="wpsn-umeta-help">This is a simplified mapping. Advanced schema stays in JSON‑LD module.</div>'
    + '      </div>'
    + '    </div>'
    + '  </div>'
    + '  <div class="wpsn-umeta-footer">'
    + '    <div id="wpsn-umeta-status"></div>'
    + '    <button type="button" id="wpsn-umeta-refresh">Refresh</button>'
    + '    <button type="button" id="wpsn-umeta-save" class="primary">Save</button>'
    + '  </div>'
    + '</div>';

  var btn = qs('#wpsn-umeta-btn', root);
  var panel = qs('#wpsn-umeta-panel', root);
  var closeBtn = qs('#wpsn-umeta-close', root);
  var statusEl = qs('#wpsn-umeta-status', root);
  var saveBtn = qs('#wpsn-umeta-save', root);
  var refreshBtn = qs('#wpsn-umeta-refresh', root);
  var badgesEl = qs('#wpsn-umeta-badges', root);
  var btnBadgesEl = qs('#wpsn-umeta-btn-badges', root);
  var quickLinksEl = qs('#wpsn-umeta-quicklinks', root);

  function setStatus(msg) {
    statusEl.textContent = msg || '';
  }

  function renderQuickLinks() {
    if (!quickLinksEl) return;
    var links = (cfg && cfg.links) ? cfg.links : null;
    if (!links) return;

    var parts = [];
    function addLink(url, text) {
      url = url ? String(url) : '';
      if (!url) return;
      parts.push('<a href="' + escHtml(url) + '" target="_blank" rel="noopener noreferrer">' + escHtml(text) + '</a>');
    }

    addLink(links.editPost, 'Edit post');
    addLink(links.aiDrafts, 'AI drafts');
    addLink(links.internalLinksIncoming, 'Internal links (incoming)');
    addLink(links.internalLinksOutgoing, 'Internal links (outgoing)');
    addLink(links.audit, 'Audit');

    if (parts.length) {
      quickLinksEl.style.display = 'flex';
      quickLinksEl.innerHTML = parts.join('');
    } else {
      quickLinksEl.style.display = 'none';
      quickLinksEl.innerHTML = '';
    }
  }

  function renderBadges(data) {
    if (!badgesEl) return;

    var r = (data && data.resolved) ? data.resolved : {};
    var robots = (r && r.robots) ? r.robots : {};

    var d = (data && data.drafts) ? data.drafts : {};
    var hasDrafts = false;

    var issueBadges = [];
    function isTrue(v) {
      return v === true || v === 1 || v === '1' || v === 'true';
    }

    if (d && isTrue(d.has_drafts)) {
      hasDrafts = true;
    }

    if (robots && isTrue(robots.noindex)) {
      issueBadges.push({ cls: 'bad', text: 'NOINDEX' });
    }

    if (robots && isTrue(robots.nofollow)) {
      issueBadges.push({ cls: 'warn', text: 'NOFOLLOW' });
    }

    if (!r.og_image) {
      issueBadges.push({ cls: 'warn', text: 'Missing OG image' });
    }

    // Keep it minimal, but still helpful.
    if (!r.title) {
      issueBadges.push({ cls: 'warn', text: 'Missing title' });
    }

    var badges = issueBadges.slice();
    if (hasDrafts) {
      badges.push({ cls: 'info', text: 'Has drafts' });
    }

    var hasAny = badges.length > 0;
    btn.classList.toggle('wpsn-has-issues', hasAny);
    btn.classList.toggle('wpsn-has-drafts', hasDrafts);

    // Button badges: keep it compact.
    if (btnBadgesEl) {
      var btnBadges = [];

      function toBtnText(b) {
        if (!b || !b.text) return '';
        if (b.text === 'Missing OG image') return 'OG IMG';
        if (b.text === 'Missing title') return 'NO TITLE';
        return b.text;
      }

      if (issueBadges.length) {
        var top = issueBadges[0];
        btnBadges.push({ cls: top.cls, text: toBtnText(top) });
      }
      if (hasDrafts) {
        var draftsUrl = (cfg && cfg.links && cfg.links.aiDrafts) ? String(cfg.links.aiDrafts) : '';
        btnBadges.push({ cls: 'info', text: 'DRAFTS', action: 'drafts', url: draftsUrl });
      }

      btnBadgesEl.innerHTML = btnBadges.map(function (b) {
        var cls = 'wpsn-btn-badge ' + escHtml(b.cls);
        var attrs = '';
        if (b && b.action) {
          cls += ' is-clickable';
          attrs += ' data-action="' + escHtml(b.action) + '"';
          if (b.url) {
            attrs += ' data-url="' + escHtml(String(b.url)) + '"';
          }
          if (b.action === 'drafts') {
            attrs += ' title="Open AI drafts for this post"';
          }
        }
        return '<span class="' + cls + '"' + attrs + '>' + escHtml(b.text) + '</span>';
      }).join('');
    }

    if (!hasAny) {
      badgesEl.innerHTML = '<span class="wpsn-badge ok">OK</span>';
      return;
    }

    badgesEl.innerHTML = badges.map(function (b) {
      return '<span class="wpsn-badge ' + escHtml(b.cls) + '">' + escHtml(b.text) + '</span>';
    }).join('');
  }

  // Make the DRAFTS badge clickable (open Bulk drafts for this post) without opening the panel.
  if (btnBadgesEl) {
    btnBadgesEl.addEventListener('click', function (e) {
      var t = e && e.target ? e.target : null;
      if (!t || !t.getAttribute) return;
      var action = t.getAttribute('data-action');
      if (action !== 'drafts') return;

      var url = t.getAttribute('data-url') || (cfg && cfg.links && cfg.links.aiDrafts ? String(cfg.links.aiDrafts) : '');
      if (!url) return;

      if (e.preventDefault) e.preventDefault();
      if (e.stopPropagation) e.stopPropagation();

      try {
        window.open(url, '_blank', 'noopener');
      } catch (err) {
        // Fallback: navigate in the same tab.
        window.location.href = url;
      }
    });
  }

  function openPanel() {
    panel.classList.add('is-open');
    panel.setAttribute('aria-hidden', 'false');
    btn.style.display = 'none';
  }
  function closePanel() {
    panel.classList.remove('is-open');
    panel.setAttribute('aria-hidden', 'true');
    btn.style.display = '';
  }

  btn.addEventListener('click', function () {
    openPanel();
  });
  closeBtn.addEventListener('click', function () {
    closePanel();
  });

  document.addEventListener('keydown', function (e) {
    if (e && e.key === 'Escape' && panel.classList.contains('is-open')) {
      closePanel();
    }
  });

  // Tabs.
  qsa('.wpsn-umeta-tabs button', root).forEach(function (tb) {
    tb.addEventListener('click', function () {
      var tab = tb.getAttribute('data-tab');
      qsa('.wpsn-umeta-tabs button', root).forEach(function (b) { b.classList.remove('is-active'); });
      qsa('.wpsn-umeta-tab', root).forEach(function (t) { t.classList.remove('is-active'); });
      tb.classList.add('is-active');
      var tabEl = qs('.wpsn-umeta-tab[data-tab="' + tab + '"]', root);
      if (tabEl) tabEl.classList.add('is-active');
    });
  });

  function getVal(id) {
    var el = qs(id, root);
    return el ? (el.value || '') : '';
  }
  function setVal(id, value) {
    var el = qs(id, root);
    if (!el) return;
    el.value = (value === null || value === undefined) ? '' : String(value);
  }
  function setText(id, value) {
    var el = qs(id, root);
    if (!el) return;
    el.textContent = (value === null || value === undefined) ? '' : String(value);
  }

  function populate(data) {
    data = data || {};
    var o = data.overrides || {};
    var r = data.resolved || {};

    setVal('#wpsn-umeta-title', o.title || '');
    setVal('#wpsn-umeta-desc', o.description || '');
    setVal('#wpsn-umeta-canon', o.canonical || '');

    var ri = o.robots_index || '';
    var rf = o.robots_follow || '';
    setVal('#wpsn-umeta-robots-index', ri ? ri : 'default');
    setVal('#wpsn-umeta-robots-follow', rf ? rf : 'default');

    setVal('#wpsn-umeta-og-title', o.og_title || '');
    setVal('#wpsn-umeta-og-desc', o.og_description || '');
    setVal('#wpsn-umeta-og-img', o.og_image || '');

    setVal('#wpsn-umeta-tw-title', o.twitter_title || '');
    setVal('#wpsn-umeta-tw-desc', o.twitter_description || '');
    setVal('#wpsn-umeta-tw-img', o.twitter_image || '');

    var st = o.schema_type || '';
    setVal('#wpsn-umeta-schema', st ? st : 'default');

    // Resolved preview.
    setText('#wpsn-umeta-prev-title', r.title || '');
    setText('#wpsn-umeta-prev-desc', r.description || '');
    setText('#wpsn-umeta-prev-canon', r.canonical || '');

    renderBadges(data);
  }

  function apiFetch(method, body) {
    var opts = {
      method: method,
      credentials: 'same-origin',
      headers: {
        'X-WP-Nonce': cfg.nonce,
        'Accept': 'application/json'
      }
    };
    if (body !== undefined) {
      opts.headers['Content-Type'] = 'application/json';
      opts.body = JSON.stringify(body);
    }

    return fetch(cfg.restUrl, opts).then(function (res) {
      return res.json().then(function (json) {
        if (!res.ok) {
          var err = new Error('Request failed');
          err.data = json;
          throw err;
        }
        return json;
      });
    });
  }

  function loadMeta() {
    setStatus('Loading…');
    return apiFetch('GET').then(function (data) {
      populate(data);
      setStatus('');
      return data;
    }).catch(function (err) {
      console.error('[WPSN UMETA] load error', err);
      var msg = (err && err.data && err.data.message) ? err.data.message : 'Failed to load';
      setStatus(msg);
    });
  }

  function collectPayload() {
    var title = getVal('#wpsn-umeta-title').trim();
    var desc = getVal('#wpsn-umeta-desc').trim();
    var canon = getVal('#wpsn-umeta-canon').trim();

    var robotsIndex = getVal('#wpsn-umeta-robots-index');
    var robotsFollow = getVal('#wpsn-umeta-robots-follow');
    if (robotsIndex === 'default') robotsIndex = '';
    if (robotsFollow === 'default') robotsFollow = '';

    var ogTitle = getVal('#wpsn-umeta-og-title').trim();
    var ogDesc = getVal('#wpsn-umeta-og-desc').trim();
    var ogImg = getVal('#wpsn-umeta-og-img').trim();

    var twTitle = getVal('#wpsn-umeta-tw-title').trim();
    var twDesc = getVal('#wpsn-umeta-tw-desc').trim();
    var twImg = getVal('#wpsn-umeta-tw-img').trim();

    var schema = getVal('#wpsn-umeta-schema');
    if (schema === 'default') schema = '';

    return {
      overrides: {
        title: title,
        description: desc,
        canonical: canon,
        robots_index: robotsIndex,
        robots_follow: robotsFollow,
        og_title: ogTitle,
        og_description: ogDesc,
        og_image: ogImg,
        twitter_title: twTitle,
        twitter_description: twDesc,
        twitter_image: twImg,
        schema_type: schema
      }
    };
  }

  function saveMeta() {
    saveBtn.disabled = true;
    setStatus('Saving…');

    return apiFetch('PATCH', collectPayload()).then(function (data) {
      populate(data);
      setStatus('Saved');
      setTimeout(function () { setStatus(''); }, 1200);
    }).catch(function (err) {
      console.error('[WPSN UMETA] save error', err);
      var msg = (err && err.data && err.data.message) ? err.data.message : 'Save failed';
      setStatus(msg);
    }).finally(function () {
      saveBtn.disabled = false;
    });
  }

  refreshBtn.addEventListener('click', function () {
    loadMeta();
  });

  saveBtn.addEventListener('click', function () {
    saveMeta();
  });

  // Initial load.
  renderQuickLinks();
  loadMeta();
})();
