<script setup>
const visible = useMarketplaceConfirmLog()
const param = useMarketplaceConfirmLogParam()

const fetching = ref(false)
const fetchedLog = ref('')

const close = () => {
  visible.value = false
}

const parsed = computed(() => {
  const raw = (param.value?.logBlob ?? fetchedLog.value ?? '').toString().trim()
  if (!raw) return null
  try {
    return JSON.parse(raw)
  } catch {
    return { _unparseable: true, raw }
  }
})

const formatTimestamp = (iso) => {
  if (!iso) return ''
  try {
    const d = new Date(iso)
    return d.toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' })
  } catch {
    return iso
  }
}

const prettyPayload = computed(() => {
  if (!parsed.value) return ''
  const payload = parsed.value.resp ?? parsed.value.error ?? parsed.value
  try {
    return typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2)
  } catch {
    return String(payload)
  }
})

const loadIfNeeded = async () => {
  if (!visible.value) return
  if (param.value?.logBlob) {
    fetchedLog.value = ''
    return
  }
  const orderId = param.value?.fetchOrderId
  if (!orderId) {
    fetchedLog.value = ''
    return
  }
  fetching.value = true
  try {
    const res = await $fetch(`/api/inouts/${orderId}/order`, {
      headers: useRequestHeaders(['cookie'])
    })
    fetchedLog.value = (res?.marketplace_confirm_log || '').toString()
  } catch (err) {
    console.error('Failed to load marketplace confirm log', err)
    fetchedLog.value = ''
  } finally {
    fetching.value = false
  }
}

watch(visible, (v) => {
  if (v) loadIfNeeded()
  else fetchedLog.value = ''
})

const onKey = (e) => {
  if (e.key === 'Escape' && visible.value) close()
}

onMounted(() => {
  window.addEventListener('keydown', onKey)
})
onUnmounted(() => {
  window.removeEventListener('keydown', onKey)
})

const copyPayload = async () => {
  try {
    await navigator.clipboard.writeText(prettyPayload.value)
  } catch (err) {
    console.error('Copy failed', err)
  }
}
</script>

<template>
  <div v-if="visible" class="mcl-overlay" @click.self="close">
    <div class="mcl-container" @click.stop>
      <div class="mcl-header">
        <div class="mcl-header__title">
          <span class="mcl-header__icon"><i class="ti ti-list-details"></i></span>
          <div>
            <h3>Marketplace Confirmation Log</h3>
            <p v-if="param?.documentNo || param?.trackingNo" class="mcl-header__sub">
              <span v-if="param.documentNo">{{ param.documentNo }}</span>
              <span v-if="param.documentNo && param.trackingNo"> · </span>
              <span v-if="param.trackingNo">{{ param.trackingNo }}</span>
            </p>
          </div>
        </div>
        <button type="button" class="mcl-close" @click="close" title="Schließen">
          <i class="ti ti-x"></i>
        </button>
      </div>

      <div class="mcl-body">
        <div v-if="fetching" class="mcl-loading">
          <i class="ti ti-loader-2 mcl-spin"></i> Lade Log…
        </div>

        <div v-else-if="!parsed" class="mcl-empty">
          <i class="ti ti-info-circle"></i>
          <p>Keine Marketplace-Bestätigungs-Antwort gespeichert.</p>
          <p class="mcl-empty__hint">
            Wird automatisch befüllt, sobald die nächste Bestätigung dieses Versands an den Marketplace gesendet wird.
          </p>
        </div>

        <template v-else>
          <div class="mcl-meta">
            <div class="mcl-meta__row">
              <span class="mcl-meta__label">Marketplace</span>
              <span class="mcl-meta__value">{{ parsed.marketplace || '–' }}</span>
            </div>
            <div class="mcl-meta__row">
              <span class="mcl-meta__label">Endpoint</span>
              <span class="mcl-meta__value mcl-mono">{{ parsed.endpoint || '–' }}</span>
            </div>
            <div class="mcl-meta__row">
              <span class="mcl-meta__label">Zeitpunkt</span>
              <span class="mcl-meta__value">{{ formatTimestamp(parsed.at) }}</span>
            </div>
            <div class="mcl-meta__row">
              <span class="mcl-meta__label">Status</span>
              <span
                class="mcl-status"
                :class="parsed.ok ? 'mcl-status--ok' : 'mcl-status--err'"
              >
                <i :class="parsed.ok ? 'ti ti-check' : 'ti ti-alert-triangle'"></i>
                {{ parsed.ok ? 'OK (Laravel hat 2xx geliefert)' : (parsed._unparseable ? 'Nicht parsebar' : 'Fehler / leere Antwort') }}
              </span>
            </div>
          </div>

          <div class="mcl-payload-header">
            <span>{{ parsed.error !== undefined ? 'Fehler-Payload' : 'Antwort von Laravel' }}</span>
            <button type="button" class="mcl-copy" @click="copyPayload" title="Kopieren">
              <i class="ti ti-copy"></i>
            </button>
          </div>
          <pre class="mcl-payload">{{ prettyPayload }}</pre>
        </template>
      </div>

      <div class="mcl-footer">
        <button type="button" class="button" @click="close">
          <i class="ti ti-x me-1"></i> Schließen
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.mcl-overlay {
  position: fixed;
  inset: 0;
  background: rgba(20, 24, 33, 0.55);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 20px;
}
.mcl-container {
  background: #fff;
  border-radius: 12px;
  width: 100%;
  max-width: 720px;
  max-height: calc(100vh - 40px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
  animation: mclPop 140ms ease-out;
}
@keyframes mclPop {
  from { transform: translateY(10px) scale(0.98); opacity: 0; }
  to { transform: translateY(0) scale(1); opacity: 1; }
}
.mcl-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 1.1rem 1.25rem;
  background: linear-gradient(135deg, #eef4ff 0%, #d8e6ff 100%);
  border-bottom: 1px solid #c9d9f4;
}
.mcl-header__title {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}
.mcl-header__title h3 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 700;
  color: #1e3a8a;
}
.mcl-header__icon {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  background: #ffffff;
  color: #1e3a8a;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  border: 1px solid #c9d9f4;
}
.mcl-header__sub {
  margin: 0.15rem 0 0;
  font-size: 0.85rem;
  color: #3855a8;
  word-break: break-all;
}
.mcl-close {
  background: transparent;
  border: 0;
  font-size: 22px;
  cursor: pointer;
  color: #4b5563;
  line-height: 1;
  padding: 4px;
}
.mcl-close:hover {
  color: #111827;
}

