<?php
// views/pages/crm.php
require_once __DIR__ . '/../../app/config.php';
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/auth_middleware.php';
require_once __DIR__ . '/components/tutorial.php';

require_auth_or_redirect();
?>
<style>
/* ===== RESET E VARIÁVEIS ===== */
* {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
}

input, textarea {
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

:root {
  --primary: #6366f1;
  --primary-hover: #4f46e5;
  --primary-light: #818cf8;
  --success: #10b981;
  --success-light: #34d399;
  --danger: #ef4444;
  --danger-light: #f87171;
  --warning: #f59e0b;
  --followup: #1D163C;
  --followup-hover: #7c3aed;
  --followup-bg: #f5f3ff;
  --followup-border: #ddd6fe;
  
  --border: #e5e7eb;
  --border-light: #f3f4f6;
  --card-bg: #ffffff;
  --card-hover: #fafafa;
  
  --gray-50: #f9fafb;
  --gray-100: #f3f4f6;
  --gray-200: #e5e7eb;
  --gray-300: #d1d5db;
  --gray-400: #9ca3af;
  --gray-500: #6b7280;
  --gray-600: #4b5563;
  --gray-700: #374151;
  --gray-800: #1f2937;
  --gray-900: #111827;
  
  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  --shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);
  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
  --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
  --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
}

.dark {
  --primary: #818cf8;
  --primary-hover: #6366f1;
  --primary-light: #a5b4fc;
  --success: #34d399;
  --success-light: #6ee7b7;
  --danger: #f87171;
  --danger-light: #fca5a5;
  --warning: #fbbf24;
  --followup: #a78bfa;
  --followup-hover: #8b5cf6;
  --followup-bg: #312e81;
  --followup-border: #4c1d95;
  
  --border: #374151;
  --border-light: #4b5563;
  --card-bg: #1f2937;
  --card-hover: #374151;
  
  --gray-50: #111827;
  --gray-100: #1f2937;
  --gray-200: #374151;
  --gray-300: #4b5563;
  --gray-400: #6b7280;
  --gray-500: #9ca3af;
  --gray-600: #d1d5db;
  --gray-700: #e5e7eb;
  --gray-800: #f3f4f6;
  --gray-900: #f9fafb;
}

body {
  background: var(--gray-50);
  overflow-x: hidden;
}

/* ===== CONTAINER PRINCIPAL ===== */
.crm-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 24px;
  background: var(--gray-50);
}

/* ===== HEADER ===== */
.crm-header {
  background: var(--card-bg);
  border: 1px solid var(--border);
  border-radius: 16px;
  padding: 24px 28px;
  margin-bottom: 24px;
  box-shadow: var(--shadow-sm);
}

.crm-header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
}

.crm-title-section {
  flex: 1;
}

.crm-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--gray-900);
  margin: 0 0 6px 0;
  letter-spacing: -0.02em;
}

.crm-subtitle {
  font-size: 14px;
  color: var(--gray-500);
  margin: 0;
  font-weight: 500;
}

/* ===== BOARD WRAPPER ===== */
.board-wrapper {
  background: var(--card-bg);
  border: 1px solid var(--border);
  border-radius: 16px;
  padding: 20px;
  box-shadow: var(--shadow-sm);
}

.board-scroll {
  overflow-x: auto;
  overflow-y: visible;
  padding-bottom: 16px;
  margin: -4px;
  padding: 4px;
}

.board-scroll::-webkit-scrollbar {
  height: 10px;
}

.board-scroll::-webkit-scrollbar-track {
  background: var(--gray-100);
  border-radius: 8px;
}

.board-scroll::-webkit-scrollbar-thumb {
  background: var(--gray-400);
  border-radius: 8px;
  border: 2px solid var(--gray-100);
}

.board-scroll::-webkit-scrollbar-thumb:hover {
  background: var(--gray-500);
}

#board {
  display: flex;
  gap: 20px;
  min-height: 70vh;
  padding: 4px;
}

/* ===== COLUNAS KANBAN ===== */
.kan-col {
  display: flex;
  flex-direction: column;
  width: 340px;
  min-width: 340px;
  max-height: 75vh;
  flex-shrink: 0;
  background: var(--gray-50);
  border: 2px solid var(--border-light);
  border-radius: 12px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.kan-col::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: var(--gray-300);
  opacity: 0;
  transition: opacity 0.2s;
}

.kan-col:hover {
  border-color: var(--gray-300);
  box-shadow: var(--shadow-md);
}

.kan-col:hover::before {
  opacity: 1;
}

/* Coluna com follow-up */
.kan-col.has-followup {
  background: linear-gradient(to bottom, var(--followup-bg) 0%, var(--gray-50) 120px);
  border-color: var(--followup-border);
}

.kan-col.has-followup::before {
  background: linear-gradient(90deg, var(--followup), var(--primary));
  opacity: 1;
}

.kan-col.has-followup .kan-header {
  background: transparent;
}

.kan-col.has-followup:hover {
  border-color: var(--followup);
  box-shadow: 0 8px 16px rgba(139, 92, 246, 0.15);
}

/* ===== HEADER DA COLUNA ===== */
.kan-header {
  padding: 18px 16px;
  background: var(--card-bg);
  border-bottom: 1px solid var(--border-light);
  position: relative;
}

.kan-header-top {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 14px;
}

.handle {
  cursor: grab;
  color: var(--gray-400);
  font-size: 18px;
  padding: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  border-radius: 6px;
}

.handle:hover {
  color: var(--gray-600);
  background: var(--gray-100);
}

.handle:active {
  cursor: grabbing;
  color: var(--primary);
}

.kan-col-title {
  flex: 1;
  background: transparent;
  border: none;
  font-size: 15px;
  font-weight: 700;
  color: var(--gray-900);
  padding: 6px 8px;
  border-radius: 6px;
  transition: all 0.2s;
  letter-spacing: -0.01em;
}

