<script setup>
import { ref, inject } from 'vue'
import { fmtDur, shortAddr, prioLabel, prioClass, prioColor, dayLoadColor, ICON } from 'src/composables/useHelpers'

const props = defineProps({
  open: Boolean,
  height: Number,
  groups: Array,
  unscheduledCount: Number,
  selected: Object, // Set
  dropActive: Boolean,
  sort: { type: String, default: 'date' }, // tri du pool : date | city | priority
})

const emit = defineEmits([
  'update:open', 'update:height', 'resize-start', 'update:sort',
  'toggle-select', 'select-all', 'clear-select', 'batch-assign',
  'auto-distribute', 'open-criteria',
  'row-click', 'row-dblclick', 'row-dragstart',
  'drop-unassign', 'lasso-select', 'deselect-all',
])

const store = inject('store')
const TECH_COLORS = inject('TECH_COLORS')
const jobColor = inject('jobColor')
const btColW = inject('btColW')
const startColResize = inject('startColResize')

// Aujourd'hui (fuseau Québec) → un groupe de date PASSÉE = tickets « en retard » (à traiter/fermer).
const todayISO = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Toronto' })

// ── Lasso selection ───────────────────────────────────────────────────────────
const btLasso = ref(null)
const btScrollRef = ref(null)
let btLassoMoved = false

function btLassoStart (e) {
  if (e.target.closest('button, input, .sb-bt-checkbox, a, .sb-col-resize, .sb-bottom-hdr, .sb-bottom-resize')) return
  if (e.button !== 0) return
  const scroll = btScrollRef.value
  if (!scroll) return

  // On a job row — don't start lasso, let drag handle it
  const row = e.target.closest('.sb-bottom-row')
  if (row) return

  e.preventDefault()
  btLassoMoved = false
  const rect = scroll.getBoundingClientRect()
  const x = e.clientX - rect.left + scroll.scrollLeft
  const y = e.clientY - rect.top + scroll.scrollTop
  btLasso.value = { x1: x, y1: y, x2: x, y2: y }
  document.addEventListener('mousemove', btLassoMove)
  document.addEventListener('mouseup', btLassoEnd)
}

function btLassoMove (e) {
  if (!btLasso.value) return
  e.preventDefault()
  btLassoMoved = true
  const scroll = btScrollRef.value
  const rect = scroll.getBoundingClientRect()
  btLasso.value.x2 = e.clientX - rect.left + scroll.scrollLeft
  btLasso.value.y2 = e.clientY - rect.top + scroll.scrollTop

  // Live selection as lasso moves
  const l = btLasso.value
  const h = Math.abs(l.y2 - l.y1)
  if (h > 8) {
    const scrollRect = scroll.getBoundingClientRect()
    const lassoTop = Math.min(l.y1, l.y2) - scroll.scrollTop + scrollRect.top
    const lassoBottom = lassoTop + h
    const rows = scroll.querySelectorAll('.sb-bottom-row')
    const ids = []
    rows.forEach(row => {
      const r = row.getBoundingClientRect()
      if (r.bottom > lassoTop && r.top < lassoBottom) {
        const jobId = row.dataset?.jobId
        if (jobId) ids.push(jobId)
      }
    })
    if (ids.length) emit('lasso-select', ids)
  }
}

function btLassoEnd () {
  document.removeEventListener('mousemove', btLassoMove)
  document.removeEventListener('mouseup', btLassoEnd)
  if (!btLasso.value) return

  // If no movement = click on empty space = clear selection
  if (!btLassoMoved) {
    emit('deselect-all')
  }

  btLasso.value = null
}
</script>

