<script setup lang="ts">
definePageMeta({ ssr: false })
usePageTitle('Book of Business')

const { data, pending } = usePolicy('/policies', {
  query: {
    'page_size': 100
  }
})

const policies = computed(() => data.value?.data ?? [])

const totalGWP = computed(() => policies.value.reduce((s, p) => s + (p.premium || 0), 0))
const activePolicies = computed(() => policies.value.filter((p) => p.status === 'issued').length)
const avgPremium = computed(() => {
  const count = policies.value.length
  return count > 0 ? Math.round(totalGWP.value / count) : 0
})

function fmtMoney(n: number) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(n)
}

function formatDate(d: string) {
  if (!d) return '—'
  return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
}

function policyApplicantName(p: any) {
  const info = p.insured
  if (!info || typeof info !== 'object') return '—'
  if (info.type === 'corporate') {
    return info.company_name || '—'
  }
  return info.name || '—'
}

function policyDetailsSummary(p: any) {
  const d = p.policy_details
  if (!d || typeof d !== 'object') return '—'
  if (p.policy_type === 'car') {
    const parts = [d.year, d.make, d.model].filter((x: any) => x !== undefined && x !== null && String(x) !== '')
    return parts.length ? parts.map(String).join(' ') : '—'
  }
  if (p.policy_type === 'life') {
    return `Life · ${d.coverage_amount || 0} USD`
  }
  if (p.policy_type === 'fire_structure' || p.policy_type === 'fire_contents') {
    return d.location || '—'
  }
  return '—'
}

function statusColor(status: string) {
  switch (status) {
    case 'quote_requested': return 'yellow'
    case 'quotes_received': return 'blue'
    case 'solicitation_sent': return 'purple'
    case 'issued': return 'green'
    default: return 'gray'
  }
}

function statusLabel(status: string) {
  switch (status) {
    case 'quote_requested': return 'Quote Requested'
    case 'quotes_received': return 'Quotes Received'
    case 'solicitation_sent': return 'Solicitation Sent'
    case 'issued': return 'Issued'
    default: return status
  }
}
</script>

<template>
  <div class="bk-root mx-auto max-w-6xl space-y-6 pb-12">
    <div class="flex items-start justify-between">
      <div>
        <h1 class="mt-1 text-2xl font-semibold tracking-tight text-[var(--text-primary)]">Book of Business</h1>
        <p class="mt-1 text-[13px] text-[var(--text-muted)]">
          Consolidated view of all policies
        </p>
      </div>
      <div class="flex items-center gap-2">
        <NuxtLink to="/policies">
          <button class="bk-btn-secondary">
            <UIcon name="i-heroicons-arrow-left" class="w-3.5 h-3.5" />
            All Policies
          </button>
        </NuxtLink>
      </div>
    </div>

    <div v-if="pending" class="bk-card">
      <div style="padding: 20px;">
        <div v-for="n in 8" :key="n" class="pol-skeleton-row">
          <div class="pol-skeleton" style="width: 80px; height: 12px;" />
          <div class="pol-skeleton" style="width: 140px; height: 12px;" />
          <div class="pol-skeleton" style="width: 50px; height: 18px; border-radius: 10px;" />
          <div class="pol-skeleton" style="width: 100px; height: 12px;" />
          <div class="pol-skeleton" style="width: 100px; height: 12px;" />
          <div class="pol-skeleton" style="width: 70px; height: 12px;" />
          <div class="pol-skeleton" style="width: 50px; height: 18px; border-radius: 10px;" />
          <div class="pol-skeleton" style="width: 80px; height: 12px;" />
          <div class="pol-skeleton" style="width: 60px; height: 12px;" />
        </div>
      </div>
    </div>

    <template v-else>
      <div class="bk-kpi-strip">
        <div class="bk-kpi-item">
          <span class="bk-kpi-label">Total Book GWP</span>
          <span class="bk-kpi-value">{{ fmtMoney(totalGWP) }}<span class="bk-kpi-suffix">/yr</span></span>
        </div>
        <div class="bk-kpi-divider" />
        <div class="bk-kpi-item">
          <span class="bk-kpi-label">Active Policies</span>
          <span class="bk-kpi-value">{{ activePolicies }}</span>
        </div>
        <div class="bk-kpi-divider" />
        <div class="bk-kpi-item">
          <span class="bk-kpi-label">Avg Premium</span>
          <span class="bk-kpi-value">{{ fmtMoney(avgPremium) }}</span>
        </div>
      </div>

      <div class="bk-card bk-card-flush">
        <div class="bk-card-head">
          <span>Policies</span>
          <span class="bk-card-head-count">{{ policies.length }}</span>
        </div>
        <div class="bk-table-wrap">
          <table class="bk-table">
            <thead>
              <tr>
                <th class="bk-th">Applicant</th>
                <th class="bk-th">Type</th>
                <th class="bk-th">Details</th>
                <th class="bk-th">Status</th>
                <th class="bk-th">Submitted</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="policy in policies" :key="policy.application_id" class="bk-row">
                <td class="bk-td">
                  <p class="bk-text-primary">{{ policyApplicantName(policy) }}</p>
                </td>
                <td class="bk-td">
                  <span class="bk-text-muted capitalize">{{ policy.policy_type }}</span>
                </td>
                <td class="bk-td">
                  <span class="bk-text-muted">{{ policyDetailsSummary(policy) }}</span>
                </td>
                <td class="bk-td">
                  <span
                    class="bk-status-badge"
                    :class="`bk-status-${statusColor(policy.status)}`"
                  >{{ statusLabel(policy.status) }}</span>
                </td>
                <td class="bk-td">
                  <span class="bk-renewal-date">{{ formatDate(policy.submitted_at) }}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div v-if="policies.length === 0" class="bk-empty">
          <UIcon name="i-heroicons-document-text" class="w-10 h-10" style="color: #8a8a86; opacity: 0.5;" />
          <p class="bk-empty-title">No policies found</p>
          <p class="bk-empty-sub">Create a new policy to get started</p>
        </div>
      </div>
    </template>
  </div>
