<script setup lang="ts">
import { refDebounced } from '@vueuse/core'
import type { SelectItem } from '@nuxt/ui'
import { MOCK_CUSTOMERS, fmtMoney, type MockPolicy, type MockCustomer } from '~/data/mock-customers'

usePageTitle('Policies')

const page          = ref(1)
const search        = ref('')
const statusFilter  = ref<string | null>(null)
const lineFilter    = ref<string[]>([])
const carrierFilter = ref<string[]>([])
const agentFilter   = ref<string[]>([])
const channelFilter = ref<string[]>([])
const viewMode      = ref<'card' | 'list'>('card')
const sortBy        = ref<string>('renewal_asc')
const debouncedSearch = refDebounced(search, 300)

// Multi-select dropdown open states
const openDropdown = ref<string | null>(null)
function toggleDropdown(name: string) {
  openDropdown.value = openDropdown.value === name ? null : name
}
function toggleLine(val: string) {
  lineFilter.value = lineFilter.value.includes(val) ? lineFilter.value.filter(v => v !== val) : [...lineFilter.value, val]
}
function toggleCarrier(val: string) {
  carrierFilter.value = carrierFilter.value.includes(val) ? carrierFilter.value.filter(v => v !== val) : [...carrierFilter.value, val]
}
function toggleAgent(val: string) {
  agentFilter.value = agentFilter.value.includes(val) ? agentFilter.value.filter(v => v !== val) : [...agentFilter.value, val]
}
function toggleChannel(val: string) {
  channelFilter.value = channelFilter.value.includes(val) ? channelFilter.value.filter(v => v !== val) : [...channelFilter.value, val]
}
// Close dropdown on outside click
if (import.meta.client) {
  document.addEventListener('click', (e) => {
    const el = e.target as HTMLElement
    if (!el.closest('.pol-multi-dropdown')) openDropdown.value = null
  })
}

const statusItems = ref<SelectItem[]>([
  { label: 'All Statuses',      value: null              },
  { label: 'Quote Requested',   value: 'quote_requested' },
  { label: 'Quotes Received',   value: 'quotes_received' },
  { label: 'Solicitation Sent', value: 'solicitation_sent' },
  { label: 'Issued',            value: 'issued'          }
])

watch(debouncedSearch, () => { page.value = 1 })
watch(statusFilter,    () => { page.value = 1 })
watch(lineFilter,      () => { page.value = 1 }, { deep: true })
watch(carrierFilter,   () => { page.value = 1 }, { deep: true })
watch(agentFilter,     () => { page.value = 1 }, { deep: true })
watch(channelFilter,   () => { page.value = 1 }, { deep: true })

const { data, error, pending, refresh } = usePolicy('/policies', {
  query: computed(() => ({
    'page[number]': page.value,
    'page[size]': 20,
    ...(statusFilter.value && {
      'filters[0][field]': 'status',
      'filters[0][op]':    '==',
      'filters[0][value]': statusFilter.value
    }),
    ...(debouncedSearch.value && {
      [`filters[${statusFilter.value ? 1 : 0}][field]`]: 'search',
      [`filters[${statusFilter.value ? 1 : 0}][op]`]:    '==',
      [`filters[${statusFilter.value ? 1 : 0}][value]`]: debouncedSearch.value
    })
  }))
})

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

/* ── Mock fallback: flatten all policies across mock customers ── */
type FlatMockPolicy = MockPolicy & { customerName: string; customerId: string; agent: string }

const mockPolicies = computed<FlatMockPolicy[]>(() => {
  const rows: FlatMockPolicy[] = []
  for (const cust of MOCK_CUSTOMERS) {
    for (const pol of cust.policies) {
      rows.push({ ...pol, customerName: cust.name || 'Unnamed customer', customerId: cust.id, agent: cust.agent })
    }
  }
  return rows
})

const filteredMockPolicies = computed(() => {
  let rows = mockPolicies.value
  if (lineFilter.value.length > 0) {
    rows = rows.filter((p) => lineFilter.value.includes(p.line))
  }
  if (carrierFilter.value.length > 0) {
    rows = rows.filter((p) => carrierFilter.value.includes(p.carrier))
  }
  if (debouncedSearch.value) {
    const q = debouncedSearch.value.toLowerCase()
    rows = rows.filter((p) =>
      p.product.toLowerCase().includes(q) ||
      p.carrier.toLowerCase().includes(q) ||
      p.customerName.toLowerCase().includes(q) ||
      p.id.toLowerCase().includes(q)
    )
  }
  if (statusFilter.value) {
    const map: Record<string, string> = { active: 'Active', quote_requested: 'Pending', solicitation_sent: 'Pending', quotes_received: 'Pending' }
    const target = map[statusFilter.value] ?? statusFilter.value
    rows = rows.filter((p) => p.status === target)
  }
  if (agentFilter.value.length > 0) {
    rows = rows.filter((p) => agentFilter.value.includes(p.agent))
  }
  if (channelFilter.value.length > 0) {
    rows = rows.filter((p) => p.referralChannel != null && channelFilter.value.includes(p.referralChannel))
  }
  return rows
})

