<script setup>
// Document-quality onboarding report: an archival record of every entity created and the
// exact values set, for filing alongside the merchant contract. Renders on-screen detail
// cards + a status summary, and produces a polished multi-section PDF (download / print).
const props = defineProps({
  result: { type: Object, required: true },
  details: { type: Array, default: () => [] },
  isGerman: { type: Boolean, default: false }
})

const user = useCookie('logship_user')
const createdBy = computed(() => user.value?.Name || user.value?.identifier || 'SUPERUSER')

const rows = computed(() => props.result?.report || [])
const meta = computed(() => props.result?.meta || {})
const ok = computed(() => Number(props.result?.status) === 200)
const loginUrl = computed(() => meta.value?.loginUrl || 'https://app.logship.de')
const companyName = computed(() => meta.value?.companyName || '')
const shortName = computed(() => meta.value?.shortName || '')

const createdAtLabel = computed(() => {
  const iso = meta.value?.createdAt
  if (!iso) return ''
  try {
    const d = new Date(iso)
    const p = (n) => String(n).padStart(2, '0')
    return `${p(d.getDate())}.${p(d.getMonth() + 1)}.${d.getFullYear()} ${p(d.getHours())}:${p(d.getMinutes())}`
  } catch { return iso }
})

const statusClass = (s) => s === 'success' ? 'is-ok' : (s === 'error' ? 'is-err' : 'is-skip')
const statusLabel = (s) => {
  if (s === 'success') return props.isGerman ? 'Erstellt' : 'Created'
  if (s === 'error') return props.isGerman ? 'Fehler' : 'Failed'
  return props.isGerman ? 'Übersprungen' : 'Skipped'
}
const t = (de, en) => (props.isGerman ? de : en)

// ---- PDF ------------------------------------------------------------------------------
const loadPdfMake = async () => {
  const pdfMakeModule = await import('pdfmake/build/pdfmake.js')
  const pdfFontsModule = await import('pdfmake/build/vfs_fonts.js')
  const pdfMake = pdfMakeModule.default || pdfMakeModule
  let vfs = null
  if (pdfFontsModule.pdfMake?.vfs) vfs = pdfFontsModule.pdfMake.vfs
  else if (pdfFontsModule.default?.pdfMake?.vfs) vfs = pdfFontsModule.default.pdfMake.vfs
  else if (pdfFontsModule.default?.vfs) vfs = pdfFontsModule.default.vfs
  else if (pdfFontsModule.default) {
    const keys = Object.keys(pdfFontsModule.default)
    if (keys.some(k => k.endsWith('.ttf'))) vfs = pdfFontsModule.default
  }
  pdfMake.vfs = vfs
  return pdfMake
}