</template>

<style scoped>
.bk-root {
  --bk-brand: #01696f;
  --bk-brand-soft: rgba(1, 105, 111, 0.06);
  --bk-border: rgba(0, 0, 0, 0.06);
  --bk-border-strong: rgba(0, 0, 0, 0.08);
  --bk-muted: #8a8a86;
  --bk-surface: #ffffff;
}

.bk-card {
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
}
.bk-card-flush {
  overflow: hidden;
}
.bk-card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
}
.bk-card-head-count {
  font-size: 11px;
  font-weight: 600;
  color: #8a8a86;
  background: rgba(0, 0, 0, 0.04);
  padding: 2px 8px;
  border-radius: 10px;
}

.bk-kpi-strip {
  display: flex;
  align-items: center;
  gap: 0;
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  padding: 16px 0;
}
.bk-kpi-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.bk-kpi-label {
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: #8a8a86;
}
.bk-kpi-value {
  font-size: 22px;
  font-weight: 700;
  color: var(--text-primary, #1a1a1a);
  letter-spacing: -0.01em;
}
.bk-kpi-suffix {
  font-size: 13px;
  font-weight: 500;
  color: #8a8a86;
  margin-left: 2px;
}
.bk-kpi-divider {
  width: 1px;
  height: 36px;
  background: rgba(0, 0, 0, 0.06);
  flex-shrink: 0;
}

.bk-btn-secondary {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 7px 14px;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  cursor: pointer;
  transition: all 150ms ease;
}
.bk-btn-secondary:hover {
  border-color: rgba(1, 105, 111, 0.2);
  color: #01696f;
}

.bk-table-wrap {
  overflow-x: auto;
}
.bk-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}
.bk-th {
  padding: 10px 16px;
  text-align: left;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: #8a8a86;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  white-space: nowrap;
}
.bk-td {
  padding: 12px 16px;
  vertical-align: middle;
  border-bottom: 1px solid rgba(0, 0, 0, 0.03);
}
.bk-row {
  transition: background 120ms ease;
}
.bk-row:hover {
  background: rgba(0, 0, 0, 0.015);
}
.bk-row:last-child .bk-td {
  border-bottom: none;
}

.bk-text-primary {
  font-size: 13px;
  color: var(--text-primary, #1a1a1a);
}
.bk-text-muted {
  font-size: 13px;
  color: var(--text-muted, #5c5650);
}

.bk-status-badge {
  display: inline-block;
  font-size: 10px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 10px;
  white-space: nowrap;
}
.bk-status-yellow { background: rgba(245, 158, 11, 0.1); color: #d97706; }
.bk-status-blue { background: rgba(59, 130, 246, 0.1); color: #2563eb; }
.bk-status-purple { background: rgba(139, 92, 246, 0.1); color: #7c3aed; }
.bk-status-green { background: rgba(16, 185, 129, 0.1); color: #059669; }
.bk-status-gray { background: rgba(0, 0, 0, 0.05); color: #8a8a86; }

.bk-renewal-date {
  font-size: 12px;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}

.bk-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48px 20px;
  text-align: center;
}
.bk-empty-title {
  margin-top: 12px;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
}
.bk-empty-sub {
  margin-top: 4px;
  font-size: 12px;
  color: #8a8a86;
}

.pol-skeleton-row {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 10px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.03);
}
.pol-skeleton-row:last-child { border-bottom: none; }
.pol-skeleton {
  height: 12px;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.05);
  animation: pol-pulse 1.5s ease-in-out infinite;
}
@keyframes pol-pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}
</style>
