// =============================================
// SHARK CRM - Kanban Pipeline Drag & Drop
// =============================================

let dragCard = null;

function initPipeline() {
  const cards = document.querySelectorAll('.kanban-card');
  const cols  = document.querySelectorAll('.kanban-cards');

  cards.forEach(card => {
    card.setAttribute('draggable', 'true');
    card.addEventListener('dragstart', onDragStart);
    card.addEventListener('dragend', onDragEnd);
  });

  cols.forEach(col => {
    col.addEventListener('dragover', onDragOver);
    col.addEventListener('dragleave', onDragLeave);
    col.addEventListener('drop', onDrop);
  });
}

function onDragStart(e) {
  dragCard = this;
  this.classList.add('dragging');
  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/plain', this.dataset.id);
}

function onDragEnd(e) {
  this.classList.remove('dragging');
  document.querySelectorAll('.kanban-cards').forEach(c => c.classList.remove('drag-over'));
  dragCard = null;
}

function onDragOver(e) {
  e.preventDefault();
  e.dataTransfer.dropEffect = 'move';
  this.classList.add('drag-over');
}

function onDragLeave(e) {
  this.classList.remove('drag-over');
}

async function onDrop(e) {
  e.preventDefault();
  this.classList.remove('drag-over');
  if (!dragCard) return;

  const leadId  = dragCard.dataset.id;
  const stageId = this.dataset.stage;
  const oldCol  = dragCard.parentNode;

  // Move card in DOM
  this.appendChild(dragCard);

  // Update column counts
  updateColCount(oldCol);
  updateColCount(this);

  // Persist to server
  const fd = new FormData();
  fd.append('action', 'move_stage');
  fd.append('lead_id', leadId);
  fd.append('stage_id', stageId);

  const res = await fetch('handlers/leads.php', { method: 'POST', body: fd });
  const data = await res.json();

  if (data.success) {
    showToast('Stage updated', 'success');
    // Update the stage pill if visible
    const pill = dragCard.querySelector('.kanban-stage-pill');
    if (pill && data.stage_name) pill.textContent = data.stage_name;
  } else {
    showToast('Failed to update stage', 'error');
    // Revert
    oldCol.appendChild(dragCard);
    updateColCount(oldCol);
    updateColCount(this);
  }
}

function updateColCount(col) {
  const colEl = col.closest('.kanban-col');
  if (!colEl) return;
  const count = col.querySelectorAll('.kanban-card').length;
  const countEl = colEl.querySelector('.kanban-col-count');
  if (countEl) countEl.textContent = count;
}

document.addEventListener('DOMContentLoaded', initPipeline);
