<script setup>
/**
 * Two-step dunning gate, mounted globally in app.vue (outside <NuxtPage>).
 *
 * Driven by two Yes-No flags on the org's linked C_BPartner
 * (via /api/invoices/termination-status):
 *  - IsTerminationNotice → dismissible warning modal, re-shown once per login
 *    (keyed on the server session), listing the partner's open invoices.
 *  - IsTerminated → permanent full-screen block on every route except
 *    /fulfillment/invoices (so invoice PDFs stay downloadable) until the flag
 *    is cleared. Only "view invoices" and logout are possible.
 *
 * Applies only to limited fulfillment-customer roles (menu type 'c') —
 * LogYou staff are never blocked so they can still service a flagged org.
 */
const route = useRoute()
const status = useTerminationStatus()
const { t, lang } = useTranslation()
const { getMenuType } = useRoleMenu()

const orgIdCookie = useCookie('logship_organization_id')
const userCookie = useCookie('logship_user')

const GUEST_PATHS = ['/signin', '/select-role', '/login', '/register', '/verify-email', '/forgot-password', '/reset-password']
const NOTICE_SEEN_KEY = 'logship_termination_notice_seen'
const ALLOWED_TERMINATED_PATH = '/fulfillment/invoices'
const RECHECK_MS = 60000

const isExcludedRoute = computed(() => GUEST_PATHS.includes(route.path) || route.path.startsWith('/tracking'))

const isEligible = computed(() =>
  !isExcludedRoute.value
  && !!orgIdCookie.value
  && !!userCookie.value?.id
  && getMenuType() === 'c'
)

const fetching = ref(false)
let lastFetchAt = 0

const fetchStatus = async (force = false) => {
  if (!isEligible.value || fetching.value) return
  if (!force && Date.now() - lastFetchAt < RECHECK_MS) return
  fetching.value = true
  try {
    const res = await $fetch('/api/invoices/termination-status', {
      headers: useRequestHeaders(['cookie'])
    })
    // Only accept the expected shape — an error payload must not flip the gate.
    if (res && typeof res.notice !== 'undefined' && typeof res.terminated !== 'undefined') {
      status.value = res
      lastFetchAt = Date.now()
    }
  } catch (err) {
    // Fail-soft: keep the previous state; an API hiccup must never lock users
    // out or pop a false modal.
  }
  fetching.value = false
}

onMounted(() => { fetchStatus(true) })
watch(() => route.path, () => { fetchStatus(false) })
watch(() => orgIdCookie.value, () => {
  status.value = null
  lastFetchAt = 0
  fetchStatus(true)
})

// --- Notice modal (step 1): once per login session ---
const dismissTick = ref(0)
const sessionMarker = computed(() => status.value?.sessionKey || 'no-session')

const noticeVisible = computed(() => {
  dismissTick.value // re-evaluate after dismiss
  if (!isEligible.value || !status.value?.notice || status.value?.terminated) return false
  if (typeof localStorage === 'undefined') return false
  return localStorage.getItem(NOTICE_SEEN_KEY) !== sessionMarker.value
})

const dismissNotice = () => {
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem(NOTICE_SEEN_KEY, sessionMarker.value)
  }
  dismissTick.value++
}

// --- Terminated modal (step 2): permanent block ---
const terminatedVisible = computed(() =>
  isEligible.value
  && !!status.value?.terminated
  && !route.path.startsWith(ALLOWED_TERMINATED_PATH)
)

watch(terminatedVisible, (val) => {
  if (typeof document === 'undefined') return
  document.body.style.overflow = val ? 'hidden' : ''
}, { immediate: true })

onUnmounted(() => {
  if (typeof document !== 'undefined') document.body.style.overflow = ''
})

const goToInvoices = () => {
  navigateTo(ALLOWED_TERMINATED_PATH)
}

const logout = async () => {
  try {
    await $fetch('/api/idempiere-auth/logout', { method: 'POST', headers: useRequestHeaders(['cookie']) })
  } catch (err) {}
  location.href = '/signin'
}

// --- Formatting (locale follows the active UI language) ---
const invoices = computed(() => status.value?.invoices || [])

