<script setup lang="ts">
/**
 * Detail panel for the current board selection: an order (truck) or an
 * allocation link (ribbon). For a ready SO it hosts the one-click shipment
 * generation button (same iDempiere process the SO edit page uses).
 */
import type { CdLink, CdOrder } from '~/composables/useCrossdockBoard'

const board = inject('cdBoard') as ReturnType<typeof useCrossdockBoard>
const tabs = useTabs()

const sel = computed(() => board.selection.value)

const selectedOrder = computed<CdOrder | null>(() => {
  if (sel.value?.type !== 'order' || !sel.value.id) return null
  return (sel.value.lane === 'in'
    ? board.inboundById.value[sel.value.id]
    : board.outboundById.value[sel.value.id]) ?? null
})
const selectedLink = computed<CdLink | null>(() => {
  if (sel.value?.type !== 'link') return null
  return board.links.value.find(l =>
    l.poOrderId === sel.value?.poOrderId && l.soOrderId === sel.value?.soOrderId
  ) ?? null
})

const orderLinks = computed<CdLink[]>(() => {
  if (!selectedOrder.value || !sel.value?.lane) return []
  return board.linksForOrder(sel.value.lane, selectedOrder.value.id)
})

const linkPo = computed(() => selectedLink.value ? board.inboundById.value[selectedLink.value.poOrderId] : null)
const linkSo = computed(() => selectedLink.value ? board.outboundById.value[selectedLink.value.soOrderId] : null)

const confirmingDelete = ref(false)
watch(sel, () => { confirmingDelete.value = false })

const openOrderPage = (lane: 'in' | 'out', id: number) => {
  const link = lane === 'in' ? `/procurements/orders/${id}/edit` : `/sales/orders/${id}/edit`
  tabs.value.push({ link, text: lane === 'in' ? 'Edit Order' : 'Edit Order' })
  navigateTo(link)
}