const usingApi  = computed(() => apiPolicies.value.length > 0)
const policies  = computed(() => usingApi.value ? apiPolicies.value : filteredMockPolicies.value)
const usingMock = computed(() => !usingApi.value && mockPolicies.value.length > 0)

/* ── Filter dropdown items ── */
const lineOptions = ['Auto', 'Home', 'Life', 'General Risk', 'Fianza']
const carrierOptions = computed(() => [...new Set(mockPolicies.value.map((p) => p.carrier))].sort())
const agentOptions = computed(() => [...new Set(mockPolicies.value.map((p) => p.agent))].sort())
const channelOptions = computed(() => [...new Set(mockPolicies.value.map((p) => p.referralChannel).filter(Boolean) as string[])].sort())

function multiLabel(selected: string[], allLabel: string) {
  if (selected.length === 0) return allLabel
  if (selected.length === 1) return selected[0]
  return `${selected.length} selected`
}

/* ── Renewal urgency ── */
function renewalUrgency(dateStr: string) {
  const now = new Date()
  const d = new Date(dateStr)
  const days = Math.round((d.getTime() - now.getTime()) / 86400000)
  if (days < -90) return { label: `${Math.abs(days)}d past`, class: 'pol-renew-expired', days }
  if (days < -30) return { label: `${Math.abs(days)}d past`, class: 'pol-renew-past', days }
  if (days < 0) return { label: `${Math.abs(days)}d past`, class: 'pol-renew-overdue', days }
  if (days <= 14) return { label: `${days}d`, class: 'pol-renew-urgent', days }
  if (days <= 30) return { label: `${days}d`, class: 'pol-renew-soon', days }
  if (days <= 90) return { label: `${days}d`, class: 'pol-renew-ok', days }
  return { label: formatDate(dateStr), class: 'pol-renew-far', days }
}

/* ── Status helpers ── */
const statusColor = (status: string) => {
  switch (status) {
    case 'quote_requested':   return 'yellow'
    case 'quotes_received':   return 'blue'
    case 'solicitation_sent': return 'purple'
    case 'issued':
    case 'active':
    case 'Active':            return 'green'
    case 'Pending':           return 'amber'
    case 'Lapsed':            return 'rose'
    case 'Cancelled':         return 'gray'
    default:                  return 'gray'
  }
}

const 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'
    case 'active':            return 'Active'
    default:                  return status
  }
}

function policyApplicantName(p: { applicant_info?: Record<string, unknown> }) {
  const info = p.applicant_info
  if (!info || typeof info !== 'object') return '—'
  const company = info.company_name
  if (typeof company === 'string' && company) return company
  const name = info.name
  if (typeof name === 'string' && name) return name
  return '—'
}

function policyApplicantDoc(p: { applicant_info?: Record<string, unknown> }) {
  const info = p.applicant_info
  if (!info || typeof info !== 'object') return '—'
  const doc = info.document_id
  if (typeof doc === 'string' && doc) return doc
  const ruc = info.ruc
  if (typeof ruc === 'string' && ruc) return ruc
  return '—'
}

function policyDetailsSummary(p: {
  policy_type: string
  policy_details?: Record<string, unknown> | null
}) {
  const d = p.policy_details
  if (!d || typeof d !== 'object') return '—'
  if (p.policy_type === 'car') {
    const y = d.year
    const make = d.make
    const model = d.model
    const parts = [y, make, model].filter((x) => x !== undefined && x !== null && String(x) !== '')
    return parts.length ? parts.map(String).join(' ') : '—'
  }
  if (p.policy_type === 'life') {
    const b = d.beneficiary
    return typeof b === 'string' && b ? `Life · ${b}` : 'Life'
  }
  if (p.policy_type === 'fire') {
    const a = d.property_address
    return typeof a === 'string' && a ? a : '—'
  }
  return '—'
}

const lineIcon = (line: string) => {
  switch (line) {
    case 'Auto':         return 'i-heroicons-truck'
    case 'Life':         return 'i-heroicons-shield-check'
    case 'Home':         return 'i-heroicons-home-modern'
    case 'General Risk': return 'i-heroicons-shield-exclamation'
    case 'Fianza':       return 'i-heroicons-document-check'
    default:             return 'i-heroicons-document'
  }
}

const formatDate = (d: string) => {
  const date = new Date(d)
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
}

/* ── Tab filter for table ── */
type TableFilter = 'all' | 'active' | 'pending' | 'lapsed' | 'cancelled'
const tableTab = ref<TableFilter>('all')

const tabFilteredPolicies = computed(() => {
  let base = filteredMockPolicies.value

  /* tab filter */
  if (tableTab.value === 'active') base = base.filter(p => p.status === 'Active')
  else if (tableTab.value === 'pending') base = base.filter(p => p.status === 'Pending')
  else if (tableTab.value === 'lapsed') base = base.filter(p => p.status === 'Lapsed')
  else if (tableTab.value === 'cancelled') base = base.filter(p => p.status === 'Cancelled')

  /* sort */
  const sorted = [...base]
  switch (sortBy.value) {
    case 'renewal_asc':
      sorted.sort((a, b) => new Date(a.renewal).getTime() - new Date(b.renewal).getTime())
      break
    case 'premium_desc':
      sorted.sort((a, b) => b.premium - a.premium)
      break
    case 'premium_asc':
      sorted.sort((a, b) => a.premium - b.premium)
      break
    case 'customer_name':
      sorted.sort((a, b) => a.customerName.localeCompare(b.customerName))
      break
  }
  return sorted
})