const buildPdf = async () => {
  const pdfMake = await loadPdfMake()
  const accent = '#2563eb'

  // per-entity sections: a coloured header bar + a 2-col key/value table
  const sectionBlocks = []
  for (const sec of props.details) {
    sectionBlocks.push({
      table: { widths: ['*'], body: [[{
        text: [
          { text: sec.title, bold: true, color: '#1e3a8a' },
          { text: `   ${sec.entity}${sec.id ? '  ·  ID ' + sec.id : ''}`, color: '#64748b', fontSize: 7.5 }
        ],
        fillColor: '#eef4ff', margin: [8, 5, 8, 5]
      }]] },
      layout: 'noBorders',
      margin: [0, 12, 0, 0]
    })
    if (sec.fields?.length) {
      sectionBlocks.push({
        table: {
          widths: [165, '*'],
          body: sec.fields.map((f) => [
            { text: f.label, style: 'k' },
            { text: f.value ?? '—', style: 'v' }
          ])
        },
        layout: {
          hLineWidth: () => 0.5, vLineWidth: () => 0,
          hLineColor: () => '#eaecef',
          fillColor: (rowIndex) => (rowIndex % 2 ? '#f8fafc' : null),
          paddingLeft: () => 8, paddingRight: () => 8, paddingTop: () => 4, paddingBottom: () => 4
        },
        margin: [0, 2, 0, 0]
      })
    }
  }

  // closing "records created" summary
  const summaryBody = [[
    { text: '#', style: 'th' }, { text: t('Objekt', 'Entity'), style: 'th' },
    { text: 'ID', style: 'th' }, { text: 'Status', style: 'th' }
  ]]
  for (const r of rows.value) {
    summaryBody.push([
      { text: String(r.step ?? ''), style: 'td' },
      { text: `${r.entity}${r.label ? ' — ' + r.label : ''}`, style: 'td' },
      { text: r.id != null ? String(r.id) : '—', style: 'td' },
      { text: statusLabel(r.status), style: 'td' }
    ])
  }

  const docDefinition = {
    pageSize: 'A4',
    pageMargins: [40, 78, 40, 54],
    header: () => ({
      margin: [40, 22, 40, 0],
      stack: [
        {
          columns: [
            { text: 'LogShip', bold: true, color: accent, fontSize: 13 },
            { text: t('Händler-Onboarding · Datensatz', 'Merchant Onboarding · Record'), alignment: 'right', color: '#64748b', fontSize: 9, margin: [0, 3, 0, 0] }
          ]
        },
        { canvas: [{ type: 'line', x1: 0, y1: 6, x2: 515, y2: 6, lineWidth: 1, lineColor: accent }] }
      ]
    }),
    footer: (currentPage, pageCount) => ({
      margin: [40, 12, 40, 0],
      columns: [
        { text: `${t('Erstellt', 'Generated')}: ${createdAtLabel.value}  ·  ${createdBy.value}  ·  LogYou`, color: '#94a3b8', fontSize: 7.5 },
        { text: `${currentPage} / ${pageCount}`, alignment: 'right', color: '#94a3b8', fontSize: 7.5 }
      ]
    }),
    content: [
      { text: companyName.value || shortName.value, style: 'docTitle' },
      { text: `${t('Kurzname', 'Short name')}: ${shortName.value}`, style: 'docSub', margin: [0, 1, 0, 10] },
      {
        table: {
          widths: ['*', '*', '*'],
          body: [[
            { text: [{ text: t('Erstellt von\n', 'Created by\n'), color: '#94a3b8', fontSize: 7.5 }, { text: createdBy.value, bold: true }], border: [false, false, false, false] },
            { text: [{ text: t('Datum\n', 'Date\n'), color: '#94a3b8', fontSize: 7.5 }, { text: createdAtLabel.value, bold: true }], border: [false, false, false, false] },
            { text: [{ text: 'Login\n', color: '#94a3b8', fontSize: 7.5 }, { text: loginUrl.value, bold: true, color: accent }], border: [false, false, false, false] }
          ]]
        },
        layout: { fillColor: () => '#f8fafc', paddingLeft: () => 10, paddingRight: () => 10, paddingTop: () => 8, paddingBottom: () => 8 },
        margin: [0, 0, 0, 6]
      },
      ...sectionBlocks,
      { text: t('Angelegte Datensätze', 'Records created'), style: 'sectionTitle', margin: [0, 16, 0, 4] },
      {
        table: { headerRows: 1, widths: [18, '*', 50, 60], body: summaryBody, dontBreakRows: true },
        layout: {
          hLineWidth: () => 0.5, vLineWidth: () => 0.5, hLineColor: () => '#e5e7eb', vLineColor: () => '#e5e7eb',
          fillColor: (i) => (i === 0 ? '#eef4ff' : null), paddingLeft: () => 5, paddingRight: () => 5, paddingTop: () => 3, paddingBottom: () => 3
        }
      }
    ],
    styles: {
      docTitle: { fontSize: 17, bold: true, color: '#0f172a' },
      docSub: { fontSize: 9.5, color: '#64748b' },
      sectionTitle: { fontSize: 11, bold: true, color: '#1e3a8a' },
      k: { fontSize: 8.5, color: '#64748b' },
      v: { fontSize: 8.5, color: '#0f172a', bold: true },
      th: { fontSize: 8, bold: true, color: '#1e3a8a' },
      td: { fontSize: 8 }
    },
    defaultStyle: { fontSize: 9, color: '#1f2937' }
  }
  return pdfMake.createPdf(docDefinition)
}

const fileName = computed(() => {
  const sn = (shortName.value || 'merchant').replace(/[^A-Za-z0-9]/g, '')
  return `Merchant-Onboarding-${sn}.pdf`
})
const downloadPdf = async () => { (await buildPdf()).download(fileName.value) }
const printPdf = async () => { (await buildPdf()).print() }
</script>

