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

const props = defineProps({
  tech: Object,
  segments: Array, // from techDayJobsWithTravel
  hourTicks: Array,
  totalW: Number,
  pxPerHr: Number,
  hStart: Number,
  hEnd: Number,
  rowH: Number,
  isSelected: Boolean,
  isElevated: Boolean,
  dropGhostX: { type: Number, default: null },
})

const emit = defineEmits([
  'select-tech', 'ctx-tech', 'open-tech-tags', 'drag-tech-start', 'reorder-drop',
  'timeline-dragover', 'timeline-dragleave', 'timeline-drop',
  'job-dragstart', 'job-click', 'job-dblclick', 'job-ctx',
  'assist-ctx', 'hover-job', 'unhover-job',
  'block-move', 'block-resize',
  'open-absence', 'end-absence',
  'absence-resize',
  'ghost-click', 'ghost-materialize',
  'open-schedule',
])

const TECH_COLORS = inject('TECH_COLORS')
const jobColor = inject('jobColor')
const selectedJob = inject('selectedJob')
const hoveredJobId = inject('hoveredJobId')
const periodLoadH = inject('periodLoadH')
const techPeriodCapacityH = inject('techPeriodCapacityH')
const techDayEndH = inject('techDayEndH')
const getTagColor = inject('getTagColor')
const isJobMultiSelected = inject('isJobMultiSelected')
const planningMode = inject('planningMode', ref(false))
</script>