.mcl-body {
  padding: 1.1rem 1.25rem;
  overflow-y: auto;
  flex: 1;
}

.mcl-loading {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4b5563;
  padding: 24px 0;
  justify-content: center;
}
.mcl-spin {
  animation: mclSpin 1s linear infinite;
}
@keyframes mclSpin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.mcl-empty {
  text-align: center;
  padding: 28px 12px;
  color: #6b7280;
}
.mcl-empty i {
  font-size: 36px;
  color: #9ca3af;
  margin-bottom: 8px;
  display: inline-block;
}
.mcl-empty p {
  margin: 4px 0;
  font-size: 14px;
}
.mcl-empty__hint {
  font-size: 12px;
  color: #9ca3af;
}

.mcl-meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fb;
  border: 1px solid #e8eaed;
  border-radius: 8px;
}
.mcl-meta__row {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
}
.mcl-meta__label {
  min-width: 110px;
  font-weight: 600;
  color: #6b7280;
}
.mcl-meta__value {
  color: #111827;
  word-break: break-all;
}
.mcl-mono {
  font-family: 'SF Mono', 'Fira Code', monospace;
  font-size: 12px;
}

.mcl-status {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: 700;
  font-size: 12px;
}
.mcl-status--ok {
  background: #d4f8d4;
  color: #2e7d32;
}
.mcl-status--err {
  background: #fde2e2;
  color: #c0392b;
}

.mcl-payload-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 4px 0;
  font-size: 12px;
  font-weight: 700;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}
.mcl-copy {
  background: transparent;
  border: 0;
  padding: 4px;
  cursor: pointer;
  color: #3273dc;
  font-size: 16px;
}
.mcl-copy:hover { color: #2366d1; }

.mcl-payload {
  background: #0f172a;
  color: #e5e7eb;
  border-radius: 8px;
  padding: 12px;
  font-family: 'SF Mono', 'Fira Code', monospace;
  font-size: 12px;
  line-height: 1.5;
  max-height: 360px;
  overflow: auto;
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
}

.mcl-footer {
  padding: 0.85rem 1.25rem;
  background: #f8f9fb;
  border-top: 1px solid #eef0f3;
  display: flex;
  justify-content: flex-end;
}
</style>