.kan-col-title:hover {
  background: var(--gray-100);
}

.kan-col-title:focus {
  outline: none;
  background: var(--card-bg);
  box-shadow: 0 0 0 2px var(--primary-light);
}

.kan-header-badges {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
}

/* ===== BADGES ===== */
.badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 0.02em;
  transition: all 0.2s;
}

.badge-count {
  background: var(--gray-200);
  color: var(--gray-700);
  min-width: 32px;
}

.has-followup .badge-count {
  background: rgba(255, 255, 255, 0.9);
  color: var(--followup);
}

.followup-badge {
  display: none;
  background: var(--followup);
  color: white;
  padding: 4px 8px;
  animation: pulse-followup 2s ease-in-out infinite;
}

.has-followup .followup-badge {
  display: inline-flex;
}

@keyframes pulse-followup {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.85;
    transform: scale(0.98);
  }
}

/* ===== CONTROLS ===== */
.kan-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 12px;
}

.kan-search {
  flex: 1;
  padding: 9px 12px 9px 36px;
  border: 1.5px solid var(--border);
  border-radius: 8px;
  background: var(--card-bg);
  font-size: 13px;
  color: var(--gray-700);
  transition: all 0.2s;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%239ca3af'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z'/%3E%3C/svg%3E");
  background-size: 18px;
  background-repeat: no-repeat;
  background-position: 10px center;
}

.kan-search::placeholder {
  color: var(--gray-400);
}

.kan-search:focus {
  outline: none;
  border-color: var(--primary);
  background-color: var(--card-bg);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.08);
}

/* ===== BOTÕES DE AÇÃO ===== */
.btn-icon-action {
  padding: 8px;
  border-radius: 8px;
  border: 1.5px solid var(--border);
  background: var(--card-bg);
  color: var(--gray-600);
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.btn-icon-action:hover {
  background: var(--gray-100);
  border-color: var(--gray-300);
  color: var(--gray-900);
  transform: translateY(-1px);
}

.btn-icon-action:active {
  transform: translateY(0);
}

.btn-icon-action.btn-followup-trigger {
  border-color: var(--followup-border);
  color: var(--followup);
}

.btn-icon-action.btn-followup-trigger:hover {
  background: var(--followup);
  border-color: var(--followup);
  color: white;
}

.btn-icon-action.btn-delete-stage {
  border-color: rgba(239, 68, 68, 0.2);
  color: var(--danger);
}

.btn-icon-action.btn-delete-stage:hover {
  background: var(--danger);
  border-color: var(--danger);
  color: white;
}

/* ===== LISTA DE CARDS ===== */
.kan-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 14px 12px;
  min-height: 200px;
  position: relative;
}

.kan-list::-webkit-scrollbar {
  width: 6px;
}

.kan-list::-webkit-scrollbar-track {
  background: transparent;
}

.kan-list::-webkit-scrollbar-thumb {
  background: var(--gray-300);
  border-radius: 4px;
}

.kan-list::-webkit-scrollbar-thumb:hover {
  background: var(--gray-400);
}

.empty-state {
  text-align: center;
  padding: 48px 20px;
  color: var(--gray-400);
}

.empty-state-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.5;
}

.empty-state-text {
  font-size: 13px;
  font-weight: 500;
}

/* ===== CARDS ===== */
.kan-card {
  background: var(--card-bg);
  border: 1.5px solid var(--border);
  border-radius: 10px;
  padding: 14px 16px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: var(--shadow-sm);
  position: relative;
}

.kan-card::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: var(--primary);
  opacity: 0;
  transition: opacity 0.2s;
  border-radius: 10px 0 0 10px;
}

.kan-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
  border-color: var(--primary-light);
  background: var(--card-hover);
}

.kan-card:hover::before {
  opacity: 1;
}

.kan-card:active {
  transform: translateY(0);
  box-shadow: var(--shadow);
}

.kan-card.dragging {
  opacity: 0.6;
  cursor: grabbing;
  transform: rotate(2deg);
  box-shadow: var(--shadow-lg);
}

.kan-card-company {
  font-size: 14px;
  font-weight: 700;
  color: var(--gray-900);
  margin-bottom: 6px;
  letter-spacing: -0.01em;
  line-height: 1.3;
}

.kan-card-phone {
  font-size: 13px;
  color: var(--gray-500);
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
}

.kan-card-phone::before {
  content: '📱';
  font-size: 14px;
}

/* ===== BOTÕES ===== */
.btn {
  padding: 11px 20px;
  border-radius: 10px;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  border: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  letter-spacing: 0.01em;
}

.btn-primary {
  background: var(--primary);
  color: white;
  box-shadow: 0 1px 3px rgba(99, 102, 241, 0.3);
}

.btn-primary:hover {
  background: var(--primary-hover);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);
}

.btn-primary:active {
  transform: translateY(0);
}

.btn-icon {
  padding: 8px 14px;
  border-radius: 8px;
  border: 1.5px solid var(--border);
  background: var(--card-bg);
  color: var(--gray-700);
  font-weight: 600;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-icon:hover {
  background: var(--gray-100);
  border-color: var(--gray-300);
  transform: translateY(-1px);
}

.btn-followup {
  padding: 8px 14px;
  border-radius: 8px;
  background: var(--followup-bg);
  color: var(--followup);
  border: 1.5px solid var(--followup-border);
  font-size: 13px;
  font-weight: 600;
}

.btn-followup:hover {
  background: var(--followup);
  color: white;
  border-color: var(--followup);
}

.btn-danger {
  padding: 8px 14px;
  border-radius: 8px;
  background: rgba(239, 68, 68, 0.08);
  color: var(--danger);
  border: 1.5px solid rgba(239, 68, 68, 0.3);
  font-size: 13px;
  font-weight: 600;
}

.btn-danger:hover {
  background: var(--danger);
  color: white;
  border-color: var(--danger);
}

/* ===== MODAL ===== */
.modal {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: none;
  align-items: center;
  justify-content: center;
}

.modal.active {
  display: flex;
}

.modal-overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(8px);
  animation: fadeIn 0.2s ease-out;
}

