<!-- front-end/app/pages/pipeline/index.vue -->
<script setup lang="ts">
import { PIPELINE_ETAPAS } from '~/types'

const { apiFetch } = useApi()

interface ApiEdital {
  ID: string; Numero: string; Orgao: string; Modalidade: string
  Objeto: string; Plataforma: string; ValorEstimado: number
  DataPublicacao: string; DataAbertura: string; Status: string
}

const { data: rawEditais } = await useAsyncData('pipeline-editais', () =>
  apiFetch<ApiEdital[]>('/editais')
)

// Cópia local reativa — permite optimistic updates que o computed detecta
const items = ref<ApiEdital[]>([])
watchEffect(() => { items.value = [...(rawEditais.value ?? [])] })

const etapaParaStatus: Record<number, string> = {
  1: 'em_analise',
  2: 'elaborando_proposta',
  3: 'edital_publicado',
  4: 'fase_lances',
  5: 'habilitacao',
  6: 'recurso',
  7: 'adjudicado',
  8: 'contrato',
}

const statusParaEtapa: Record<string, number> = {
  em_analise: 1,
  elaborando_proposta: 2,
  edital_publicado: 3,
  fase_lances: 4,
  habilitacao: 5,
  recurso: 6,
  adjudicado: 7,
  contrato: 8,
  vencida: 8,
  perdida: 8,
  deserta: 8,
}

const colunas = computed(() =>
  PIPELINE_ETAPAS.map((etapa, idx) => ({
    etapa,
    numero: idx + 1,
    cards: items.value.filter(e => statusParaEtapa[e.Status] === idx + 1),
  }))
)

const modalidadeAbrev: Record<string, string> = {
  pregao_eletronico: 'PE',
  pregao_presencial: 'PP',
  concorrencia: 'CC',
  dispensa: 'DI',
  inexigibilidade: 'IN',
}

/* ── Drag & Drop ── */
const draggedId = ref<string | null>(null)
const dragOverCol = ref<number | null>(null)
const movingCardId = ref<string | null>(null)

function onDragStart(e: DragEvent, card: ApiEdital) {
  draggedId.value = card.ID
  if (e.dataTransfer) {
    e.dataTransfer.effectAllowed = 'move'
    e.dataTransfer.setData('text/plain', card.ID)
  }
  const el = e.target as HTMLElement
  requestAnimationFrame(() => el.classList.add('dragging'))
}

function onDragEnd(e: DragEvent) {
  draggedId.value = null
  dragOverCol.value = null
  const el = e.target as HTMLElement
  el.classList.remove('dragging')
}

function onDragOver(e: DragEvent, colNum: number) {
  e.preventDefault()
  if (e.dataTransfer) e.dataTransfer.dropEffect = 'move'
  dragOverCol.value = colNum
}

function onDragLeave(_e: DragEvent, colNum: number) {
  if (dragOverCol.value === colNum) dragOverCol.value = null
}

function draggedStatus() {
  const card = items.value.find(e => e.ID === draggedId.value)
  return card?.Status ?? ''
}

async function onDrop(e: DragEvent, colNum: number) {
  e.preventDefault()
  dragOverCol.value = null

  const cardId = draggedId.value
  draggedId.value = null
  if (!cardId) return

  const idx = items.value.findIndex(e => e.ID === cardId)
  if (idx === -1) return

  const card = items.value[idx]
  const currentEtapa = statusParaEtapa[card.Status]
  if (currentEtapa === colNum) return

  const newStatus = etapaParaStatus[colNum]
  if (!newStatus) return

  // Optimistic update — substitui o objeto no array para triggerar reatividade
  const oldStatus = card.Status
  items.value[idx] = { ...card, Status: newStatus }
  movingCardId.value = cardId

  try {
    await apiFetch(`/editais/${cardId}`, {
      method: 'PUT',
      body: { Status: newStatus },
    })
  } catch {
    // Reverte
    items.value[idx] = { ...items.value[idx], Status: oldStatus }
  } finally {
    setTimeout(() => { movingCardId.value = null }, 400)
  }
}
</script>

