/* ============================================================
   Content Automation Engine — App JavaScript
   ============================================================ */

document.addEventListener('DOMContentLoaded', () => {

  // ── Sidebar Toggle ──────────────────────────────────────────
  const sidebarToggle = document.getElementById('sidebar-toggle');
  const sidebar       = document.getElementById('sidebar');

  if (sidebarToggle && sidebar) {
    sidebarToggle.addEventListener('click', () => {
      if (window.innerWidth <= 768) {
        sidebar.classList.toggle('mobile-open');
      } else {
        sidebar.classList.toggle('collapsed');
        localStorage.setItem('cae_sidebar_collapsed', sidebar.classList.contains('collapsed'));
      }
    });

    // Restore sidebar state
    if (window.innerWidth > 768 && localStorage.getItem('cae_sidebar_collapsed') === 'true') {
      sidebar.classList.add('collapsed');
    }
  }

  // ── Delete Confirmations ────────────────────────────────────
  document.querySelectorAll('.confirm-delete').forEach(form => {
    form.addEventListener('submit', e => {
      e.preventDefault();
      Swal.fire({
        title: 'Are you sure?',
        text: 'This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Yes, delete it',
        cancelButtonText: 'Cancel',
      }).then(result => {
        if (result.isConfirmed) form.submit();
      });
    });
  });

  // ── Auto-dismiss Flash Messages ─────────────────────────────
  const flashes = document.querySelectorAll('.alert-dismissible');
  flashes.forEach(el => {
    setTimeout(() => {
      const bsAlert = bootstrap.Alert.getOrCreateInstance(el);
      if (bsAlert) bsAlert.close();
    }, 5000);
  });

  // ── DataTables Default Init ─────────────────────────────────
  if (typeof $ !== 'undefined' && $.fn.DataTable) {
    document.querySelectorAll('table.dt-init').forEach(table => {
      $(table).DataTable({ pageLength: 25, order: [] });
    });
  }

  // ── Toast Notification Helper ───────────────────────────────
  window.showToast = function(message, type = 'success') {
    const wrapper = document.createElement('div');
    wrapper.style.cssText = 'position:fixed;top:80px;right:20px;z-index:9999;min-width:280px;';
    wrapper.innerHTML = `
      <div class="toast show align-items-center text-white bg-${type === 'error' ? 'danger' : type} border-0 shadow-lg" role="alert">
        <div class="d-flex">
          <div class="toast-body fw-medium">${message}</div>
          <button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.closest('.toast').remove()"></button>
        </div>
      </div>`;
    document.body.appendChild(wrapper);
    setTimeout(() => wrapper.remove(), 4000);
  };

  // ── Generate Content: AJAX mode ─────────────────────────────
  const generateForm = document.getElementById('generate-form-ajax');
  if (generateForm) {
    generateForm.addEventListener('submit', e => {
      e.preventDefault();
      const topicIds = [...document.querySelectorAll('.topic-check:checked')].map(c => parseInt(c.value));
      if (!topicIds.length) {
        showToast('Select at least one topic', 'warning');
        return;
      }

      const btn    = document.getElementById('generate-btn');
      const origHtml = btn.innerHTML;
      btn.disabled = true;
      btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Generating…';

      fetch(BASE_URL + '/api/content/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ topic_ids: topicIds }),
      })
      .then(r => r.json())
      .then(data => {
        if (data.success) {
          const results = data.data || {};
          const ok  = Object.values(results).filter(r => r.success).length;
          const fail= Object.values(results).filter(r => !r.success).length;
          showToast(`${ok} generated${fail ? ', ' + fail + ' failed' : ''}`, ok > 0 ? 'success' : 'danger');
          setTimeout(() => location.reload(), 1500);
        } else {
          showToast(data.message || 'Generation failed', 'danger');
          btn.disabled = false;
          btn.innerHTML = origHtml;
        }
      })
      .catch(err => {
        showToast('Network error: ' + err.message, 'danger');
        btn.disabled = false;
        btn.innerHTML = origHtml;
      });
    });
  }

  // ── Expose BASE_URL globally ────────────────────────────────
  if (typeof window.BASE_URL === 'undefined') {
    const base = document.querySelector('meta[name="base-url"]');
    window.BASE_URL = base ? base.content : '';
  }

});
