<script setup lang="ts">
import { NCard, NTag } from 'naive-ui'

interface TableData {
  caption?: string
  is_table1?: boolean
  headers?: string[]
  rows?: string[][]
  footnotes?: string[]
}

defineProps<{
  tables?: TableData[]
}>()
</script>

<template>
  <div v-if="tables?.length" class="table1-viewer">
    <div v-for="(tbl, idx) in tables" :key="idx" class="table-wrap-card">
      <NCard v-if="tbl.caption || tbl.is_table1" size="small" :title="tbl.caption || `Table ${idx + 1}`">
        <template v-if="tbl.is_table1" #header-extra>
          <NTag size="tiny" type="success" :bordered="false">Table 1 基线特征</NTag>
        </template>
        <div class="table-scroll">
          <table class="structured-table">
            <thead v-if="tbl.headers?.length">
              <tr>
                <th v-for="(h, hi) in tbl.headers" :key="hi">{{ h }}</th>
              </tr>
            </thead>
            <tbody v-if="tbl.rows?.length">
              <tr v-for="(row, ri) in tbl.rows" :key="ri" :class="{ 'table-row-alt': ri % 2 === 1 }">
                <td v-for="(cell, ci) in row" :key="ci" :class="{ 'row-label': ci === 0 }">{{ cell }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-if="tbl.footnotes?.length" class="table-footnotes">
          <div v-for="(fn, fi) in tbl.footnotes" :key="fi" class="footnote">[{{ fi + 1 }}] {{ fn }}</div>
        </div>
      </NCard>
    </div>
  </div>
  <div v-else-if="tables !== undefined" class="table1-empty">
    暂无表格数据
  </div>
</template>

<style scoped>
.table1-viewer {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.table-wrap-card {
  overflow: hidden;
}
.table-scroll {
  overflow-x: auto;
  margin: 0 -12px;
  padding: 0 12px;
}
.structured-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
  line-height: 1.6;
}
.structured-table th {
  background: var(--bg-page);
  font-weight: 600;
  padding: 8px 12px;
  text-align: left;
  border-bottom: 2px solid #d0d7de;
  white-space: nowrap;
}
.structured-table td {
  padding: 6px 12px;
  border-bottom: 1px solid #e8edf2;
  vertical-align: top;
}
.structured-table .row-label {
  font-weight: 500;
  color: var(--text-primary);
  white-space: nowrap;
}
.table-row-alt td {
  background: var(--preview-ai-bg);
}
.table-footnotes {
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px solid var(--border-color);
}
.footnote {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.5;
}
.table1-empty {
  padding: 24px;
  text-align: center;
  color: var(--text-muted);
  font-size: 13px;
}
</style>