.modal-content {
  position: relative;
  z-index: 1001;
  max-width: 640px;
  width: 92%;
  max-height: 90vh;
  overflow-y: auto;
  background: var(--card-bg);
  border-radius: 16px;
  box-shadow: var(--shadow-xl);
  animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 24px 28px;
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--gray-50);
}

.modal-header h3 {
  font-size: 20px;
  font-weight: 700;
  color: var(--gray-900);
  margin: 0;
  letter-spacing: -0.01em;
}

.modal-body {
  padding: 28px;
}

.modal-footer {
  padding: 20px 28px;
  border-top: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--gray-50);
}

/* ===== FORMULÁRIO ===== */
.form-group {
  margin-bottom: 22px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 700;
  margin-bottom: 8px;
  color: var(--gray-900);
  letter-spacing: -0.01em;
}

.form-input, .form-select, .form-textarea {
  width: 100%;
  padding: 11px 14px;
  border: 1.5px solid var(--border);
  border-radius: 8px;
  background: var(--card-bg);
  font-size: 14px;
  color: var(--gray-900);
  transition: all 0.2s;
  font-family: inherit;
}

.form-input::placeholder,
.form-textarea::placeholder {
  color: var(--gray-400);
}

.form-input:focus, .form-select:focus, .form-textarea:focus {
  outline: none;
  border-color: var(--primary);
  background: var(--card-bg);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.08);
}

.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: var(--gray-500);
  font-weight: 500;
}

.form-media-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
  flex-wrap: wrap;
}

.form-media-preview {
  padding: 16px;
  border: 1.5px dashed var(--border);
  border-radius: 8px;
  background: var(--gray-50);
  margin-bottom: 14px;
  min-height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-media-preview img {
  max-height: 160px;
  border-radius: 8px;
  border: 1px solid var(--border);
  box-shadow: var(--shadow-sm);
}

/* ===== UTILITÁRIOS ===== */
.hidden { display: none !important; }
.flex { display: flex; }
.items-center { align-items: center; }
.justify-between { justify-content: space-between; }
.gap-2 { gap: 8px; }
.gap-3 { gap: 12px; }
.gap-4 { gap: 16px; }
.mb-1 { margin-bottom: 4px; }
.mb-2 { margin-bottom: 8px; }
.mb-3 { margin-bottom: 12px; }
.mb-4 { margin-bottom: 16px; }
.mt-2 { margin-top: 8px; }
.p-4 { padding: 16px; }
.text-sm { font-size: 14px; }
.text-xs { font-size: 12px; }
.font-semibold { font-weight: 600; }
.font-bold { font-weight: 700; }

.kan-sentinel {
  height: 1px !important;
  opacity: 0 !important;
  pointer-events: none !important;
  margin: 0 !important;
  padding: 0 !important;
}

.grid { display: grid; }
.grid-cols-2 { grid-template-columns: repeat(2, 1fr); }

/* ===== LOADING ===== */
.loading-indicator {
  text-align: center;
  padding: 24px;
  color: var(--gray-500);
  font-size: 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--gray-200);
  border-top-color: var(--primary);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}



/* ===== TAG FOLLOW-UP ATIVO ===== */
/* ===== TAG FOLLOW-UP ATIVO ===== */
.followup-active-tag {
  position: absolute;
  top: 12px;
  left: 12px;
  background: var(--followup);
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 9px;
  font-weight: 700;
  letter-spacing: 0.3px;
  text-transform: uppercase;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  z-index: 10;
  box-shadow: 0 1px 3px rgba(139, 92, 246, 0.3);
}

.followup-tag-icon {
  font-size: 10px;
}

.followup-tag-text {
  font-size: 9px;
  line-height: 1;
}

/* Ajuste no header da coluna com follow-up */
.kan-col.has-followup .kan-header {
  padding-top: 40px;
}

.kan-col.has-followup {
  background: linear-gradient(to bottom, var(--followup-bg) 0%, var(--gray-50) 120px);
  border-color: var(--followup-border);
  position: relative;
}


/* ===== AVISO BETA CRM ===== */
.crm-beta-alert {
  margin-top: 10px;
  padding: 8px 12px;
  border-radius: 10px;
  background: var(--followup-bg);
  border: 1px solid var(--followup-border);
  color: var(--followup);
  font-size: 12px;
  font-weight: 500;
  display: inline-flex;
  align-items: flex-start;
  gap: 8px;
  max-width: 420px;
}

.crm-beta-alert-badge {
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  padding: 4px 8px;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.9);
}

.crm-beta-alert-text {
  margin: 0;
  line-height: 1.4;
}










@keyframes float {
  0%, 100% {
    transform: translateX(-50%) translateY(0px);
  }
  50% {
    transform: translateX(-50%) translateY(-3px);
  }
}

@keyframes sparkle {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.2);
  }
}

