'use strict';

// ── Toast Notification ────────────────────────────────────────
function showToast(msg, type) {
  type = type || 'success';
  var tc = document.getElementById('toast-container');
  if (!tc) {
    tc = document.createElement('div');
    tc.id = 'toast-container';
    tc.style.cssText = 'position:fixed;top:16px;right:16px;z-index:9000;display:flex;flex-direction:column;gap:8px;';
    document.body.appendChild(tc);
  }
  var toast = document.createElement('div');
  var bg = type === 'success' ? '#14532d' : '#7f1d1d';
  var border = type === 'success' ? '#16a34a' : '#dc2626';
  toast.style.cssText = 'background:' + bg + ';border:1px solid ' + border + ';color:#fff;font-size:13px;padding:10px 16px;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.4);display:flex;align-items:center;gap:8px;';
  toast.innerHTML = '<span>' + (type === 'success' ? '✓' : '✕') + '</span><span>' + msg + '</span>';
  tc.appendChild(toast);
  setTimeout(function() { toast.remove(); }, 3500);
}

// ── Confirm helper ────────────────────────────────────────────
function confirmAction(msg, callback) {
  if (confirm(msg)) callback();
}

// ── Clipboard Copy ────────────────────────────────────────────
document.querySelectorAll('[data-copy]').forEach(function(btn) {
  btn.addEventListener('click', function() {
    navigator.clipboard.writeText(btn.dataset.copy).then(function() {
      showToast('Copied to clipboard!');
    });
  });
});

// ── Auto-submit selects ───────────────────────────────────────
document.querySelectorAll('.auto-submit').forEach(function(el) {
  el.addEventListener('change', function() { el.closest('form').submit(); });
});

// ── Image preview on file input ───────────────────────────────
document.querySelectorAll('input[type="file"][data-preview]').forEach(function(input) {
  input.addEventListener('change', function() {
    var preview = document.getElementById(input.dataset.preview);
    if (!preview || !input.files[0]) return;
    var reader = new FileReader();
    reader.onload = function(e) {
      preview.src = e.target.result;
      preview.style.display = 'block';
    };
    reader.readAsDataURL(input.files[0]);
  });
});

// ── Mobile sidebar toggle ─────────────────────────────────────
var sidebarToggle = document.getElementById('sidebar-toggle');
var adminSidebar  = document.getElementById('admin-sidebar');
if (sidebarToggle && adminSidebar) {
  sidebarToggle.addEventListener('click', function() {
    adminSidebar.classList.toggle('open');
  });
}