const tabCounts = computed(() => ({
  all: filteredMockPolicies.value.length,
  active: filteredMockPolicies.value.filter(p => p.status === 'Active').length,
  pending: filteredMockPolicies.value.filter(p => p.status === 'Pending').length,
  lapsed: filteredMockPolicies.value.filter(p => p.status === 'Lapsed').length,
  cancelled: filteredMockPolicies.value.filter(p => p.status === 'Cancelled').length,
}))

/* ── Bottom bar totals ── */
const visiblePremiumTotal = computed(() =>
  tabFilteredPolicies.value.reduce((s, p) => s + p.premium, 0)
)
</script>

<template>
  <div class="pol-root mx-auto max-w-7xl pb-12">
    <!-- Header row -->
    <div class="pol-header">
      <div class="pol-header-left">
        <h1 class="pol-title">Policies</h1>
        <span class="pol-count-badge">{{ usingMock ? mockPolicies.length : (meta?.total_count ?? 0) }}</span>
      </div>
      <div class="pol-header-right">
        <NuxtLink to="/policies/book">
          <button class="pol-btn-secondary">
            <UIcon name="i-heroicons-book-open" class="w-3.5 h-3.5" />
            Book of Business
          </button>
        </NuxtLink>
        <NuxtLink to="/policies/new">
          <button class="pol-btn-primary">
            <UIcon name="i-heroicons-plus" class="w-3.5 h-3.5" />
            New Policy
          </button>
        </NuxtLink>
      </div>
    </div>

    <!-- Filter bar -->
    <div class="pol-filter-bar">
      <div class="pol-search-wrap">
        <UIcon name="i-heroicons-magnifying-glass" class="pol-search-icon" />
        <input
          v-model="search"
          type="text"
          placeholder="Search by policy #, customer, carrier..."
          class="pol-search-input"
        />
      </div>
      <!-- Lines multi-select -->
      <div class="pol-multi-dropdown">
        <button type="button" class="pol-select" @click.stop="toggleDropdown('line')">
          {{ multiLabel(lineFilter, 'All Lines') }}
          <UIcon name="i-heroicons-chevron-down" class="pol-select-chevron" />
        </button>
        <div v-if="openDropdown === 'line'" class="pol-dropdown-panel">
          <label v-for="opt in lineOptions" :key="opt" class="pol-dropdown-option" @click.stop>
            <input type="checkbox" :checked="lineFilter.includes(opt)" @change="toggleLine(opt)" />
            <span>{{ opt }}</span>
          </label>
          <button v-if="lineFilter.length > 0" type="button" class="pol-dropdown-clear" @click.stop="lineFilter = []">Clear</button>
        </div>
      </div>

      <!-- Carriers multi-select -->
      <div class="pol-multi-dropdown">
        <button type="button" class="pol-select" @click.stop="toggleDropdown('carrier')">
          {{ multiLabel(carrierFilter, 'All Carriers') }}
          <UIcon name="i-heroicons-chevron-down" class="pol-select-chevron" />
        </button>
        <div v-if="openDropdown === 'carrier'" class="pol-dropdown-panel">
          <label v-for="opt in carrierOptions" :key="opt" class="pol-dropdown-option" @click.stop>
            <input type="checkbox" :checked="carrierFilter.includes(opt)" @change="toggleCarrier(opt)" />
            <span>{{ opt }}</span>
          </label>
          <button v-if="carrierFilter.length > 0" type="button" class="pol-dropdown-clear" @click.stop="carrierFilter = []">Clear</button>
        </div>
      </div>

      <!-- Agents multi-select -->
      <div class="pol-multi-dropdown">
        <button type="button" class="pol-select" @click.stop="toggleDropdown('agent')">
          {{ multiLabel(agentFilter, 'All Agents') }}
          <UIcon name="i-heroicons-chevron-down" class="pol-select-chevron" />
        </button>
        <div v-if="openDropdown === 'agent'" class="pol-dropdown-panel">
          <label v-for="opt in agentOptions" :key="opt" class="pol-dropdown-option" @click.stop>
            <input type="checkbox" :checked="agentFilter.includes(opt)" @change="toggleAgent(opt)" />
            <span>{{ opt }}</span>
          </label>
          <button v-if="agentFilter.length > 0" type="button" class="pol-dropdown-clear" @click.stop="agentFilter = []">Clear</button>
        </div>
      </div>

      <!-- Channels multi-select -->
      <div class="pol-multi-dropdown">
        <button type="button" class="pol-select" @click.stop="toggleDropdown('channel')">
          {{ multiLabel(channelFilter, 'All Channels') }}
          <UIcon name="i-heroicons-chevron-down" class="pol-select-chevron" />
        </button>
        <div v-if="openDropdown === 'channel'" class="pol-dropdown-panel">
          <label v-for="opt in channelOptions" :key="opt" class="pol-dropdown-option" @click.stop>
            <input type="checkbox" :checked="channelFilter.includes(opt)" @change="toggleChannel(opt)" />
            <span>{{ opt }}</span>
          </label>
          <button v-if="channelFilter.length > 0" type="button" class="pol-dropdown-clear" @click.stop="channelFilter = []">Clear</button>
        </div>
      </div>
      <select v-model="sortBy" class="pol-select">
        <option value="renewal_asc">Sort: Renewal date</option>
        <option value="premium_desc">Sort: Premium (high-low)</option>
        <option value="premium_asc">Sort: Premium (low-high)</option>
        <option value="customer_name">Sort: Customer name</option>
      </select>
      <button class="pol-btn-ghost" :disabled="pending" @click="refresh()">
        <UIcon name="i-heroicons-arrow-path" class="w-3.5 h-3.5" :class="{ 'animate-spin': pending }" />
        Refresh
      </button>
      <div class="pol-view-toggle">
        <button type="button" :class="['pol-view-toggle-btn', viewMode === 'card' && 'pol-view-toggle-btn--active']" title="Card view" @click="viewMode = 'card'">
          <UIcon name="i-heroicons-squares-2x2" style="width: 16px; height: 16px;" />
        </button>
        <button type="button" :class="['pol-view-toggle-btn', viewMode === 'list' && 'pol-view-toggle-btn--active']" title="List view" @click="viewMode = 'list'">
          <UIcon name="i-heroicons-bars-3" style="width: 16px; height: 16px;" />
        </button>
      </div>
    </div>

    <!-- Error state -->
    <div v-if="error && !usingMock" class="pol-card" style="border-color: rgba(193,56,56,0.15); background: rgba(193,56,56,0.03);">
      <div style="padding: 16px 20px; display: flex; align-items: center; gap: 10px;">
        <UIcon name="i-heroicons-exclamation-circle" class="w-5 h-5 text-rose-500 flex-shrink-0" />
        <div>
          <p class="text-sm font-semibold text-rose-700">Failed to load policies</p>
          <p class="text-xs text-rose-500 mt-0.5">{{ error.message }}</p>
        </div>
      </div>
    </div>

    <!-- Loading state -->
    <div v-if="pending && !usingMock" class="pol-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>


    <!-- Policy views (mock data) -->
    <template v-if="!pending || usingMock">
      <!-- ═══ Card View ═══ -->
      <div v-if="viewMode === 'card' && usingMock" class="pol-card-grid">
        <NuxtLink
          v-for="pol in tabFilteredPolicies"
          :key="pol.id"
          :to="`/policies/${pol.id}`"
          class="pol-card-item"
        >
          <div class="pol-card-item__top">
            <span class="pol-policy-number pol-policy-link">{{ pol.id }}</span>
            <span class="pol-status-badge" :class="`pol-status-${pol.status.toLowerCase()}`">{{ pol.status }}</span>
          </div>
          <p class="pol-card-item__customer">{{ pol.customerName }}</p>
          <div class="pol-card-item__body">
            <div class="pol-card-item__field">
              <span class="pol-card-item__label">Line</span>
              <span class="pol-line-chip" :class="`pol-line-${pol.line.toLowerCase()}`">
                <UIcon :name="pol.icon || lineIcon(pol.line)" class="pol-line-chip-icon" />
                {{ pol.line }}
              </span>
            </div>
            <div class="pol-card-item__field">
              <span class="pol-card-item__label">Carrier</span>
              <span class="pol-card-item__value">{{ pol.carrier }}</span>
            </div>
            <div class="pol-card-item__field">
              <span class="pol-card-item__label">Product</span>
              <span class="pol-card-item__value">{{ pol.product }}</span>
            </div>
            <div class="pol-card-item__field">
              <span class="pol-card-item__label">Premium</span>
              <span class="pol-card-item__value" style="font-weight: 600;">{{ fmtMoney(pol.premium) }}<span class="pol-premium-period">/yr</span></span>
            </div>
            <div class="pol-card-item__field">
              <span class="pol-card-item__label">Renewal</span>
              <span :class="renewalUrgency(pol.renewal).class">{{ renewalUrgency(pol.renewal).label }}</span>
            </div>
            <div class="pol-card-item__field">
              <span class="pol-card-item__label">Agent</span>
              <span class="pol-card-item__value">{{ pol.agent }}</span>
            </div>
          </div>
        </NuxtLink>
        <div v-if="tabFilteredPolicies.length === 0" class="pol-empty" style="grid-column: 1 / -1;">
          <UIcon name="i-heroicons-document-magnifying-glass" class="w-10 h-10" style="color: #8a8a86; opacity: 0.5;" />
          <p class="pol-empty-title">No policies match your filters</p>
          <p class="pol-empty-sub">Try adjusting your search or filter criteria</p>
        </div>
      </div>

      <!-- ═══ List View ═══ -->
      <div v-if="viewMode === 'list' && usingMock" class="pol-card pol-card-flush">
        <!-- Status tabs -->
        <div class="pol-card-head">
          <div class="pol-table-tabs">
            <button
              v-for="t in ([
                { id: 'all', label: 'All' },
                { id: 'active', label: 'Active' },
                { id: 'pending', label: 'Pending' },
                { id: 'lapsed', label: 'Lapsed' },
                { id: 'cancelled', label: 'Cancelled' },
              ] as { id: TableFilter; label: string }[])"
              :key="t.id"
              type="button"
              class="pol-table-tab"
              :class="tableTab === t.id ? 'pol-tab-on' : 'pol-tab-off'"
              @click="tableTab = t.id"
            >
              {{ t.label }}
              <span class="pol-tab-count" :class="tableTab === t.id ? 'pol-tab-count-on' : ''">{{ tabCounts[t.id] }}</span>
            </button>
          </div>
        </div>

        <!-- Table -->
        <div class="pol-table-wrap">
          <table class="pol-table">
            <thead>
              <tr>
                <th class="pol-th">Policy #</th>
                <th class="pol-th">Customer</th>
                <th class="pol-th">Line</th>
                <th class="pol-th">Carrier</th>
                <th class="pol-th">Product</th>
                <th class="pol-th pol-th-right">Premium</th>
                <th class="pol-th">Status</th>
                <th class="pol-th">Renewal</th>
                <th class="pol-th">Agent</th>
                <th class="pol-th pol-th-actions">Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="pol in tabFilteredPolicies"
                :key="pol.id"
                class="pol-row"
              >
                <td class="pol-td">
                  <NuxtLink :to="`/policies/${pol.id}`" class="pol-policy-number pol-policy-link">{{ pol.id }}</NuxtLink>
                </td>
                <td class="pol-td">
                  <NuxtLink :to="`/customers/${pol.customerId}`" class="pol-customer-link">
                    {{ pol.customerName }}
                  </NuxtLink>
                </td>
                <td class="pol-td">
                  <span class="pol-line-chip" :class="`pol-line-${pol.line.toLowerCase()}`">
                    <UIcon :name="pol.icon || lineIcon(pol.line)" class="pol-line-chip-icon" />
                    {{ pol.line }}
                  </span>
                </td>
                <td class="pol-td">
                  <span class="pol-carrier">{{ pol.carrier }}</span>
                </td>
                <td class="pol-td">
                  <span class="pol-product">{{ pol.product }}</span>
                  <span v-if="pol.details" class="pol-product-detail">{{ pol.details }}</span>
                </td>
                <td class="pol-td pol-td-right">
                  <span class="pol-premium">{{ fmtMoney(pol.premium) }}</span>
                  <span class="pol-premium-period">/yr</span>
                </td>
                <td class="pol-td">
                  <span
                    class="pol-status-badge"
                    :class="`pol-status-${pol.status.toLowerCase()}`"
                  >{{ pol.status }}</span>
                </td>
                <td class="pol-td">
                  <span :class="renewalUrgency(pol.renewal).class">
                    {{ renewalUrgency(pol.renewal).label }}
                  </span>
                </td>
                <td class="pol-td">
                  <span class="pol-agent">{{ pol.agent }}</span>
                </td>
                <td class="pol-td pol-td-actions">
                  <NuxtLink :to="`/policies/${pol.id}`" class="pol-action-btn" title="View policy">
                    <UIcon name="i-heroicons-eye" class="w-3.5 h-3.5" />
                  </NuxtLink>
                  <NuxtLink :to="`/customers/${pol.customerId}`" class="pol-action-btn" title="View customer">
                    <UIcon name="i-heroicons-user" class="w-3.5 h-3.5" />
                  </NuxtLink>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Empty filtered state -->
        <div v-if="tabFilteredPolicies.length === 0" class="pol-empty">
          <UIcon name="i-heroicons-document-magnifying-glass" class="w-10 h-10" style="color: #8a8a86; opacity: 0.5;" />
          <p class="pol-empty-title">No policies match your filters</p>
          <p class="pol-empty-sub">Try adjusting your search or filter criteria</p>
        </div>

        <!-- Bottom bar -->
        <div v-if="tabFilteredPolicies.length > 0" class="pol-bottom-bar">
          <span class="pol-bottom-count">{{ tabFilteredPolicies.length }} {{ tabFilteredPolicies.length === 1 ? 'policy' : 'policies' }}</span>
          <span class="pol-bottom-sep"></span>
          <span class="pol-bottom-premium">Total visible premium: <strong>{{ fmtMoney(visiblePremiumTotal) }}</strong>/yr</span>
        </div>
      </div>

      <!-- API policy table -->
      <div v-else-if="apiPolicies.length > 0" class="pol-card pol-card-flush">
        <div class="pol-card-head">
          <span>Policies</span>
          <span class="pol-card-head-count">{{ meta?.total_count ?? apiPolicies.length }}</span>
        </div>
        <div class="pol-table-wrap">
          <table class="pol-table">
            <thead>
              <tr>
                <th class="pol-th">Applicant</th>
                <th class="pol-th">Document</th>
                <th class="pol-th">Details</th>
                <th class="pol-th">Status</th>
                <th class="pol-th">Quotes</th>
                <th class="pol-th">Submitted</th>
              </tr>
            </thead>
            <tbody>
              <NuxtLink
                v-for="policy in apiPolicies"
                :key="policy.application_id"
                :to="`/policies/app/${policy.application_id}`"
                custom
                v-slot="{ navigate }"
              >
                <tr class="pol-row" style="cursor: pointer;" @click="navigate">
                  <td class="pol-td">
                    <p class="pol-product-name">{{ policyApplicantName(policy) }}</p>
                  </td>
                  <td class="pol-td">
                    <span class="pol-policy-number">{{ policyApplicantDoc(policy) }}</span>
                  </td>
                  <td class="pol-td">
                    <span class="pol-carrier">
                      {{ policyDetailsSummary(policy) }}
                    </span>
                  </td>
                  <td class="pol-td">
                    <span
                      class="pol-status-badge"
                      :class="{
                        'pol-status-active': policy.status === 'issued',
                        'pol-status-pending': policy.status === 'quote_requested' || policy.status === 'solicitation_sent',
                        'pol-status-lapsed': policy.status === 'quotes_received',
                      }"
                    >{{ statusLabel(policy.status) }}</span>
                  </td>
                  <td class="pol-td">
                    <span class="pol-carrier">
                      {{ Object.keys(policy.quotes ?? {}).length }} / {{ (policy.selected_providers ?? []).length }}
                    </span>
                  </td>
                  <td class="pol-td">
                    <span class="pol-renewal-date">{{ new Date(policy.submitted_at).toLocaleDateString('es-PA') }}</span>
                  </td>
                </tr>
              </NuxtLink>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Empty state (API, no results) -->
      <div v-else-if="!usingMock && apiPolicies.length === 0 && !pending" class="pol-card">
        <div class="pol-empty">
          <UIcon name="i-heroicons-document-text" class="w-10 h-10" style="color: #8a8a86; opacity: 0.5;" />
          <p class="pol-empty-title">No policies found</p>
          <p class="pol-empty-sub">Create a new policy or adjust your filters</p>
        </div>
      </div>

      <!-- Pagination -->
      <div v-if="meta && meta.total_pages > 1" class="flex justify-center pt-2">
        <UPagination v-model="page" :total="meta.total_count" :page-count="meta.page_size" />
      </div>
    </template>
  </div>
