/* 后台交互 */
(function () {
  var mt = document.querySelector('.menu-toggle');
  if (mt) mt.addEventListener('click', function () {
    var s = document.querySelector('.admin-side'); if (s) s.classList.toggle('open');
  });

  // 分系统（CRM/PSI）侧栏抽屉
  var mt2 = document.querySelector('.subsys .menu-toggle');
  if (mt2) mt2.addEventListener('click', function () {
    document.body.classList.toggle('nav-open');
  });

  function val(k) { var el = document.getElementById('f_' + k); return el ? el.value : ''; }
  function updatePreview() {
    var pb = document.getElementById('themePreview'); if (!pb) return;
    pb.style.background = 'linear-gradient(135deg,' + val('primary') + ',' + val('secondary') + ')';
    pb.style.color = '#fff';
    pb.querySelector('.pv-title').textContent = '降温服 · 风格预览';
    pb.querySelector('.pv-sub').textContent = '主色 ' + val('primary') + ' / 辅色 ' + val('secondary');
  }

  var presetSel = document.getElementById('preset');
  var presets = window.__presets__ || null;
  if (presetSel && presets) {
    presetSel.addEventListener('change', function () {
      var p = presets[this.value]; if (!p) return;
      ['primary', 'primary_600', 'secondary', 'accent', 'bg', 'surface', 'text', 'muted', 'border', 'nav_bg']
        .forEach(function (k) {
          var el = document.getElementById('f_' + k);
          if (el && p.vars[k] != null) el.value = p.vars[k];
        });
      updatePreview();
    });
  }
  ['primary', 'secondary', 'accent', 'bg', 'surface', 'text', 'muted', 'border', 'nav_bg']
    .forEach(function (k) {
      var el = document.getElementById('f_' + k);
      if (el) el.addEventListener('input', updatePreview);
    });
  updatePreview();

  // 确认删除
  document.querySelectorAll('form.del-form').forEach(function (f) {
    f.addEventListener('submit', function (e) {
      if (!confirm('确定要删除吗？此操作不可恢复。')) e.preventDefault();
    });
  });
})();

// 通用删除/操作确认：用 data-confirm 属性替代内联 onclick/onsubmit 确认，
// 以配合严格 CSP（script-src 已移除 'unsafe-inline'）。
document.addEventListener('submit', function (e) {
  var el = e.target;
  if (el && el.hasAttribute('data-confirm') && !window.confirm(el.getAttribute('data-confirm'))) {
    e.preventDefault();
  }
});
document.addEventListener('click', function (e) {
  var el = e.target && e.target.closest ? e.target.closest('[data-confirm]') : null;
  if (el && !window.confirm(el.getAttribute('data-confirm'))) {
    e.preventDefault();
    e.stopPropagation();
  }
});
