<script setup>
/**
 * Parcel-contents modal (sales-order edit page).
 *
 * Shows the multi-parcel commission allocation stored in
 * M_InOut.commission_parcels_json: per parcel — tracking number, total weight
 * and the articles scanned into it, grouped by the scanned/label code
 * (FBA printLabelCode when used, else SKU). PDF download via pdfmake (A4).
 */
import { toast } from 'bulma-toast'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  shipment: {
    // { id, DocumentNo, commission_parcels_json }
    type: Object,
    default: () => ({})
  },
  orderDocumentNo: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

const { t } = useTranslation()
const { parseParcelContents, groupParcelItems, parcelTotals, formatCreatedAt, buildParcelContentsDoc } = useParcelContentsDoc()

const busy = ref(false)

const contents = computed(() => parseParcelContents(props.shipment?.commission_parcels_json))
const totals = computed(() => contents.value ? parcelTotals(contents.value) : { parcels: 0, pieces: 0, weight: 0 })

const close = () => emit('update:modelValue', false)

const stamp = () => new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14)
const fileName = () => `${props.shipment?.DocumentNo || props.shipment?.id}-PAKETINHALT-${stamp()}.pdf`

const download = async () => {
  if (!contents.value) return
  busy.value = true
  try {
    const pdf = await buildParcelContentsDoc(contents.value, props.shipment?.DocumentNo || '', props.orderDocumentNo || '')
    pdf.download(fileName())
  } catch (err) {
    toast({ message: err?.message || 'PDF generation failed', type: 'is-danger', duration: 3000 })
  } finally {
    busy.value = false
  }
}
</script>