</template>

<style scoped>
/* =====================================================================
   POLICIES INDEX — TABLE-FIRST LAYOUT (scoped, pol- prefix)
   ===================================================================== */

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

/* ---- Header ---- */
.pol-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pol-header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}
.pol-title {
  font-size: 24px;
  font-weight: 600;
  letter-spacing: -0.01em;
  color: var(--text-primary, #1a1a1a);
  line-height: 1;
}
.pol-count-badge {
  font-size: 11px;
  font-weight: 700;
  color: #01696f;
  background: rgba(1, 105, 111, 0.08);
  padding: 2px 9px;
  border-radius: 10px;
  letter-spacing: 0.01em;
}
.pol-header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* ---- Filter bar ---- */
.pol-filter-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

/* ---- Card system ---- */
.pol-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);
}
.pol-card-flush {
  overflow: hidden;
}
.pol-card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
}
.pol-card-head-count {
  font-size: 11px;
  font-weight: 600;
  color: #8a8a86;
  background: rgba(0, 0, 0, 0.04);
  padding: 2px 8px;
  border-radius: 10px;
}

/* ---- Buttons ---- */
.pol-btn-primary {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 7px 14px;
  font-size: 12px;
  font-weight: 600;
  color: #ffffff;
  background: #01696f;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 150ms ease;
}
.pol-btn-primary:hover { background: #015258; }

.pol-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;
}
.pol-btn-secondary:hover {
  border-color: rgba(1, 105, 111, 0.2);
  color: #01696f;
}