const fmtDate = (v: any) => {
  const d = board.parseDate(v)
  if (!d) return '—'
  return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}.${d.getFullYear()}`
}

const stateBadge = (o: CdOrder, lane: 'in' | 'out') => {
  if (lane === 'in') return o.received ? { text: 'Ware eingetroffen', cls: 'is-success' } : { text: 'Erwartet', cls: 'is-info is-light' }
  const s = board.soLinkState(o.id)
  if (s === 'ready') return { text: 'Bereit zum Versand', cls: 'is-success' }
  if (s === 'partial') return { text: 'Teilweise eingetroffen', cls: 'is-warning' }
  if (s === 'planned') return { text: 'Cross-Dock geplant', cls: 'is-info is-light' }
  return { text: 'Offen', cls: 'is-light' }
}

const generateFor = (soId: number) => {
  const so = board.outboundById.value[soId]
  if (so) board.generateShipment(so)
}
</script>

<template>
  <aside class="cdsp box">
    <!-- nothing selected -->
    <template v-if="!selectedOrder && !selectedLink">
      <p class="cdsp__hintTitle"><span class="ti ti-hand-click mr-1"></span> So funktioniert's</p>
      <ul class="cdsp__hints">
        <li><span class="ti ti-arrows-horizontal"></span> LKW horizontal ziehen → Termin (DatePromised) ändern</li>
        <li><span class="ti ti-link"></span> Eingangs-LKW auf Ausgangs-LKW ziehen → Cross-Dock Zuordnung</li>
        <li><span class="ti ti-click"></span> LKW oder Verbindung anklicken → Details hier im Panel</li>
        <li><span class="ti ti-truck-loading"></span> Ware eingetroffen → Auftrag leuchtet grün, Versand per Klick</li>
      </ul>
    </template>

    <!-- order selected -->
    <template v-else-if="selectedOrder">
      <div class="cdsp__head">
        <span class="cdsp__laneTag" :class="sel?.lane === 'in' ? 'cdsp__laneTag--in' : 'cdsp__laneTag--out'">
          <span :class="sel?.lane === 'in' ? 'ti ti-truck-delivery' : 'ti ti-truck'"></span>
          {{ sel?.lane === 'in' ? 'Wareneingang' : 'Warenausgang' }}
        </span>
        <span class="tag" :class="stateBadge(selectedOrder, sel!.lane!).cls">{{ stateBadge(selectedOrder, sel!.lane!).text }}</span>
      </div>

      <h3 class="cdsp__doc">{{ selectedOrder.documentNo }}</h3>
      <p class="cdsp__partner">{{ selectedOrder.partnerName }}</p>

      <div class="cdsp__facts">
        <div><span class="cdsp__k">Termin</span><span class="cdsp__v">{{ fmtDate(selectedOrder.datePromised) }}</span></div>
        <div><span class="cdsp__k">Bestellt</span><span class="cdsp__v">{{ fmtDate(selectedOrder.dateOrdered) }}</span></div>
        <div><span class="cdsp__k">Lager</span><span class="cdsp__v">{{ selectedOrder.warehouseName || '—' }}</span></div>
        <div><span class="cdsp__k">Organisation</span><span class="cdsp__v">{{ selectedOrder.orgName }}</span></div>
        <div><span class="cdsp__k">Positionen</span><span class="cdsp__v">{{ selectedOrder.lineCount }} ({{ selectedOrder.totalQty }} Stk, offen {{ selectedOrder.openQty }})</span></div>
      </div>

      <div v-if="selectedOrder.isUnfulfillable" class="notification is-warning is-light cdsp__note">
        <span class="ti ti-alert-triangle mr-1"></span> Bestand reicht aktuell nicht — Cross-Dock Kandidat!
      </div>

      <!-- links of this order -->
      <p class="cdsp__section">Cross-Dock Verknüpfungen</p>
      <p v-if="!orderLinks.length" class="cdsp__emptyLinks">Keine — LKW auf einen LKW der anderen Spur ziehen.</p>
      <button
        v-for="l in orderLinks"
        :key="l.poOrderId + '-' + l.soOrderId"
        type="button"
        class="cdsp__linkRow"
        @click="board.selection.value = { type: 'link', poOrderId: l.poOrderId, soOrderId: l.soOrderId }"
      >
        <span class="ti" :class="l.arrived ? 'ti-circle-check cdsp__ok' : 'ti-clock'"></span>
        <span class="cdsp__linkDocs">
          {{ board.inboundById.value[l.poOrderId]?.documentNo ?? '#' + l.poOrderId }}
          →
          {{ board.outboundById.value[l.soOrderId]?.documentNo ?? '#' + l.soOrderId }}
        </span>
        <span class="tag is-rounded" :class="l.arrived ? 'is-success' : 'is-light'">{{ l.coveragePct }}%</span>
      </button>

      <!-- ready-to-ship action on the SO -->
      <template v-if="sel?.lane === 'out' && board.soLinkState(selectedOrder.id) === 'ready'">
        <div class="notification is-success is-light cdsp__note">
          <span class="ti ti-truck-loading mr-1"></span> Ware eingetroffen — Auftrag kann versendet werden.
        </div>
        <button
          type="button"
          class="button is-success is-fullwidth"
          :class="{ 'is-loading': board.generateStatus.value[selectedOrder.id] === 'loading' }"
          :disabled="board.generateStatus.value[selectedOrder.id] === 'success'"
          @click="board.generateShipment(selectedOrder)"
        >
          <span class="ti ti-file-export mr-1"></span>
          {{ board.generateStatus.value[selectedOrder.id] === 'success' ? 'Lieferschein erstellt' : 'Lieferschein generieren' }}
        </button>
        <p class="cdsp__caveat">
          Hinweis: erstellt Lieferscheine für <strong>alle offenen Aufträge</strong> dieses Partners in diesem Lager.
        </p>
      </template>

      <button type="button" class="button is-small is-fullwidth cdsp__open" @click="openOrderPage(sel!.lane!, selectedOrder.id)">
        <span class="ti ti-external-link mr-1"></span> Beleg öffnen
      </button>
    </template>

    <!-- link selected -->
    <template v-else-if="selectedLink">
      <div class="cdsp__head">
        <span class="cdsp__laneTag cdsp__laneTag--link"><span class="ti ti-link"></span> Cross-Dock Zuordnung</span>
        <span class="tag" :class="selectedLink.arrived ? 'is-success' : 'is-light'">
          {{ selectedLink.arrived ? 'Ware eingetroffen' : 'Geplant' }}
        </span>
      </div>

      <div class="cdsp__linkPair">
        <div>
          <p class="cdsp__k">Eingang</p>
          <p class="cdsp__doc cdsp__doc--sm">{{ linkPo?.documentNo ?? '#' + selectedLink.poOrderId }}</p>
          <p class="cdsp__partner">{{ linkPo?.partnerName }}</p>
        </div>
        <span class="ti ti-arrow-down cdsp__pairArrow"></span>
        <div>
          <p class="cdsp__k">Ausgang</p>
          <p class="cdsp__doc cdsp__doc--sm">{{ linkSo?.documentNo ?? '#' + selectedLink.soOrderId }}</p>
          <p class="cdsp__partner">{{ linkSo?.partnerName }}</p>
        </div>
      </div>

      <div class="cdsp__coverage">
        <div class="cdsp__coverageBar">
          <div class="cdsp__coverageFill" :class="{ 'cdsp__coverageFill--ok': selectedLink.arrived }" :style="{ width: selectedLink.coveragePct + '%' }"></div>
        </div>
        <span class="cdsp__coverageText">{{ selectedLink.coveragePct }}% Deckung ({{ selectedLink.qtyAllocated }} / {{ selectedLink.soOpenTotal }} Stk)</span>
      </div>

      <table class="table is-fullwidth is-narrow cdsp__table">
        <thead>
          <tr><th>Produkt</th><th class="has-text-right">Zugeord.</th><th class="has-text-right">Offen SO</th></tr>
        </thead>
        <tbody>
          <tr v-for="p in selectedLink.products" :key="p.allocId">
            <td>{{ p.productName }}</td>
            <td class="has-text-right">{{ p.qtyAllocated }}</td>
            <td class="has-text-right">
              {{ p.soOpenQty }}
              <span v-if="p.qtyAllocated > p.soOpenQty || p.qtyAllocated > p.poOpenQty" class="ti ti-alert-triangle cdsp__stale" title="Zuordnung übersteigt offene Menge — Mengen haben sich geändert"></span>
            </td>
          </tr>
        </tbody>
      </table>

      <button
        type="button"
        class="button is-small is-fullwidth"
        @click="board.openAllocation(selectedLink.poOrderId, selectedLink.soOrderId)"
      >
        <span class="ti ti-pencil mr-1"></span> Zuordnung bearbeiten
      </button>

      <template v-if="selectedLink.arrived && linkSo && board.soLinkState(linkSo.id) === 'ready'">
        <button
          type="button"
          class="button is-success is-fullwidth mt-2"
          :class="{ 'is-loading': board.generateStatus.value[linkSo.id] === 'loading' }"
          @click="generateFor(linkSo.id)"
        >
          <span class="ti ti-file-export mr-1"></span> Lieferschein generieren
        </button>
      </template>

      <template v-if="!confirmingDelete">
        <button type="button" class="button is-small is-danger is-outlined is-fullwidth mt-2" @click="confirmingDelete = true">
          <span class="ti ti-unlink mr-1"></span> Verknüpfung entfernen
        </button>
      </template>
      <template v-else>
        <div class="cdsp__confirm">
          <span>Wirklich entfernen?</span>
          <button type="button" class="button is-small is-danger" @click="board.removeLink(selectedLink)">Ja, entfernen</button>
          <button type="button" class="button is-small" @click="confirmingDelete = false">Abbrechen</button>
        </div>
      </template>
    </template>
  </aside>
</template>

<style scoped>
.cdsp {
  width: 312px;
  flex: 0 0 312px;
  align-self: flex-start;
  padding: 16px;
  max-height: calc(100vh - 220px);
  overflow-y: auto;
}

.cdsp__hintTitle {
  font-weight: 700;
  margin-bottom: 10px;
}
.cdsp__hints {
  display: flex;
  flex-direction: column;
  gap: 10px;
  font-size: 0.82rem;
  color: var(--theme-text-secondary, #7a8194);
}
.cdsp__hints li {
  display: flex;
  gap: 8px;
  align-items: flex-start;
}
.cdsp__hints .ti {
  margin-top: 1px;
}

.cdsp__head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}
.cdsp__laneTag {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 0.72rem;
  font-weight: 700;
  letter-spacing: 0.5px;
  text-transform: uppercase;
  padding: 3px 8px;
  border-radius: 6px;
  color: #ffffff;
}
.cdsp__laneTag--in { background: linear-gradient(#42628c, #2c4661); }
.cdsp__laneTag--out { background: linear-gradient(#6a5da8, #4a3f7d); }
.cdsp__laneTag--link { background: linear-gradient(#5c6577, #434b5a); }

.cdsp__doc {
  font-size: 1.15rem;
  font-weight: 700;
  margin-bottom: 0;
}
.cdsp__doc--sm { font-size: 0.95rem; }
.cdsp__partner {
  color: var(--theme-text-secondary, #7a8194);
  font-size: 0.85rem;
  margin-bottom: 10px;
}

.cdsp__facts {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 10px;
}
.cdsp__facts > div {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  font-size: 0.83rem;
}
.cdsp__k {
  color: var(--theme-text-secondary, #7a8194);
}
.cdsp__v {
  font-weight: 600;
  text-align: right;
}

.cdsp__note {
  padding: 8px 10px;
  font-size: 0.82rem;
  margin-bottom: 10px;
}
.cdsp__section {
  font-size: 0.72rem;
  font-weight: 700;
  letter-spacing: 0.6px;
  text-transform: uppercase;
  color: var(--theme-text-secondary, #7a8194);
  margin: 12px 0 6px;
}
.cdsp__emptyLinks {
  font-size: 0.8rem;
  color: var(--theme-text-secondary, #9aa1b3);
  margin-bottom: 8px;
}
.cdsp__linkRow {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  padding: 6px 8px;
  margin-bottom: 4px;
  border: 1px solid var(--theme-border, #e3e5ea);
  border-radius: 8px;
  background: transparent;
  cursor: pointer;
  font-size: 0.8rem;
  color: inherit;
}
.cdsp__linkRow:hover {
  border-color: #4a5fc1;
}
.cdsp__linkDocs {
  flex: 1;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.cdsp__ok { color: #22a559; }

.cdsp__caveat {
  font-size: 0.72rem;
  color: var(--theme-text-secondary, #9aa1b3);
  margin-top: 6px;
}
.cdsp__open {
  margin-top: 12px;
}

.cdsp__linkPair {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 10px;
}
.cdsp__pairArrow {
  color: var(--theme-text-secondary, #9aa1b3);
  margin-left: 4px;
}

.cdsp__coverage {
  margin-bottom: 12px;
}
.cdsp__coverageBar {
  height: 8px;
  border-radius: 4px;
  background: var(--theme-bg-secondary, #eef0f4);
  overflow: hidden;
  margin-bottom: 4px;
}
.cdsp__coverageFill {
  height: 100%;
  border-radius: 4px;
  background: #8b93a7;
  transition: width 0.4s ease;
}
.cdsp__coverageFill--ok { background: #22a559; }
.cdsp__coverageText {
  font-size: 0.78rem;
  color: var(--theme-text-secondary, #7a8194);
}
.cdsp__table {
  font-size: 0.8rem;
}
.cdsp__stale {
  color: #e8a13c;
  margin-left: 4px;
}
.cdsp__confirm {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.8rem;
  margin-top: 8px;
  flex-wrap: wrap;
}
</style>