<template>
  <div class="page">
    <AppTopbar title="Kanban de Processos" breadcrumb="Pipeline" />
    <div class="kanban-scroll">
      <div class="kanban-board">
        <div
          v-for="col in colunas"
          :key="col.numero"
          class="kanban-col"
          :class="{ 'drop-target': dragOverCol === col.numero && statusParaEtapa[draggedStatus()] !== col.numero }"
          @dragover="onDragOver($event, col.numero)"
          @dragleave="onDragLeave($event, col.numero)"
          @drop="onDrop($event, col.numero)"
        >
          <div class="col-header">
            <span class="col-num">{{ col.numero }}</span>
            <span class="col-title">{{ col.etapa }}</span>
            <UBadge :label="String(col.cards.length)" variant="soft" color="neutral" size="xs" />
          </div>
          <div class="col-cards">
            <div
              v-for="card in col.cards"
              :key="card.ID"
              class="kanban-card"
              :class="{ 'card-just-moved': movingCardId === card.ID }"
              draggable="true"
              @dragstart="onDragStart($event, card)"
              @dragend="onDragEnd"
              @click="navigateTo(`/oportunidades/${card.ID}`)"
            >
              <div class="card-top">
                <span class="card-num">{{ card.Numero }}</span>
                <StatusChip :status="(card.Status as any)" />
              </div>
              <p class="card-objeto">{{ card.Objeto }}</p>
              <p class="card-orgao">{{ card.Orgao }}</p>
              <div class="card-bottom">
                <span class="card-modal">{{ modalidadeAbrev[card.Modalidade] ?? card.Modalidade }}</span>
                <span class="card-valor">
                  {{ new Intl.NumberFormat('pt-BR', { notation: 'compact', currency: 'BRL', style: 'currency' }).format(card.ValorEstimado) }}
                </span>
              </div>
            </div>
            <p v-if="!col.cards.length" class="col-empty">Sem editais</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.page { display: flex; flex-direction: column; height: 100vh; }
.kanban-scroll { flex: 1; overflow-x: auto; padding: 20px 22px; }
.kanban-board { display: flex; gap: 12px; min-width: max-content; align-items: flex-start; }
.kanban-col {
  width: 220px;
  background: #f8fafc;
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  flex-shrink: 0;
  transition: border-color .2s, background .2s, box-shadow .2s;
}
.kanban-col.drop-target {
  border-color: #667eea;
  background: #eef2ff;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.25);
}
.col-header { display: flex; align-items: center; gap: 6px; padding: 10px 12px; border-bottom: 1px solid #e2e8f0; }
.col-num { width: 20px; height: 20px; background: #667eea; color: white; border-radius: 50%; font-size: 10px; font-weight: 700; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.col-title { font-size: 11.5px; font-weight: 600; color: #374151; flex: 1; }
.col-cards { padding: 8px; display: flex; flex-direction: column; gap: 8px; min-height: 80px; }
.kanban-card {
  background: white;
  border-radius: 8px;
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  cursor: grab;
  transition: border-color .15s, box-shadow .15s, opacity .15s, transform .2s;
  user-select: none;
}
.kanban-card:hover { border-color: #667eea; box-shadow: 0 2px 8px rgba(102,126,234,.15); }
.kanban-card:active { cursor: grabbing; }
.kanban-card.dragging {
  opacity: 0.4;
  transform: scale(0.95);
}
.kanban-card.card-just-moved {
  animation: card-pop 0.4s ease;
}
@keyframes card-pop {
  0% { transform: scale(0.9); opacity: 0.5; }
  50% { transform: scale(1.03); }
  100% { transform: scale(1); opacity: 1; }
}
.card-top { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }
.card-num { font-size: 11px; font-weight: 700; color: #0f172a; }
.card-objeto { font-size: 12px; color: #374151; font-weight: 500; margin-bottom: 3px; line-height: 1.3; }
.card-orgao { font-size: 10.5px; color: #94a3b8; margin-bottom: 8px; }
.card-bottom { display: flex; justify-content: space-between; align-items: center; }
.card-modal { font-size: 10px; font-weight: 600; background: #f1f5f9; color: #64748b; padding: 2px 6px; border-radius: 4px; }
.card-valor { font-size: 11px; font-weight: 700; color: #667eea; }
.col-empty { font-size: 11px; color: #94a3b8; text-align: center; padding: 16px 0; }
</style>