const formatDate = (d) => {
  if (!d) return ''
  try {
    return new Date(d).toLocaleDateString(lang.value || 'de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
  } catch (err) {
    return d
  }
}

const formatAmount = (v, currency) => {
  try {
    return Number(v || 0).toLocaleString(lang.value || 'de-DE', { style: 'currency', currency: currency || 'EUR' })
  } catch (err) {
    return v
  }
}

const totalOpenFormatted = computed(() =>
  formatAmount(status.value?.totalOpen, invoices.value[0]?.currency)
)
</script>

<template>
  <div>
    <!-- Step 1: termination notice (last reminder) — dismissible, once per login -->
    <div v-if="noticeVisible" class="tg-overlay">
      <div class="tg-container tg-container--notice">
        <div class="tg-header tg-header--notice">
          <span class="tg-header__icon tg-header__icon--notice"><i class="ti ti-alert-triangle"></i></span>
          <h3>{{ t?.termination_notice_title || 'Zahlung überfällig — letzte Mahnung' }}</h3>
        </div>
        <div class="tg-body">
          <p class="tg-text">{{ t?.termination_notice_text || 'Trotz vorheriger Mahnungen sind die folgenden Rechnungen weiterhin unbezahlt. Dies ist die letzte Mahnung vor der Kündigung: Wird der offene Betrag nicht beglichen, werden Ihr Konto und alle Services bis zum Zahlungseingang gesperrt.' }}</p>
          <h4 class="tg-subtitle">{{ t?.termination_open_invoices || 'Offene Rechnungen' }}</h4>
          <table v-if="invoices.length" class="tg-table">
            <thead>
              <tr>
                <th>{{ t?.invoice_no || 'Rechnungsnummer' }}</th>
                <th>{{ t?.invoice_date || 'Rechnungsdatum' }}</th>
                <th class="tg-num">{{ t?.termination_open_amount || 'Offener Betrag' }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="inv in invoices" :key="inv.id">
                <td>{{ inv.documentNo }}</td>
                <td>{{ formatDate(inv.dateInvoiced) }}</td>
                <td class="tg-num">{{ formatAmount(inv.openAmt, inv.currency) }}</td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="2">{{ t?.termination_total_open || 'Offener Gesamtbetrag' }}</td>
                <td class="tg-num">{{ totalOpenFormatted }}</td>
              </tr>
            </tfoot>
          </table>
          <p class="tg-contact">{{ t?.termination_contact_note || 'Sollten Sie die Zahlung bereits geleistet haben, kontaktieren Sie uns bitte.' }}</p>
        </div>
        <div class="tg-footer">
          <button type="button" class="button" @click="goToInvoices(); dismissNotice()">
            <i class="ti ti-file-invoice me-1"></i> {{ t?.termination_view_invoices || 'Offene Rechnungen ansehen' }}
          </button>
          <button type="button" class="button is-warning" @click="dismissNotice">
            <i class="ti ti-check me-1"></i> {{ t?.termination_understood || 'Verstanden' }}
          </button>
        </div>
      </div>
    </div>

    <!-- Step 2: terminated — permanent block, no close, only invoices + logout -->
    <div v-if="terminatedVisible" class="tg-overlay tg-overlay--terminated">
      <div class="tg-container tg-container--terminated">
        <div class="tg-header tg-header--terminated">
          <span class="tg-header__icon tg-header__icon--terminated"><i class="ti ti-lock"></i></span>
          <h3>{{ t?.termination_final_title || 'Konto gesperrt' }}</h3>
        </div>
        <div class="tg-body">
          <p class="tg-text">{{ t?.termination_final_text || 'Ihr Konto wurde aufgrund offener Zahlungen gesperrt. LogShip kann erst wieder genutzt werden, wenn die unten aufgeführten offenen Rechnungen vollständig bezahlt wurden. Nach Zahlungseingang wird der Zugang wieder freigeschaltet.' }}</p>
          <h4 class="tg-subtitle">{{ t?.termination_open_invoices || 'Offene Rechnungen' }}</h4>
          <table v-if="invoices.length" class="tg-table">
            <thead>
              <tr>
                <th>{{ t?.invoice_no || 'Rechnungsnummer' }}</th>
                <th>{{ t?.invoice_date || 'Rechnungsdatum' }}</th>
                <th class="tg-num">{{ t?.termination_open_amount || 'Offener Betrag' }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="inv in invoices" :key="inv.id">
                <td>{{ inv.documentNo }}</td>
                <td>{{ formatDate(inv.dateInvoiced) }}</td>
                <td class="tg-num">{{ formatAmount(inv.openAmt, inv.currency) }}</td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="2">{{ t?.termination_total_open || 'Offener Gesamtbetrag' }}</td>
                <td class="tg-num">{{ totalOpenFormatted }}</td>
              </tr>
            </tfoot>
          </table>
          <p class="tg-contact">{{ t?.termination_contact_note || 'Sollten Sie die Zahlung bereits geleistet haben, kontaktieren Sie uns bitte.' }}</p>
        </div>
        <div class="tg-footer">
          <button type="button" class="button is-danger is-outlined" @click="logout">
            <i class="ti ti-logout me-1"></i> {{ t?.logout || 'Abmelden' }}
          </button>
          <button type="button" class="button is-primary" @click="goToInvoices">
            <i class="ti ti-file-invoice me-1"></i> {{ t?.termination_view_invoices || 'Offene Rechnungen ansehen' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.tg-overlay {
  position: fixed;
  inset: 0;
  background: rgba(20, 24, 33, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999;
  padding: 20px;
}
.tg-overlay--terminated {
  z-index: 100000;
  background: rgba(20, 24, 33, 0.78);
  backdrop-filter: blur(3px);
}
.tg-container {
  background: #fff;
  border-radius: 12px;
  width: 100%;
  max-width: 640px;
  max-height: calc(100vh - 40px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.35);
  animation: tgPop 140ms ease-out;
}
@keyframes tgPop {
  from { transform: translateY(10px) scale(0.98); opacity: 0; }
  to { transform: translateY(0) scale(1); opacity: 1; }
}
.tg-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1.1rem 1.25rem;
}
.tg-header h3 {
  margin: 0;
  font-size: 1.15rem;
  font-weight: 700;
}
.tg-header--notice {
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6c2 100%);
  border-bottom: 1px solid #f1d6a4;
}
.tg-header--notice h3 { color: #6b3a00; }
.tg-header--terminated {
  background: linear-gradient(135deg, #fdeaea 0%, #f8c9c9 100%);
  border-bottom: 1px solid #eba9a9;
}
.tg-header--terminated h3 { color: #7a1212; }
.tg-header__icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 2.4rem;
  height: 2.4rem;
  border-radius: 50%;
  background: #fff;
  font-size: 1.2rem;
  flex-shrink: 0;
}
.tg-header__icon--notice { color: #d97800; box-shadow: 0 2px 6px rgba(217, 120, 0, 0.25); }
.tg-header__icon--terminated { color: #c22525; box-shadow: 0 2px 6px rgba(194, 37, 37, 0.25); }
.tg-body {
  padding: 1.25rem;
  overflow-y: auto;
  flex: 1;
}
.tg-text {
  margin: 0 0 1rem;
  color: #333;
  font-size: 0.95rem;
  line-height: 1.5;
}
.tg-subtitle {
  margin: 0 0 0.5rem;
  font-size: 0.9rem;
  font-weight: 700;
  color: #555;
  text-transform: uppercase;
  letter-spacing: 0.03em;
}
.tg-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}
.tg-table th,
.tg-table td {
  padding: 0.45rem 0.6rem;
  border-bottom: 1px solid #eee;
  text-align: left;
  color: #2d2a25;
}
.tg-table thead th {
  background: #f7f9fc;
  font-weight: 700;
  color: #555;
}
.tg-table tfoot td {
  font-weight: 700;
  border-top: 2px solid #ddd;
  border-bottom: none;
}
.tg-num { text-align: right !important; white-space: nowrap; }
.tg-contact {
  margin: 0;
  color: #6b7280;
  font-size: 0.85rem;
}
.tg-footer {
  padding: 0.9rem 1.25rem;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 0.6rem;
  flex-wrap: wrap;
}
@media (max-width: 520px) {
  .tg-footer { justify-content: stretch; flex-direction: column; }
  .tg-footer .button { width: 100%; }
}
</style>