<template>
<div v-if="open" class="sb-bottom-panel" :style="'height:'+height+'px'">
  <div class="sb-bottom-resize" @mousedown.prevent="emit('resize-start', $event)"></div>
  <div class="sb-bottom-hdr">
    <span class="sb-bottom-title">
      Jobs non assignées
      <span class="sbf-count">{{ unscheduledCount }}</span>
    </span>
    <button v-if="unscheduledCount" class="sbf-auto-btn" @click="emit('auto-distribute')" title="Répartir automatiquement">⚡ Répartir auto</button>
    <button class="sbf-auto-btn" style="border-color:rgba(255,255,255,0.12)" @click="emit('open-criteria')" title="Critères de dispatch">⚙ Critères</button>
    <label style="display:inline-flex;align-items:center;gap:4px;font-size:0.72rem;opacity:.85" title="Trier le pool">⇅
      <select :value="sort" @change="emit('update:sort', $event.target.value)" style="background:rgba(255,255,255,0.06);color:inherit;border:1px solid rgba(255,255,255,0.12);border-radius:5px;padding:1px 4px;font-size:0.72rem">
        <option value="date">Date</option><option value="city">Ville</option><option value="priority">Priorité</option>
      </select>
    </label>
    <!-- Batch assign bar -->
    <template v-if="selected.size">
      <span class="sb-bottom-sel-count">{{ selected.size }} sélectionnée{{ selected.size>1?'s':'' }}</span>
      <span class="sb-bottom-sel-lbl">→</span>
      <button v-for="t in store.technicians" :key="t.id" class="sb-multi-tech"
              :style="'border-color:'+TECH_COLORS[t.colorIdx]" :title="t.fullName"
              @click="emit('batch-assign', t.id)">
        {{ t.fullName.split(' ').map(n=>n[0]).join('').toUpperCase().slice(0,2) }}
      </button>
      <button class="sb-bottom-sel-clear" @click="emit('clear-select')">✕</button>
    </template>
    <div style="flex:1"></div>
    <button v-if="unscheduledCount" class="sb-bottom-sel-all" @click="emit('select-all')" title="Tout sélectionner">☐ Tout</button>
    <button class="sb-bottom-close" @click="emit('update:open', false)">✕</button>
  </div>
  <div class="sb-bottom-body"
       :class="{ 'sbf-drop-active': dropActive }"
       @dragover.prevent="$emit('drop-unassign', $event, 'over')"
       @dragleave="$emit('drop-unassign', $event, 'leave')"
       @drop="$emit('drop-unassign', $event, 'drop')">
    <div v-if="dropActive" class="sbf-drop-hint" style="margin:4px">↩ Désaffecter ici</div>
    <table class="sb-bottom-table">
      <thead>
        <tr>
          <th class="sb-bt-chk" style="width:28px"></th>
          <th class="sb-bt-prio" style="width:12px"></th>
          <th class="sb-bt-name" :style="'width:'+btColW('name',200)"><span>Nom</span><div class="sb-col-resize" @mousedown="startColResize($event,'name')"></div></th>
          <th class="sb-bt-addr" :style="'width:'+btColW('addr',180)"><span>Adresse</span><div class="sb-col-resize" @mousedown="startColResize($event,'addr')"></div></th>
          <th class="sb-bt-dur" :style="'width:'+btColW('dur',130)"><span>Durée</span><div class="sb-col-resize" @mousedown="startColResize($event,'dur')"></div></th>
          <th class="sb-bt-prio-lbl" style="width:70px">Priorité</th>
          <th class="sb-bt-tags">Skills / Tags</th>
        </tr>
      </thead>
    </table>
    <div class="sb-bottom-scroll" ref="btScrollRef" @mousedown="btLassoStart" style="position:relative">
      <template v-for="group in groups" :key="group.key || group.date || 'nodate'">
        <div class="sb-bottom-date-sep">
          <span class="sb-bottom-date-label">{{ group.label }}</span>
          <span class="sb-bottom-date-count">{{ group.jobs.length }}</span>
          <span v-if="group.date && group.date < todayISO" :style="{ marginLeft:'8px', color:'#e53935', fontWeight:700, fontSize:'10px', letterSpacing:'.3px' }" title="Date dépassée — à replanifier ou fermer">⏰ EN RETARD</span>
        </div>
        <table class="sb-bottom-table">
          <tbody>
            <tr v-for="job in group.jobs" :key="job.id"
                class="sb-bottom-row" :class="{ 'sb-bottom-row-sel': selected.has(job.id) }"
                :data-job-id="job.id"
                draggable="true"
                @dragstart="emit('row-dragstart', $event, job, selected.has(job.id) && selected.size > 1)"
                @click="emit('row-click', job, $event)"
                @dblclick.stop="emit('row-dblclick', job)">
              <td class="sb-bt-chk" style="width:28px" @click.stop="emit('toggle-select', job.id, $event)">
                <span class="sb-bt-checkbox" :class="{ checked: selected.has(job.id) }"></span>
              </td>
              <td class="sb-bt-prio" style="width:12px">
                <span class="sb-bt-prio-dot" :style="'background:'+prioColor(job.priority)" :title="prioLabel(job.priority)"></span>
              </td>
              <td class="sb-bt-name" :style="'width:'+btColW('name',200)">
                <span :style="{ display:'inline-block', width:'9px', height:'9px', borderRadius:'2px', marginRight:'6px', verticalAlign:'middle', flex:'0 0 auto', background: jobColor(job) }" :title="job.legacyDept || job.jobType || ''"></span>
                <span class="sb-bt-name-text">{{ job.subject }}</span>
              </td>
              <td class="sb-bt-addr" :style="'width:'+btColW('addr',180)">{{ shortAddr(job.address) || '—' }}</td>
              <td class="sb-bt-dur" :style="'width:'+btColW('dur',130)">
                <div class="sb-bt-dur-wrap">
                  <div class="sb-bt-dur-bar">
                    <div class="sb-bt-dur-fill" :style="{ width: Math.min(100,(parseFloat(job.duration)||0)/8*100)+'%', background: dayLoadColor((parseFloat(job.duration)||0)/8) }"></div>
                  </div>
                  <span class="sb-bt-dur-lbl">{{ fmtDur(job.duration) }}</span>
                </div>
              </td>
              <td class="sb-bt-prio-lbl" style="width:70px">
                <span :class="prioClass(job.priority)" class="sb-bt-prio-tag">{{ prioLabel(job.priority) }}</span>
              </td>
              <td class="sb-bt-tags">
                <span v-for="t in (job.tags||[])" :key="t" class="sb-bt-skill-chip">{{ t }}</span>
                <span v-if="!(job.tags||[]).length" class="sb-bt-no-tag">—</span>
              </td>
            </tr>
          </tbody>
        </table>
      </template>
      <div v-if="!unscheduledCount" class="sbf-empty" style="padding:1rem;text-align:center">Aucune job non assignée</div>
      <div v-if="btLasso" class="sb-bt-lasso" :style="{
        left: Math.min(btLasso.x1, btLasso.x2) + 'px',
        top: Math.min(btLasso.y1, btLasso.y2) + 'px',
        width: Math.abs(btLasso.x2 - btLasso.x1) + 'px',
        height: Math.abs(btLasso.y2 - btLasso.y1) + 'px'
      }"></div>
    </div>
  </div>
</div>
</template>