<template>
  <div class="mo-report">
    <div class="mo-banner" :class="ok ? 'is-ok' : 'is-err'">
      <span :class="ok ? 'ti ti-circle-check' : 'ti ti-alert-triangle'" class="mo-banner-icon"></span>
      <div>
        <strong>
          {{ ok ? t('Händler erfolgreich angelegt', 'Merchant created successfully')
                : t('Onboarding mit Fehler gestoppt', 'Onboarding stopped with an error') }}
        </strong>
        <div class="mo-banner-sub">{{ companyName }} ({{ shortName }})</div>
        <div v-if="!ok && result?.message" class="mo-banner-sub">{{ result.message }}</div>
      </div>
      <div class="mo-banner-actions">
        <button type="button" class="mo-btn mo-btn-primary" @click="downloadPdf"><span class="ti ti-download"></span> {{ t('PDF', 'PDF') }}</button>
        <button type="button" class="mo-btn" @click="printPdf"><span class="ti ti-printer"></span> {{ t('Drucken', 'Print') }}</button>
      </div>
    </div>

    <div class="mo-meta">
      <span>{{ t('Erstellt von', 'Created by') }}: <strong>{{ createdBy }}</strong></span>
      <span>{{ t('Datum', 'Date') }}: <strong>{{ createdAtLabel }}</strong></span>
      <span>Login: <a :href="loginUrl" target="_blank">{{ loginUrl }}</a></span>
    </div>

    <!-- full per-entity detail (every value that was set) -->
    <div class="mo-detail-grid">
      <div v-for="(sec, i) in details" :key="i" class="mo-detail-card">
        <div class="mo-detail-head">
          <span class="mo-detail-title">{{ sec.title }}</span>
          <span class="mo-detail-entity">{{ sec.entity }}<template v-if="sec.id"> · ID {{ sec.id }}</template></span>
        </div>
        <dl class="mo-kv">
          <div v-for="(f, j) in sec.fields" :key="j"><dt>{{ f.label }}</dt><dd>{{ f.value || '—' }}</dd></div>
          <div v-if="!sec.fields.length" class="mo-kv-empty">—</div>
        </dl>
      </div>
    </div>

    <!-- status summary -->
    <h4 class="mo-sum-title">{{ t('Angelegte Datensätze', 'Records created') }}</h4>
    <table class="mo-table">
      <thead>
        <tr><th>#</th><th>{{ t('Objekt', 'Entity') }}</th><th>{{ t('Name', 'Name') }}</th><th>ID</th><th>Status</th></tr>
      </thead>
      <tbody>
        <tr v-for="(r, i) in rows" :key="i" :class="statusClass(r.status)">
          <td>{{ r.step }}</td>
          <td><div class="mo-entity">{{ r.entity }}</div><div class="mo-entity-sub">{{ r.label }}</div></td>
          <td>{{ r.name || '—' }}</td>
          <td>{{ r.id != null ? r.id : '—' }}</td>
          <td>
            <span class="mo-badge" :class="statusClass(r.status)">{{ statusLabel(r.status) }}</span>
            <div v-if="r.message" class="mo-msg">{{ r.message }}</div>
            <div v-else-if="r.detail" class="mo-detail-note">{{ r.detail }}</div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.mo-report { max-width: 960px; }
.mo-banner { display: flex; align-items: flex-start; gap: 12px; padding: 16px; border-radius: 12px; margin-bottom: 16px; }
.mo-banner.is-ok { background: #ecfdf5; border: 1px solid #a7f3d0; color: #065f46; }
.mo-banner.is-err { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
.mo-banner-icon { font-size: 1.7rem; line-height: 1; }
.mo-banner-sub { font-size: 0.85rem; opacity: 0.9; }
.mo-banner-actions { margin-left: auto; display: flex; gap: 8px; }
.mo-btn { display: inline-flex; align-items: center; gap: 6px; padding: 7px 12px; border-radius: 8px; font-size: 0.82rem; font-weight: 600; cursor: pointer; border: 1px solid var(--theme-border, #d1d5db); background: #fff; color: #374151; }
.mo-btn-primary { background: #2563eb; border-color: #2563eb; color: #fff; }
.mo-btn:hover { filter: brightness(0.97); }

.mo-meta { display: flex; flex-wrap: wrap; gap: 18px; font-size: 0.85rem; color: #555; margin-bottom: 16px; }
.mo-meta a { color: #2563eb; }

.mo-detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; margin-bottom: 22px; }
@media (max-width: 720px) { .mo-detail-grid { grid-template-columns: 1fr; } }
.mo-detail-card { border: 1px solid var(--theme-border, #e5e7eb); border-radius: 12px; overflow: hidden; background: var(--theme-surface, #fff); }
.mo-detail-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; padding: 9px 14px; background: #eef4ff; border-bottom: 1px solid #dbe5ff; }
.mo-detail-title { font-weight: 700; color: #1e3a8a; font-size: 0.92rem; }
.mo-detail-entity { font-size: 0.72rem; color: #64748b; font-family: monospace; }
.mo-kv { padding: 6px 14px 10px; }
.mo-kv > div { display: flex; justify-content: space-between; gap: 14px; padding: 5px 0; border-bottom: 1px dashed var(--theme-border, #eef0f3); font-size: 0.83rem; }
.mo-kv > div:last-child { border-bottom: none; }
.mo-kv dt { color: #6b7280; flex-shrink: 0; }
.mo-kv dd { font-weight: 600; text-align: right; word-break: break-word; }
.mo-kv-empty { justify-content: center !important; color: #9ca3af; }

.mo-sum-title { font-weight: 700; font-size: 0.98rem; margin: 4px 0 10px; color: var(--theme-text-primary, #1e293b); }
.mo-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
.mo-table th, .mo-table td { border: 1px solid var(--theme-border, #e5e7eb); padding: 8px 10px; text-align: left; vertical-align: top; }
.mo-table th { background: #eef4ff; font-weight: 600; color: #1e3a8a; }
.mo-entity { font-weight: 600; }
.mo-entity-sub { font-size: 0.76rem; color: #6b7280; }
.mo-badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 0.74rem; font-weight: 600; }
.mo-badge.is-ok { background: #d1fae5; color: #065f46; }
.mo-badge.is-err { background: #fee2e2; color: #991b1b; }
.mo-badge.is-skip { background: #e5e7eb; color: #4b5563; }
.mo-msg { font-size: 0.76rem; color: #991b1b; margin-top: 3px; }
.mo-detail-note { font-size: 0.76rem; color: #6b7280; margin-top: 3px; }
tr.is-err td { background: rgba(254, 226, 226, 0.35); }
</style>