/* Ajuste para dar espaço à tag */
.kan-col.has-followup {
  margin-top: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* ===== RESPONSIVO ===== */
@media (max-width: 768px) {
  .crm-container {
    padding: 16px;
  }
  
  .crm-header {
    padding: 20px;
  }
  
  .crm-header-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .kan-col {
    width: 300px;
    min-width: 300px;
  }
  
  .modal-content {
    width: 96%;
    max-height: 94vh;
  }
}
</style>

<?= tutorial_component([
  'id' => 'crm',
  'title' => 'Como usar o CRM',
  'button' => 'Ver tutorial de CRM',
  'video' => 'https://youtu.be/H2fgn112d_0',
  'spotlight' => true
]); ?>

<div class="crm-container">
  <!-- Header -->
  <div class="crm-header">
    <div class="crm-header-content">
      <div class="crm-title-section">
        <h1 class="crm-title">CRM - Follow Up</h1>
        <p class="crm-subtitle">Gerencie seus leads e automatize follow-ups inteligentes</p>
        
        
        
        
        
        
      <div class="crm-beta-alert">
        <div class="crm-beta-alert-badge">Beta</div>
        <p class="crm-beta-alert-text">
Este módulo de CRM está em <strong>versão Beta</strong>. 
Você pode usar normalmente, estamos finalizando melhorias e ajustes para deixar tudo ainda melhor para sua experiência. 🚀

        </p>
      </div>
    </div>
      <button id="btnAddStage" class="btn btn-primary">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
        </svg>
        Nova Coluna
      </button>
    </div>
  </div>

  <!-- Board -->
  <div class="board-wrapper">
    <div class="board-scroll">
      <div id="board"></div>
    </div>
  </div>
</div>

<!-- Modal Follow-up -->
<div id="followupModal" class="modal">
  <div class="modal-overlay"></div>
  <div class="modal-content">
    <div class="modal-header">
      <h3>⚙️ Configurar Follow-up Automático</h3>
      <button id="fuClose" class="btn-icon">✕</button>
    </div>
    
    <form id="fuForm" class="modal-body">
      <input type="hidden" id="fuStageId">
      
      <div class="form-group">
        <label class="form-label">Tipo de mensagem</label>
        <select id="fuMessageType" name="message_type" class="form-select">
          <option value="text">📝 Texto</option>
          <option value="image">🖼️ Imagem</option>
          <option value="video">🎥 Vídeo</option>
              <option value="audio">🎵 Áudio</option>

        </select>
      </div>

      <div class="form-group">
        <label class="form-label">Mensagem / Legenda</label>
        <textarea id="fuMessageText" name="message_text" class="form-textarea" rows="4" placeholder="Digite a mensagem que será enviada..."></textarea>
      </div>

      <div id="fuMediaSection" class="form-group hidden">
        <label class="form-label">Arquivo de mídia</label>
        
        <div class="form-media-actions">
          <button type="button" id="fuBtnUpload" class="btn-icon">
            📤 Upload
          </button>
          <button type="button" id="fuBtnPaste" class="btn-icon">
            📋 Colar URL
          </button>
          <button type="button" id="fuBtnOpen" class="btn-icon" disabled>
            🔗 Abrir
          </button>
          <button type="button" id="fuBtnClear" class="btn-icon" disabled>
            🗑️ Remover
          </button>
        </div>

        <input type="hidden" id="fuMediaUrl" name="media_url">

        <div id="fuMediaPreview" class="form-media-preview">
          <div class="text-xs text-gray-500">Nenhum arquivo selecionado</div>
        </div>

<p class="form-hint">Limite de 50MB. Formatos aceitos: JPG, PNG, MP4, MP3, OGG, etc.</p>
      </div>

      <div class="form-group">
        <label class="form-label">Quando enviar?</label>
        <select id="fuDelayDays" name="delay_days" class="form-select">
          <option value="0">⚡ Imediatamente</option>
          <option value="0" data-time="1">📅 Mesmo dia às...</option>
          <option value="1" selected>📅 1 dia depois às...</option>
          <option value="2">📅 2 dias depois às...</option>
          <option value="3">📅 3 dias depois às...</option>
          <option value="7">📅 7 dias depois às...</option>
        </select>
      </div>

      <div id="fuScheduledTimeWrap" class="form-group hidden">
        <label class="form-label">⏰ Horário de envio</label>
        <input type="time" id="fuScheduledTime" name="scheduled_time" class="form-input" value="09:00">
        <p class="form-hint">Horário no formato 24h</p>
      </div>

      <div class="grid grid-cols-2 gap-3">
        <div class="form-group">
          <label class="form-label">Intervalo mínimo (Minutos)</label>
          <input type="number" id="fuIntervalMin" name="interval_min" class="form-input" value="6" min="0">
        </div>
        <div class="form-group">
          <label class="form-label">Intervalo máximo (Minutos)</label>
          <input type="number" id="fuIntervalMax" name="interval_max" class="form-input" value="15" min="0">
        </div>
      </div>
      <p class="form-hint">Intervalo aleatório entre o envio de mensagens</p>

      <div class="form-group">
        <label class="form-label">Após envio, mover para:</label>
        <select id="fuMoveToStage" name="move_to_stage_id" class="form-select">
          <option value="">Não mover automaticamente</option>
        </select>
      </div>
      
      
<div class="form-group">
  <label class="form-label">Se respondeu, mover para:</label>
  <select id="fuMoveStageSeRespondeu" name="move_stage_se_respondeu" class="form-select">
    <option value="">Não mover automaticamente</option>
  </select>
  <p class="form-hint">Coluna para onde o lead será movido caso responda a mensagem</p>
</div>

      <div class="flex items-center gap-2">
        <input type="checkbox" id="fuActive" name="active" checked class="w-4 h-4">
        <label for="fuActive" class="text-sm font-semibold">Follow-up ativo</label>
      </div>
    </form>

    <div class="modal-footer">
      <button id="fuDelete" class="btn-danger hidden">Remover Follow-up</button>
      <div class="flex gap-2 ml-auto">
        <button id="fuCancel" class="btn-icon">Cancelar</button>
        <button id="fuSave" class="btn btn-primary">Salvar Configuração</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.3/Sortable.min.js"></script>
<script>
(function(){
  const API = 'api/crm.php';
  const API_UPLOAD = 'api/upload.php';
  const board = document.getElementById('board');
  const btnAddStage = document.getElementById('btnAddStage');
  
  const PER_PAGE = 100;
  const stageState = new Map();
  
  let isDragging = false;
  let dragReleaseTimer = null;

  const esc = (s) => String(s ?? '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
  const digits = (s) => String(s||'').replace(/\D+/g,'');
  
  const normalizePhoneBR = (raw) => {
    let d = digits(raw);
    if (!d) return '';
    if (!d.startsWith('55')) d = '55' + d;
    return d;
  };

  const fileName = (u) => {
    try {
      const p = new URL(u);
      return decodeURIComponent(p.pathname.split('/').pop() || 'arquivo');
    } catch {
      const i = (u || '').lastIndexOf('/');
      return decodeURIComponent((i >= 0 ? u.slice(i + 1) : u) || 'arquivo');
    }
  };

  async function fetchJSON(url, opts) {
    const r = await fetch(url, {credentials:'same-origin', cache:'no-store', ...opts});
    const t = await r.text();
    try {
      const j = JSON.parse(t);
      if(!r.ok) return {ok:false, error:j?.error || t};
      return j;
    } catch {
      return {ok:false, error:t || 'Falha'};
    }
  }

const stageTemplate = (stage) => `
  <div class="kan-col ${stage.has_followup ? 'has-followup' : ''}" data-stage-wrap="${stage.id}">
    ${stage.has_followup ? `
      <div class="followup-active-tag">
        <span class="followup-tag-icon">✨</span>
        <span class="followup-tag-text">Follow-up Ativo</span>
      </div>
    ` : ''}
    <div class="kan-header">
      <div class="kan-header-top">
        <button class="handle" title="Arrastar coluna">⋮⋮</button>
        <input class="kan-col-title" value="${esc(stage.name)}" data-id="${stage.id}">
        <div class="kan-header-badges">
          <span class="badge badge-count">${stage.total ?? 0}</span>
          <span class="followup-badge">✨</span>
        </div>
      </div>
      <div class="kan-controls">
        <input class="kan-search" type="text" placeholder="Buscar leads..." data-stage="${stage.id}">
        ${stage.name.toLowerCase() !== 'leads' ? `<button class="btn-icon-action btn-followup-trigger" data-id="${stage.id}" title="Configurar follow-up">⚙️</button>` : ''}
${stage.name.toLowerCase() !== 'leads' ? `<button class="btn-icon-action btn-delete-stage" data-del="${stage.id}" title="Excluir coluna">🗑️</button>` : ''}
      </div>
    </div>
    <div class="kan-list" data-stage="${stage.id}">
      <div class="kan-sentinel" data-sentinel="${stage.id}"></div>
    </div>
  </div>
`;

  const cardTemplate = (lead) => {
    const company = lead.company || 'Sem nome';
    const phoneRaw = lead.phone || '';
    const phoneDigits = normalizePhoneBR(phoneRaw);
    return `
      <div class="kan-card" data-id="${lead.id}" data-company="${esc(company).toLowerCase()}" data-phone="${phoneDigits}">
        <div class="kan-card-company">${esc(company)}</div>
        <div class="kan-card-phone">${esc(phoneRaw || 'Sem telefone')}</div>
      </div>
    `;
  };

  function attachInfiniteScroll(list, sid) {
    const sentinel = list.querySelector('.kan-sentinel');
    if (!sentinel) return;

    const io = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) loadNextPage(sid);
      });
    }, {root: list, rootMargin: '200px'});
    io.observe(sentinel);

    list.addEventListener('scroll', () => {
      const st = stageState.get(sid);
      if (!st || st.loading || !st.hasMore) return;
      const nearBottom = (list.scrollTop + list.clientHeight) / list.scrollHeight > 0.9;
      if (nearBottom) loadNextPage(sid);
    });
  }

  let isLoadingBoard = false;

  async function loadBoard(retryCount = 0) {
    if (isLoadingBoard) {
      console.log('Carregamento já em andamento...');
      return;
    }

    isLoadingBoard = true;
    board.innerHTML = '<div class="loading-indicator"><div class="loading-spinner"></div><div>Carregando pipeline...</div></div>';
    
    try {
      const d = await fetchJSON(`${API}?action=board_meta&_t=${Date.now()}`);
      
      if (!d.ok) {
        if (retryCount < 2 && d.error && d.error.includes('does not exist')) {
          console.log(`Tentativa ${retryCount + 1} falhou, tentando novamente...`);
          isLoadingBoard = false;
          await new Promise(resolve => setTimeout(resolve, 300));
          return loadBoard(retryCount + 1);
        }
        
        board.innerHTML = `<div class="loading-indicator"><div style="color: var(--danger);">❌ ${esc(d.error||'Erro ao carregar')}</div></div>`;
        isLoadingBoard = false;
        return;
      }

      const {stages} = d;
      board.innerHTML = stages.map(stageTemplate).join('');

      document.querySelectorAll('.kan-list').forEach(list => {
        const sid = Number(list.getAttribute('data-stage'));
        stageState.set(sid, {page: 0, q: '', loading: false, hasMore: true});

        new Sortable(list, {
          group: {name: 'kanban', pull: true, put: true},
          animation: 200,
          ghostClass: 'opacity-50',
          dragClass: 'dragging',
          forceFallback: true,
          scroll: true,
          scrollSensitivity: 60,
          scrollSpeed: 15,
          bubbleScroll: true,
          draggable: '.kan-card',
          filter: '.kan-sentinel',
          onMove: (evt) => {
            if (evt.related && evt.related.classList.contains('kan-sentinel')) return false;
            return true;
          },
          onStart: (evt) => {
            isDragging = true;
            if (dragReleaseTimer) clearTimeout(dragReleaseTimer);
            evt.item.classList.add('dragging');
          },
          onEnd: (evt) => {
            evt.item.classList.remove('dragging');
            const l = evt.to || evt.from || list;
            const s = l.querySelector('.kan-sentinel');
            if (s && s !== l.lastElementChild) l.appendChild(s);
            dragReleaseTimer = setTimeout(() => { isDragging = false; }, 150);
          },
          onAdd: (evt) => {
            const l = evt.to;
            const s = l.querySelector('.kan-sentinel');
            if (s && s !== l.lastElementChild) l.appendChild(s);
            saveMove(evt);
          },
          onUpdate: (evt) => {
            const l = evt.to;
            const s = l.querySelector('.kan-sentinel');
            if (s && s !== l.lastElementChild) l.appendChild(s);
            saveMove(evt);
          }
        });

        attachInfiniteScroll(list, sid);
      });

      new Sortable(board, {
        handle: '.handle',
        animation: 200,
        onEnd: saveStageOrder
      });

      board.querySelectorAll('input[data-id]').forEach(inp => {
        inp.addEventListener('change', async () => {
          const id = inp.getAttribute('data-id');
          const name = inp.value.trim();
          if (!name) return;
          await fetchJSON(`${API}?action=stage_rename`, {
            method: 'POST',
            body: new URLSearchParams({id, name})
          });
        });
      });

      board.querySelectorAll('[data-del]').forEach(btn => {
        btn.addEventListener('click', async () => {
          const id = btn.getAttribute('data-del');
          if (!confirm('Excluir esta coluna? Os leads serão movidos para "Leads".')) return;
          const r = await fetchJSON(`${API}?action=stage_delete`, {
            method: 'POST',
            body: new URLSearchParams({id})
          });
          if (!r.ok) alert('❌ ' + (r.error || 'Falha ao excluir'));
          isLoadingBoard = false;
          await loadBoard();
        });
      });

      board.querySelectorAll('.btn-followup-trigger').forEach(btn => {
        btn.addEventListener('click', async () => {
          const stageId = Number(btn.getAttribute('data-id'));
          await openFollowupModal(stageId);
        });
      });

      let searchTimer = null;
      board.addEventListener('input', (e) => {
        if (e.target && e.target.classList.contains('kan-search')) {
          const sid = Number(e.target.getAttribute('data-stage'));
          const q = e.target.value || '';
          clearTimeout(searchTimer);
          searchTimer = setTimeout(() => {
            resetAndLoadFirstPage(sid, q);
          }, 300);
        }
      });

      for (const s of stages) {
        await resetAndLoadFirstPage(Number(s.id), '');
        await new Promise(resolve => setTimeout(resolve, 50));
      }

      isLoadingBoard = false;
      
    } catch (error) {
      console.error('Erro ao carregar board:', error);
      board.innerHTML = `<div class="loading-indicator"><div style="color: var(--danger);">❌ Erro: ${error.message}</div></div>`;
      isLoadingBoard = false;
    }
  }

  async function resetAndLoadFirstPage(stageId, q) {
    const list = board.querySelector(`.kan-list[data-stage="${stageId}"]`);
    if (!list) return;

    list.innerHTML = '<div class="kan-sentinel" data-sentinel="' + stageId + '"></div>';
    attachInfiniteScroll(list, stageId);

    const st = stageState.get(stageId) || {page: 0, q: '', loading: false, hasMore: true};
    st.page = 0;
    st.q = q || '';
    st.hasMore = true;
    stageState.set(stageId, st);
    await loadNextPage(stageId);
  }

  async function loadNextPage(stageId) {
    const st = stageState.get(stageId);
    if (!st || st.loading || !st.hasMore) return;

    st.loading = true;
    stageState.set(stageId, st);

    const nextPage = (st.page || 0) + 1;
    const params = new URLSearchParams({
      action: 'cards_page',
      stage_id: String(stageId),
      page: String(nextPage),
      per: String(PER_PAGE)
    });
    if (st.q) params.set('q', st.q);

    const d = await fetchJSON(`${API}?${params.toString()}`);

    if (!d.ok) {
      st.loading = false;
      stageState.set(stageId, st);
      return alert('❌ ' + (d.error || 'Falha ao carregar'));
    }

    const list = board.querySelector(`.kan-list[data-stage="${stageId}"]`);
    if (!list) {
      st.loading = false;
      stageState.set(stageId, st);
      return;
    }

    const sentinel = list.querySelector('.kan-sentinel');
    const frag = document.createDocumentFragment();
    for (const c of d.cards) {
      const el = document.createElement('div');
      el.innerHTML = cardTemplate(c);
      frag.appendChild(el.firstElementChild);
    }
    list.insertBefore(frag, sentinel);

    const countEl = board.querySelector(`[data-stage-wrap="${stageId}"] .badge-count`);
    if (countEl) countEl.textContent = `${d.total}`;

    st.page = d.page;
    st.hasMore = d.has_more;
    st.loading = false;
    stageState.set(stageId, st);
  }

  async function saveMove(evt) {
    const item = evt.item;
    const toList = evt.to;
    const toStage = toList.getAttribute('data-stage');
    const leadId = item.getAttribute('data-id');
    const newIndex = [...toList.querySelectorAll('.kan-card')].indexOf(item);

    const payload = {
      lead_id: Number(leadId),
      to_stage_id: Number(toStage),
      to_index: newIndex
    };
    const r = await fetchJSON(`${API}?action=move_card`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(payload)
    });
    if (!r.ok) alert('❌ ' + (r.error || 'Falha ao mover'));
  }

  async function saveStageOrder() {
    const ids = [...board.querySelectorAll('.kan-list')].map(el => Number(el.getAttribute('data-stage')));
    const r = await fetchJSON(`${API}?action=stage_reorder`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ids})
    });
    if (!r.ok) alert('❌ ' + (r.error || 'Falha'));
  }

  btnAddStage.addEventListener('click', async () => {
    const name = prompt('Nome da nova coluna:');
    if (!name) return;
    const r = await fetchJSON(`${API}?action=stage_create`, {
      method: 'POST',
      body: new URLSearchParams({name})
    });
    if (!r.ok) {
      alert('❌ ' + (r.error || 'Falha'));
      return;
    }
    await loadBoard();
  });

  board.addEventListener('click', (e) => {
    if (isDragging) return;
    const card = e.target.closest('.kan-card');
    if (!card) return;
    const phone = card.dataset.phone;
    if (!phone) {
      alert('Lead sem telefone cadastrado.');
      return;
    }
    window.open(`https://wa.me/${phone}`, '_blank');
  });

  // ===== FOLLOW-UP MODAL =====
  const fuModal = document.getElementById('followupModal');
  const fuForm = document.getElementById('fuForm');
  const fuStageId = document.getElementById('fuStageId');
  const fuMessageType = document.getElementById('fuMessageType');
  const fuMessageText = document.getElementById('fuMessageText');
  const fuMediaSection = document.getElementById('fuMediaSection');
  const fuMediaUrl = document.getElementById('fuMediaUrl');
  const fuMediaPreview = document.getElementById('fuMediaPreview');
  const fuBtnUpload = document.getElementById('fuBtnUpload');
  const fuBtnPaste = document.getElementById('fuBtnPaste');
  const fuBtnOpen = document.getElementById('fuBtnOpen');
  const fuBtnClear = document.getElementById('fuBtnClear');
  const fuDelayDays = document.getElementById('fuDelayDays');
  const fuScheduledTime = document.getElementById('fuScheduledTime');
  const fuScheduledTimeWrap = document.getElementById('fuScheduledTimeWrap');
  const fuIntervalMin = document.getElementById('fuIntervalMin');
  const fuIntervalMax = document.getElementById('fuIntervalMax');
  const fuMoveToStage = document.getElementById('fuMoveToStage');
  const fuActive = document.getElementById('fuActive');
  const fuClose = document.getElementById('fuClose');
  const fuCancel = document.getElementById('fuCancel');
  const fuSave = document.getElementById('fuSave');
  const fuDelete = document.getElementById('fuDelete');

  let currentFollowupStageId = null;

  fuMessageType.addEventListener('change', () => {
  const type = fuMessageType.value;
  if (type === 'image' || type === 'video' || type === 'audio') {
    fuMediaSection.classList.remove('hidden');
    renderMediaPreview();
  } else {
    fuMediaSection.classList.add('hidden');
    fuMediaUrl.value = '';
  }
});

  fuDelayDays.addEventListener('change', () => {
    const selectedOption = fuDelayDays.options[fuDelayDays.selectedIndex];
    const isImmediate = fuDelayDays.value === '0' && !selectedOption.getAttribute('data-time');
    
    if (isImmediate) {
      fuScheduledTimeWrap.classList.add('hidden');
      fuScheduledTime.value = '';
    } else {
      fuScheduledTimeWrap.classList.remove('hidden');
      if (!fuScheduledTime.value) fuScheduledTime.value = '09:00';
    }
  });

  function renderMediaPreview() {
  const type = fuMessageType.value;
  const url = fuMediaUrl.value.trim();
  
  fuBtnOpen.disabled = !url;
  fuBtnClear.disabled = !url;
  
  if (!url) {
    fuMediaPreview.innerHTML = '<div class="text-xs text-gray-500">Nenhum arquivo selecionado</div>';
    return;
  }
  
  if (type === 'image') {
    fuMediaPreview.innerHTML = `<img src="${esc(url)}" alt="preview">`;
  } else if (type === 'video') {
    fuMediaPreview.innerHTML = `
      <div class="flex items-center gap-3 text-sm">
        <svg class="w-6 h-6 text-red-500" fill="currentColor" viewBox="0 0 24 24">
          <path d="M17 10.5V6a2 2 0 0 0-2-2H3v16h12a2 2 0 0 0 2-2v-4.5l4 4v-11l-4 4z"/>
        </svg>
        <span class="truncate flex-1">${esc(fileName(url))}</span>
      </div>
    `;
  } else if (type === 'audio') {
    fuMediaPreview.innerHTML = `
      <div class="flex items-center gap-3 text-sm">
        <svg class="w-6 h-6 text-purple-500" fill="currentColor" viewBox="0 0 24 24">
          <path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/>
        </svg>
        <span class="truncate flex-1">${esc(fileName(url))}</span>
      </div>
    `;
  }
}

  fuBtnUpload.addEventListener('click', async () => {
  const type = fuMessageType.value;
  let accept = 'image/*'; // padrão
  
  if (type === 'image') {
    accept = 'image/*';
  } else if (type === 'video') {
    accept = 'video/*';
  } else if (type === 'audio') {
    accept = 'audio/*';
  }
  
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = accept;
    
    fileInput.onchange = async () => {
      if (!fileInput.files || !fileInput.files[0]) return;
      
      fuBtnUpload.disabled = true;
      const oldText = fuBtnUpload.textContent;
      fuBtnUpload.textContent = '⏳ Enviando...';
      
      const fd = new FormData();
fd.append('file', fileInput.files[0]);

let kind = 'imagem'; // padrão
if (type === 'image') {
  kind = 'imagem';
} else if (type === 'video') {
  kind = 'video';
} else if (type === 'audio') {
  kind = 'audio';
}

fd.append('kind', kind);
      
      try {
        const r = await fetch(API_UPLOAD, {
          method: 'POST',
          body: fd,
          credentials: 'same-origin'
        });
        const j = await r.json();
        
        if (j.ok) {
          fuMediaUrl.value = j.public_url || j.signed_url || '';
          renderMediaPreview();
          alert('✅ Arquivo enviado com sucesso!');
        } else {
          alert('❌ ' + (j.error || 'Falha ao enviar'));
        }
      } catch (error) {
        alert('❌ Erro de rede: ' + error.message);
      }
      
      fuBtnUpload.disabled = false;
      fuBtnUpload.textContent = oldText;
    };
    
    fileInput.click();
  });

  fuBtnPaste.addEventListener('click', () => {
    const url = prompt('Cole a URL pública do arquivo:');
    if (!url) return;
    fuMediaUrl.value = url.trim();
    renderMediaPreview();
  });

  fuBtnOpen.addEventListener('click', () => {
    const url = fuMediaUrl.value.trim();
    if (url) window.open(url, '_blank');
  });

  fuBtnClear.addEventListener('click', () => {
    fuMediaUrl.value = '';
    renderMediaPreview();
  });

  async function openFollowupModal(stageId) {
    currentFollowupStageId = stageId;
    fuStageId.value = stageId;

    const stagesData = await fetchJSON(`${API}?action=board_meta`);
    if (!stagesData.ok) {
      alert('❌ Erro ao carregar colunas');
      return;
    }
    
    const stages = stagesData.stages || [];

    fuMoveToStage.innerHTML = '<option value="">Não mover automaticamente</option>';
    stages.forEach(s => {
      if (Number(s.id) !== Number(stageId)) {
        const opt = document.createElement('option');
        opt.value = s.id;
        opt.textContent = s.name;
        fuMoveToStage.appendChild(opt);
      }
    });
    
    
// Preencher o select "Se respondeu mover para"
const fuMoveStageSeRespondeu = document.getElementById('fuMoveStageSeRespondeu');
fuMoveStageSeRespondeu.innerHTML = '<option value="">Não mover automaticamente</option>';
stages.forEach(s => {
  if (Number(s.id) !== Number(stageId)) {
    const opt = document.createElement('option');
    opt.value = s.id;
    opt.textContent = s.name;
    fuMoveStageSeRespondeu.appendChild(opt);
  }
});

    const d = await fetchJSON(`${API}?action=followup_get&stage_id=${stageId}`);
    if (d.ok && d.config) {
      const c = d.config;
      fuMessageType.value = c.message_type || 'text';
      fuMessageText.value = c.message_text || '';
      fuMediaUrl.value = c.media_url || '';
      fuDelayDays.value = c.delay_days ?? 1;
      fuScheduledTime.value = c.scheduled_time || '09:00';
      fuIntervalMin.value = c.interval_min ?? 60;
      fuIntervalMax.value = c.interval_max ?? 300;
      fuMoveToStage.value = c.move_to_stage_id || '';
      fuMoveStageSeRespondeu.value = c.move_stage_se_respondeu || '';

      fuActive.checked = c.active !== false;
      fuDelete.classList.remove('hidden');
    } else {
      fuMessageType.value = 'text';
      fuMessageText.value = '';
      fuMediaUrl.value = '';
      fuDelayDays.value = 1;
      fuScheduledTime.value = '09:00';
      fuIntervalMin.value = 6;
      fuIntervalMax.value = 15;
      fuMoveToStage.value = '';
      fuMoveStageSeRespondeu.value = '';

      fuActive.checked = true;
      fuDelete.classList.add('hidden');
    }

    fuMessageType.dispatchEvent(new Event('change'));
    fuDelayDays.dispatchEvent(new Event('change'));

    fuModal.classList.add('active');
  }

  function closeFollowupModal() {
    fuModal.classList.remove('active');
    currentFollowupStageId = null;
  }

  fuClose.addEventListener('click', closeFollowupModal);
  fuCancel.addEventListener('click', closeFollowupModal);
  fuModal.querySelector('.modal-overlay').addEventListener('click', closeFollowupModal);

  fuSave.addEventListener('click', async (e) => {
    e.preventDefault();

    const fd = new FormData();
    fd.append('stage_id', fuStageId.value);
    fd.append('message_type', fuMessageType.value);
    fd.append('message_text', fuMessageText.value);
    fd.append('media_url', fuMediaUrl.value);
    fd.append('delay_days', fuDelayDays.value);
    fd.append('scheduled_time', fuScheduledTime.value);
    fd.append('move_to_stage_id', fuMoveToStage.value);
    fd.append('move_stage_se_respondeu', document.getElementById('fuMoveStageSeRespondeu').value);
    fd.append('interval_min', fuIntervalMin.value);
    fd.append('interval_max', fuIntervalMax.value);
    fd.append('active', fuActive.checked ? '1' : '0');

    const d = await fetchJSON(`${API}?action=followup_save`, {method: 'POST', body: fd});
    if (!d.ok) {
      alert('❌ ' + (d.error || 'Erro ao salvar'));
      return;
    }

    closeFollowupModal();
    await loadBoard();
    alert('✅ Follow-up configurado com sucesso!');
  });

  fuDelete.addEventListener('click', async () => {
    if (!currentFollowupStageId) return;
    if (!confirm('Remover follow-up desta coluna?')) return;

    const fd = new FormData();
    fd.append('stage_id', currentFollowupStageId);

    const d = await fetchJSON(`${API}?action=followup_delete`, {method: 'POST', body: fd});
    if (!d.ok) {
      alert('❌ ' + (d.error || 'Erro'));
      return;
    }

    closeFollowupModal();
    await loadBoard();
    alert('✅ Follow-up removido com sucesso!');
  });

  loadBoard();
})();
</script>