.pol-btn-ghost {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 5px 10px;
  font-size: 11px;
  font-weight: 500;
  color: #8a8a86;
  background: transparent;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 6px;
  cursor: pointer;
  transition: all 150ms ease;
}
.pol-btn-ghost:hover { color: var(--text-primary, #1a1a1a); border-color: rgba(0, 0, 0, 0.12); }

/* ---- View toggle ---- */
.pol-view-toggle {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  padding: 3px;
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.04);
  margin-left: auto;
}
.pol-view-toggle-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 28px;
  border-radius: 7px;
  border: none;
  background: transparent;
  color: #8a8a86;
  cursor: pointer;
  transition: all 0.15s ease;
}
.pol-view-toggle-btn:hover { color: var(--text-primary, #1a1a1a); }
.pol-view-toggle-btn--active {
  background: #fff;
  color: var(--text-primary, #1a1a1a);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

/* ---- Card grid ---- */
.pol-card-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
}
@media (max-width: 1024px) { .pol-card-grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 640px) { .pol-card-grid { grid-template-columns: 1fr; } }

.pol-card-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 16px;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  text-decoration: none;
  transition: all 0.15s ease;
  cursor: pointer;
}
.pol-card-item:hover {
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.07);
  border-color: rgba(1, 105, 111, 0.15);
}
.pol-card-item__top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pol-card-item__customer {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.pol-card-item__body {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-top: 8px;
  border-top: 1px solid rgba(0, 0, 0, 0.04);
}
.pol-card-item__field {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pol-card-item__label {
  font-size: 12px;
  color: #8a8a86;
}
.pol-card-item__value {
  font-size: 13px;
  font-weight: 500;
  color: var(--text-primary, #1a1a1a);
}

/* ---- Search ---- */
.pol-search-wrap {
  position: relative;
  display: inline-flex;
  align-items: center;
  flex: 1;
  min-width: 200px;
  max-width: 340px;
}
.pol-search-icon {
  position: absolute;
  left: 10px;
  width: 14px;
  height: 14px;
  color: #8a8a86;
  pointer-events: none;
}
.pol-search-input {
  padding: 6px 10px 6px 30px;
  width: 100%;
  font-size: 12px;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  background: #ffffff;
  color: var(--text-primary, #1a1a1a);
  outline: none;
  transition: border-color 150ms ease;
}
.pol-search-input::placeholder { color: #8a8a86; }
.pol-search-input:focus { border-color: rgba(1, 105, 111, 0.3); }

/* ---- Native select ---- */
.pol-select {
  appearance: none;
  padding: 6px 28px 6px 10px;
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.08);
  font-size: 12px;
  font-weight: 500;
  color: var(--text-primary, #1a1a1a);
  background: #ffffff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%238a8a86'/%3E%3C/svg%3E") no-repeat right 10px center;
  cursor: pointer;
  outline: none;
  transition: border-color 150ms ease;
  white-space: nowrap;
}
.pol-select:focus { border-color: rgba(1, 105, 111, 0.3); }

/* ---- Multi-select dropdown ---- */
.pol-multi-dropdown {
  position: relative;
}
.pol-multi-dropdown .pol-select {
  display: flex;
  align-items: center;
  gap: 4px;
  text-align: left;
  min-width: 120px;
}
.pol-select-chevron {
  width: 12px;
  height: 12px;
  color: #8a8a86;
  margin-left: auto;
}
.pol-multi-dropdown .pol-select {
  background-image: none;
  padding-right: 10px;
}
.pol-dropdown-panel {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  min-width: 180px;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  z-index: 50;
  padding: 6px 0;
  max-height: 260px;
  overflow-y: auto;
}
.pol-dropdown-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 500;
  color: var(--text-primary, #1a1a1a);
  cursor: pointer;
  transition: background 100ms;
}
.pol-dropdown-option:hover {
  background: rgba(1, 105, 111, 0.04);
}
.pol-dropdown-option input[type="checkbox"] {
  width: 14px;
  height: 14px;
  accent-color: #01696f;
  cursor: pointer;
  flex-shrink: 0;
}
.pol-dropdown-clear {
  display: block;
  width: calc(100% - 16px);
  margin: 4px 8px 2px;
  padding: 4px 8px;
  font-size: 11px;
  font-weight: 600;
  color: #01696f;
  background: rgba(1, 105, 111, 0.06);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  text-align: center;
}
.pol-dropdown-clear:hover {
  background: rgba(1, 105, 111, 0.12);
}

/* ---- Mock banner ---- */
.pol-mock-banner {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 14px;
  margin-bottom: 8px;
  background: rgba(1, 105, 111, 0.04);
  border: 1px solid rgba(1, 105, 111, 0.1);
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
  color: var(--text-muted, #5c5650);
}

/* ---- Table tabs ---- */
.pol-table-tabs {
  display: inline-flex; gap: 2px; padding: 3px;
  border-radius: 8px; background: rgba(0,0,0,0.04);
}
.pol-table-tab {
  display: inline-flex; align-items: center; gap: 4px;
  padding: 5px 10px; border-radius: 6px;
  font-size: 11px; font-weight: 500; border: none;
  cursor: pointer; transition: all 150ms ease; white-space: nowrap;
}
.pol-tab-on { background: #fff; color: var(--text-primary); box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
.pol-tab-off { background: transparent; color: #8a8a86; }
.pol-tab-off:hover { color: var(--text-primary); }
.pol-tab-count {
  font-size: 9px; font-weight: 600; padding: 0px 4px;
  border-radius: 9999px; background: rgba(0,0,0,0.06); color: #8a8a86;
}
.pol-tab-count-on { background: rgba(1,105,111,0.1); color: #01696f; }

/* ---- Table ---- */
.pol-table-wrap {
  overflow-x: auto;
}
.pol-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}
.pol-th {
  padding: 8px 12px;
  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;
}
.pol-th-right { text-align: right; }
.pol-th-actions { text-align: center; width: 80px; }
.pol-td {
  padding: 8px 12px;
  vertical-align: middle;
  border-bottom: 1px solid rgba(0, 0, 0, 0.03);
  font-size: 13px;
}
.pol-td-right { text-align: right; }
.pol-td-actions {
  text-align: center;
  white-space: nowrap;
}
.pol-row {
  transition: background 120ms ease;
}
.pol-row:hover {
  background: rgba(0, 0, 0, 0.015);
}
.pol-row:last-child .pol-td {
  border-bottom: none;
}

/* ---- Table cell elements ---- */
.pol-policy-number {
  font-size: 12px;
  font-family: ui-monospace, 'SF Mono', 'Cascadia Mono', monospace;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}
.pol-policy-link {
  color: #01696f;
  text-decoration: none;
  font-weight: 600;
}
.pol-policy-link:hover {
  text-decoration: underline;
  text-underline-offset: 2px;
}
.pol-product-name {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
  line-height: 1.3;
}
.pol-product {
  font-size: 13px;
  font-weight: 500;
  color: var(--text-primary, #1a1a1a);
  display: block;
  line-height: 1.3;
}
.pol-product-detail {
  display: block;
  font-size: 11px;
  color: #8a8a86;
  margin-top: 1px;
}
.pol-carrier {
  font-size: 13px;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}
.pol-customer-link {
  font-size: 13px;
  font-weight: 500;
  color: #01696f;
  text-decoration: none;
  transition: color 150ms ease;
  white-space: nowrap;
}
.pol-customer-link:hover {
  color: #015258;
  text-decoration: underline;
}
.pol-premium {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
  font-variant-numeric: tabular-nums;
}
.pol-premium-period {
  font-size: 11px;
  font-weight: 400;
  color: #8a8a86;
}
.pol-agent {
  font-size: 12px;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}
.pol-renewal-date {
  font-size: 12px;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}

/* ---- Line chip (icon + label) ---- */
.pol-line-chip {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  font-weight: 600;
  padding: 2px 8px 2px 5px;
  border-radius: 10px;
  white-space: nowrap;
}
.pol-line-chip-icon {
  width: 12px;
  height: 12px;
}
.pol-line-auto     { background: rgba(59, 130, 246, 0.08); color: #2563eb; }
.pol-line-health   { background: rgba(236, 72, 153, 0.08); color: #db2777; }
.pol-line-life     { background: rgba(16, 185, 129, 0.08); color: #059669; }
.pol-line-home     { background: rgba(245, 158, 11, 0.08); color: #d97706; }
.pol-line-renter   { background: rgba(245, 158, 11, 0.08); color: #d97706; }
.pol-line-umbrella { background: rgba(139, 92, 246, 0.08); color: #7c3aed; }

/* ---- Status badge ---- */
.pol-status-badge {
  display: inline-block;
  font-size: 10px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 10px;
  white-space: nowrap;
}
.pol-status-active    { background: rgba(16, 185, 129, 0.1); color: #059669; }
.pol-status-pending   { background: rgba(245, 158, 11, 0.1); color: #d97706; }
.pol-status-lapsed    { background: rgba(244, 63, 94, 0.1); color: #e11d48; }
.pol-status-cancelled { background: rgba(0, 0, 0, 0.05); color: #8a8a86; }

/* ---- Action buttons ---- */
.pol-action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 6px;
  background: transparent;
  color: #8a8a86;
  cursor: pointer;
  transition: all 150ms ease;
  text-decoration: none;
  margin: 0 2px;
}
.pol-action-btn:hover {
  color: #01696f;
  border-color: rgba(1, 105, 111, 0.2);
  background: rgba(1, 105, 111, 0.04);
}

/* ---- Renewal urgency ---- */
.pol-renew-urgent {
  font-size: 12px; font-weight: 700; color: #c13838;
  padding: 1px 6px; border-radius: 4px;
  background: rgba(193,56,56,0.06);
  white-space: nowrap;
}
.pol-renew-soon {
  font-size: 12px; font-weight: 600; color: #c27b1a;
  white-space: nowrap;
}
.pol-renew-ok {
  font-size: 12px; color: var(--text-primary, #1a1a1a);
  white-space: nowrap;
}
.pol-renew-far {
  font-size: 12px; color: var(--text-muted, #5c5650);
  white-space: nowrap;
}
.pol-renew-overdue {
  font-size: 12px; font-weight: 600; color: #c27b1a;
  padding: 1px 6px; border-radius: 4px;
  background: rgba(194,123,26,0.06);
  white-space: nowrap;
}
.pol-renew-past {
  font-size: 12px; font-weight: 600; color: #c13838;
  white-space: nowrap;
}
.pol-renew-expired {
  font-size: 11px; font-weight: 600; color: #8a8a86;
  text-decoration: line-through;
  opacity: 0.6;
  white-space: nowrap;
}

/* ---- Bottom bar ---- */
.pol-bottom-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 16px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  font-size: 12px;
  color: #8a8a86;
}
.pol-bottom-count {
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
}
.pol-bottom-sep {
  width: 1px;
  height: 14px;
  background: rgba(0, 0, 0, 0.08);
}
.pol-bottom-premium {
  font-weight: 400;
}
.pol-bottom-premium strong {
  font-weight: 700;
  color: var(--text-primary, #1a1a1a);
  font-variant-numeric: tabular-nums;
}

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

/* ---- Skeleton ---- */
.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>