<template>
<div class="sb-row" :class="{ 'sb-row-sel': isSelected, 'sb-row-elevated': isElevated, 'sb-row-absent': tech.status === 'off' }"
     :style="'height:'+rowH+'px'" :data-tech-id="tech.id">

  <!-- Resource cell -->
  <div class="sb-res-cell" @click="emit('select-tech', tech)" @contextmenu.prevent="emit('ctx-tech', $event, tech)"
       draggable="true" @dragstart="emit('drag-tech-start', $event, tech)"
       @dragover.prevent="()=>{}" @drop.prevent="emit('reorder-drop', $event, tech)">
    <div v-if="tech.resourceType==='material'" class="sb-avatar sb-avatar-mat" title="Ressource matérielle">
      {{ ({Véhicule:'🚛',Outil:'🔧',Salle:'🏢',Équipement:'📦',Nacelle:'🏗️',Grue:'🏗️',Fusionneuse:'🔧',OTDR:'📡'})[tech.resourceCategory||tech.fullName] || '🔧' }}
    </div>
    <div v-else class="sb-avatar" :style="'background:'+TECH_COLORS[tech.colorIdx]">
      {{ tech.fullName.split(' ').map(n=>n[0]).join('').toUpperCase().slice(0,2) }}
    </div>
    <div class="sb-res-info">
      <div class="sb-res-name">{{ tech.fullName }}
        <span v-for="t in (tech.tags||[]).slice(0,3)" :key="t" class="sb-res-tag-dot" :style="'background:'+getTagColor(t)" :title="t"></span>
      </div>
      <div class="sb-res-sub">
        <span class="sb-st" :class="stOf(tech).cls">{{ stOf(tech).label }}</span>
        <span v-if="tech.status === 'off' && tech.absenceReason" class="sb-res-absence-tag">{{ tech.absenceReason }}</span>
        <span class="sb-load">{{ fmtDur(periodLoadH(tech)) }}/{{ fmtDur(techPeriodCapacityH(tech)) }}</span>
      </div>
      <div class="sb-util-bar">
        <div class="sb-util-fill" :style="{ width: Math.min(100,periodLoadH(tech)/techPeriodCapacityH(tech)*100)+'%', background: dayLoadColor(periodLoadH(tech)/techPeriodCapacityH(tech)) }"></div>
      </div>
      <!-- Hover action overlay -->
      <div class="sb-res-actions">
        <button @click.stop="emit('open-tech-tags', tech)" title="Tags / Skills">#</button>
        <button @click.stop="emit('open-schedule', tech)" title="Horaire hebdo">🗓</button>
        <button v-if="tech.status !== 'off'" @click.stop="emit('open-absence', tech)" title="Mettre en absence">⏸</button>
        <button v-else @click.stop="emit('end-absence', tech)" title="Fin d'absence" class="sb-act-play">▶</button>
      </div>
    </div>
  </div>

  <!-- Timeline -->
  <div class="sb-timeline" :style="'width:'+totalW+'px'"
       @dragover.prevent="emit('timeline-dragover', $event, tech)"
       @dragleave="emit('timeline-dragleave', $event)"
       @drop.prevent="emit('timeline-drop', $event, tech)">
    <!-- Hour guides -->
    <div v-for="tick in hourTicks.filter(t=>!t.isDay)" :key="'hg-'+tick.x"
         class="sb-hour-guide" :style="'left:'+tick.x+'px'"></div>
    <template v-for="h in (hEnd - hStart)" :key="'qg-'+h">
      <div v-for="q in [1,2,3]" :key="'q-'+h+'-'+q" class="sb-quarter-guide"
           :style="'left:'+(((h + q*0.25) * pxPerHr))+'px'"></div>
    </template>
    <div class="sb-capacity-line" :style="'left:'+((techDayEndH(tech) - hStart) * pxPerHr)+'px'" :title="fmtDur(techPeriodCapacityH(tech))"></div>
    <div v-if="dropGhostX!=null" class="sb-drop-line" :style="'left:'+dropGhostX+'px'"></div>

    <!-- Shift availability background blocks (only in planning mode) -->
    <template v-if="planningMode" v-for="seg in segments.filter(s => s.type === 'shift')" :key="'shift-'+seg.startH+(seg.isOnCall?'-oncall':'')">
      <div class="sb-block-shift" :class="{ 'sb-block-shift-oncall': seg.isOnCall }" :style="seg.style" :title="seg.label + ' — cliquer pour modifier'"
           style="pointer-events:auto;cursor:pointer" @click.stop="emit('open-schedule', tech)">
        <span class="sb-shift-label">{{ seg.label }}</span>
      </div>
    </template>

    <template v-for="seg in segments.filter(s => s.type !== 'shift' && !(s._isDayOff && !planningMode))" :key="seg.type+'-'+(seg.job?.id||'x')+(seg.isAssist?'-a':'')+(seg.type==='travel'?'-t':'')">
      <!-- Absence block -->
      <div v-if="seg.type==='absence'" class="sb-block sb-block-absence" :style="seg.style"
           :title="`${seg.reasonIcon} ${seg.reasonLabel}${seg.until && seg.until !== seg.from ? ' ('+seg.from+' → '+seg.until+')' : ''}`">
        <div class="sb-absence-inner">
          <span class="sb-absence-icon">{{ seg.reasonIcon }}</span>
          <span class="sb-absence-label">{{ seg.reasonLabel }}</span>
          <span v-if="seg.until && seg.until !== seg.from" class="sb-absence-dates">{{ seg.from }} → {{ seg.until }}</span>
        </div>
        <div class="sb-resize-handle sb-resize-left" @mousedown.stop.prevent="emit('absence-resize', $event, seg, tech, 'left')"></div>
        <div class="sb-resize-handle" @mousedown.stop.prevent="emit('absence-resize', $event, seg, tech, 'right')"></div>
      </div>
      <!-- Travel -->
      <div v-else-if="seg.type==='travel'" class="sb-travel-trail"
           :class="[seg.fromRoute?'sb-travel-route':'sb-travel-est', seg.isAssist?'sb-travel-assist':'']"
           :style="{ ...seg.style, background:seg.color+(seg.fromRoute?'40':'22'), borderLeft:'2px solid '+seg.color+(seg.fromRoute?'88':'44') }">
        <span v-if="parseFloat(seg.style.width)>36" class="sb-travel-lbl">{{ seg.fromRoute?'':'~' }}{{ seg.travelMin }}min</span>
      </div>
      <!-- Assist block -->
      <div v-else-if="seg.type==='assist'" class="sb-block sb-block-assist"
           :class="{ 'sb-block-assist-pinned':seg.assistPinned, 'sb-block-sel':selectedJob?.isAssist&&selectedJob?.job?.id===seg.job.id&&selectedJob?.assistTechId===seg.assistTechId, 'sb-block-linked':(selectedJob?.job?.id===seg.job.id&&!selectedJob?.isAssist)||hoveredJobId===seg.job.id }"
           :style="{ ...seg.style, background:((selectedJob?.job?.id===seg.job.id&&!selectedJob?.isAssist)||hoveredJobId===seg.job.id)?jobColor(seg.job)+'dd':(seg.assistPinned?jobColor(seg.job)+'99':jobColor(seg.job)+'44') }"
           :draggable="seg.assistPinned?'true':'false'"
           @dragstart="seg.assistPinned && emit('job-dragstart',$event,seg.job,tech.id,true)"
           @mouseenter="emit('hover-job',seg.job.id)" @mouseleave="emit('unhover-job')"
           @click.stop="emit('job-click',seg.job,seg.job.assignedTech,true,seg.assistTechId,$event)"
           @dblclick.stop="emit('job-dblclick',seg.job)"
           @contextmenu.prevent="emit('assist-ctx',$event,seg.job,seg.assistTechId)">
        <div class="sb-block-color-bar" :style="'background:'+jobColor(seg.job)"></div>
        <div class="sb-block-inner">
          <div class="sb-block-title"><span v-if="seg.assistPinned" class="sb-block-pin" title="Priorisé" v-html="ICON.pin"></span>{{ seg.assistNote||seg.job.subject }}</div>
          <div class="sb-block-meta">{{ fmtDur(seg.assistDur) }} · {{ seg.job.subject }}{{ seg.job.address?' · '+shortAddr(seg.job.address):'' }}</div>
        </div>
        <div class="sb-resize-handle" @mousedown.stop.prevent="emit('block-resize',$event,seg.job,'assist',seg.assistTechId)"></div>
      </div>
      <!-- Job block -->
      <!-- Ghost (recurring) block -->
      <div v-else-if="seg._isGhost" class="sb-block sb-block-ghost"
           :style="{ ...seg.style, background:jobColor(seg.job)+'44', borderColor:jobColor(seg.job)+'88' }"
           @click.stop="emit('ghost-click',seg._templateJob,seg.job.scheduledDate,tech.id)"
           @dblclick.stop="emit('ghost-materialize',seg._templateJob,seg.job.scheduledDate,tech.id)">
        <div class="sb-block-color-bar" :style="'background:'+jobColor(seg.job)+'88'"></div>
        <div class="sb-block-inner">
          <div class="sb-block-title"><span class="sb-ghost-icon">🔄</span> {{ seg.job.subject }}</div>
          <div class="sb-block-meta">{{ fmtDur(seg.job.duration) }} · récurrent</div>
        </div>
      </div>
      <!-- Regular job block -->
      <div v-else class="sb-block"
           :class="{ 'sb-block-done':seg.job.status==='completed', 'sb-block-draft':!seg.job.published, 'sb-block-sel':selectedJob?.job?.id===seg.job.id&&!selectedJob?.isAssist, 'sb-block-multi':isJobMultiSelected(seg.job.id), 'sb-block-linked':selectedJob?.job?.id===seg.job.id&&selectedJob?.isAssist, 'sb-block-team':seg.job.assistants?.length }"
           :style="{ ...seg.style, background:jobColor(seg.job)+'dd' }"
           :data-job-id="seg.job.id" draggable="true"
           @dragstart="emit('job-dragstart',$event,seg.job,tech.id,false)"
           @mouseenter="emit('hover-job',seg.job.id)" @mouseleave="emit('unhover-job')"
           @click.stop="emit('job-click',seg.job,tech.id,false,null,$event)"
           @dblclick.stop="emit('job-dblclick',seg.job)"
           @contextmenu.prevent="emit('job-ctx',$event,seg.job,tech.id)">
        <div class="sb-move-handle" @mousedown.stop.prevent="emit('block-move',$event,seg.job,$event.target.parentElement)" title="Déplacer"></div>
        <div class="sb-block-color-bar" :style="'background:'+jobColor(seg.job)"></div>
        <div class="sb-block-inner">
          <div class="sb-block-title"><span v-if="seg.pinned" class="sb-block-pin" title="Heure fixée" v-html="ICON.pin"></span>{{ seg.job.subject }}</div>
          <div class="sb-block-meta">{{ seg.pinnedTime||'' }}{{ seg.pinnedTime?' · ':'' }}{{ fmtDur(seg.job.duration) }}</div>
          <div v-if="seg.job.address" class="sb-block-addr"><span v-html="ICON.mapPin"></span> {{ shortAddr(seg.job.address) }}</div>
        </div>
        <div v-if="seg.job.assistants?.length" class="sb-block-assistants">
          <span v-for="a in seg.job.assistants" :key="a.techId" class="sb-assist-badge"
                :style="'background:'+TECH_COLORS[$root?.$store?.technicians?.find(t=>t.id===a.techId)?.colorIdx||0]"
                :title="a.techName">{{ (a.techName||'').split(' ').map(n=>n[0]).join('').toUpperCase().slice(0,2) }}</span>
        </div>
        <span v-if="jobStatusIcon(seg.job).svg" class="sb-block-status-icon" :class="jobStatusIcon(seg.job).cls" :title="seg.job.status" v-html="jobStatusIcon(seg.job).svg"></span>
        <div class="sb-resize-handle" @mousedown.stop.prevent="emit('block-resize',$event,seg.job,'job')"></div>
      </div>
    </template>
  </div>
</div>
</template>