<template>
  <Teleport to="body">
    <div v-if="modelValue" class="pcm-overlay" @click.self="close">
      <div class="pcm-dialog">
        <div class="pcm-head">
          <h3 class="pcm-title">
            <span class="tf-icon ti ti-packages ti-sm me-1"></span>
            {{ t?.parcel_contents || 'Paketinhalt' }} — {{ shipment?.DocumentNo }}
          </h3>
          <button type="button" class="pcm-close" @click="close"><i class="ti ti-x"></i></button>
        </div>

        <p v-if="contents" class="pcm-sub">
          {{ totals.parcels }} {{ t?.parcels || 'Pakete' }} ·
          {{ totals.pieces }} {{ t?.articles || 'Artikel' }} ·
          {{ totals.weight.toFixed(2) }} kg
          <template v-if="formatCreatedAt(contents.createdAt)">
            · {{ t?.commissioned_at || 'Kommissioniert' }}: {{ formatCreatedAt(contents.createdAt) }}
          </template>
        </p>

        <div v-if="!contents" class="pcm-empty">
          <i class="ti ti-mood-empty"></i>
          <span>{{ t?.no_parcel_contents || 'Keine Paketinhalts-Daten vorhanden' }}</span>
        </div>

        <div v-else class="pcm-body">
          <div v-for="parcel in contents.parcels" :key="parcel.no" class="pcm-parcel">
            <div class="pcm-parcel-head">
              <span class="pcm-parcel-no"><i class="ti ti-package"></i> {{ t?.parcel || 'Paket' }} {{ parcel.no }}</span>
              <span v-if="parcel.trackingNo" class="pcm-parcel-tracking" :title="parcel.trackingNo">
                <i class="ti ti-truck-delivery"></i> {{ parcel.trackingNo }}
              </span>
              <span class="pcm-parcel-weight"><i class="ti ti-weight"></i> {{ Number(parcel.weight || 0).toFixed(2) }} kg</span>
            </div>
            <table class="pcm-table">
              <thead>
                <tr>
                  <th>{{ t?.code || 'Code' }}</th>
                  <th>{{ t?.article || 'Artikel' }}</th>
                  <th>SKU</th>
                  <th class="pcm-num">{{ t?.quantity || 'Menge' }}</th>
                  <th class="pcm-num">kg</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, ri) in groupParcelItems(parcel)" :key="ri">
                  <td>
                    <span class="pcm-code" :class="{ 'pcm-code--label': row.isLabelCode }">{{ row.code }}</span>
                  </td>
                  <td>{{ row.name }}</td>
                  <td>{{ row.sku }}</td>
                  <td class="pcm-num pcm-qty">{{ row.qty }}</td>
                  <td class="pcm-num">{{ Number(row.weight || 0).toFixed(2) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="pcm-actions">
          <button type="button" class="button" :disabled="busy" @click="close">{{ t?.close || 'Schließen' }}</button>
          <button type="button" class="button is-primary" :class="{ 'is-loading': busy }" :disabled="busy || !contents" @click="download">
            <span class="tf-icon ti ti-download ti-xs me-1"></span>
            {{ t?.download || 'Download' }} (PDF)
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<!-- Teleported markup — styles must be non-scoped (teleport + scoped CSS is unreliable) -->
<style>
.pcm-overlay {
  position: fixed;
  inset: 0;
  z-index: 10000;
  background: rgba(15, 23, 42, 0.55);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
}
.pcm-dialog {
  background: var(--theme-bg-primary, #fff);
  color: var(--theme-text-primary, #0f172a);
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  width: min(720px, 100%);
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  padding: 20px 22px;
}
.pcm-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}
.pcm-title { font-size: 1.1rem; font-weight: 700; display: flex; align-items: center; margin: 0; }
.pcm-close {
  border: none;
  background: transparent;
  color: var(--theme-text-secondary, #64748b);
  cursor: pointer;
  font-size: 1.1rem;
  padding: 4px;
}
.pcm-close:hover { color: var(--theme-text-primary, #0f172a); }
.pcm-sub { font-size: 0.85rem; color: var(--theme-text-secondary, #64748b); margin: 2px 0 12px; }
.pcm-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  padding: 28px;
  color: var(--theme-text-secondary, #64748b);
}
.pcm-empty i { font-size: 1.6rem; }
.pcm-body { overflow-y: auto; }
.pcm-parcel {
  border: 1px solid var(--theme-border, #e2e8f0);
  border-radius: 10px;
  margin-bottom: 12px;
  overflow: hidden;
}
.pcm-parcel-head {
  display: flex;
  align-items: center;
  gap: 14px;
  flex-wrap: wrap;
  padding: 8px 12px;
  background: var(--theme-bg-secondary, #f8fafc);
  border-bottom: 1px solid var(--theme-border, #e2e8f0);
  font-size: 0.85rem;
}
.pcm-parcel-no { font-weight: 700; display: inline-flex; align-items: center; gap: 5px; }
.pcm-parcel-tracking {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-family: monospace;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 240px;
}
.pcm-parcel-weight { margin-left: auto; display: inline-flex; align-items: center; gap: 5px; font-weight: 600; }
.pcm-table { width: 100%; border-collapse: collapse; font-size: 0.83rem; }
.pcm-table th, .pcm-table td {
  padding: 6px 12px;
  text-align: left;
  border-bottom: 1px solid var(--theme-border, #eef2f7);
}
.pcm-table thead th {
  font-size: 0.72rem;
  text-transform: uppercase;
  letter-spacing: 0.03em;
  color: var(--theme-text-secondary, #64748b);
  background: var(--theme-bg-secondary, #f8fafc);
}
.pcm-table tbody tr:last-child td { border-bottom: none; }
.pcm-num { text-align: right !important; white-space: nowrap; }
.pcm-qty { font-weight: 700; }
.pcm-code { font-family: monospace; font-size: 0.82rem; word-break: break-all; }
.pcm-code--label {
  font-weight: 700;
  background: rgba(50, 115, 220, 0.12);
  border-radius: 4px;
  padding: 1px 6px;
}
.pcm-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 14px; }
[data-mode="dark"] .pcm-dialog { background: var(--theme-bg-primary, #1e293b); }
[data-mode="dark"] .pcm-code--label { background: rgba(96, 165, 250, 0.2); }
</style>
