/* Admin dashboard interactions: editor tabs + live SEO preview. */
document.querySelectorAll('.ed-tab').forEach(function (t) {
  t.addEventListener('click', function () {
    var tab = t.dataset.tab;
    document.querySelectorAll('.ed-tab').forEach(function (x) { x.classList.toggle('on', x === t); });
    document.querySelectorAll('.ed-panel').forEach(function (x) { x.classList.toggle('on', x.dataset.panel === tab); });
  });
});

function seoUpdate() {
  var T = (document.getElementById('seoTitle') || {}).value || '';
  var D = (document.getElementById('seoDesc') || {}).value || '';
  var K = ((document.getElementById('seoKw') || {}).value || '').toLowerCase();
  var pt = document.getElementById('pvTitle'), pd = document.getElementById('pvDesc');
  if (pt) pt.textContent = T || 'Untitled page';
  if (pd) pd.textContent = D || 'No meta description set yet…';
  var ct = document.getElementById('ctTitle');
  if (ct) { ct.textContent = T.length + '/60'; ct.className = 'counter' + (T.length > 60 ? ' bad' : T.length > 55 ? ' warn' : ''); }
  var cd = document.getElementById('ctDesc');
  if (cd) { cd.textContent = D.length + '/160'; cd.className = 'counter' + (D.length > 160 ? ' bad' : D.length > 150 ? ' warn' : ''); }
  var checks = [
    ['Title length ideal (30–60)', T.length >= 30 && T.length <= 60],
    ['Description length ideal (120–160)', D.length >= 120 && D.length <= 160],
    ['Focus keyword in title', !!K && T.toLowerCase().indexOf(K) >= 0],
    ['Focus keyword in description', !!K && D.toLowerCase().indexOf(K) >= 0],
    ['Has a meta description', D.length > 0]
  ];
  var pass = checks.filter(function (c) { return c[1]; }).length;
  var pct = Math.round(pass / checks.length * 100);
  var cc = document.getElementById('seoChecks');
  if (cc) cc.innerHTML = checks.map(function (c) {
    return '<div class="check ' + (c[1] ? 'pass' : 'fail') + '"><span class="ci">' +
      (c[1] ? '<svg class="ic ic-sm" viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>'
            : '<svg class="ic ic-sm" viewBox="0 0 24 24"><path d="M12 8v4M12 16h.01"/></svg>') +
      '</span><span>' + c[0] + '</span></div>';
  }).join('');
  var b = document.getElementById('seoPct');
  if (b) { b.textContent = pct + '%'; b.className = 'badge ' + (pct >= 80 ? 'b-ok' : pct >= 50 ? 'b-warn' : 'b-bad'); }
}
window.seoUpdate = seoUpdate;
if (document.getElementById('seoTitle')) seoUpdate();
