<script setup lang="ts">
import { ref } from 'vue'

const props = defineProps<{
  columns: Array<{ field: string; header: string; width?: string; align?: 'left' | 'center' | 'right' }>
  data: Array<Record<string, any>>
  filename?: string
}>()

const emit = defineEmits(['row-click'])
const selectedRow = ref<Record<string, any> | null>(null)

const handleRowClick = (row: Record<string, any>) => {
  selectedRow.value = row
  emit('row-click', row)
}

const exportToExcel = () => {
  const headers = props.columns.map(c => c.header).join(',')
  const rows = props.data.map(row => props.columns.map(c => `"${row[c.field] ?? ''}"`).join(','))
  const csvContent = 'data:text/csv;charset=utf-8,\uFEFF' + [headers, ...rows].join('\n')
  const encodedUri = encodeURI(csvContent)
  const link = document.createElement('a')
  link.setAttribute('href', encodedUri)
  link.setAttribute('download', `${props.filename || 'export'}_${new Date().toISOString().substring(0,10)}.csv`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

defineExpose({ exportToExcel })
</script>

<template>
  <div style="display: flex; flex-direction: column; height: 100%; width: 100%; border: 1px solid #CBD5E1; background: white;">
    <!-- Grid Header Toolbar -->
    <div style="background: #F8FAFC; padding: 6px 12px; border-bottom: 1px solid #CBD5E1; display: flex; justify-content: space-between; align-items: center;">
      <span style="font-size: 12px; font-weight: bold; color: #2C3E50;">
        <i class="ti ti-table me-1"></i> 총 {{ data.length }} 건
      </span>
      <button style="background: #27AE60; color: white; border: none; padding: 3px 10px; font-size: 11px; font-weight: bold; border-radius: 2px; cursor: pointer;" @click="exportToExcel">
        <span class="hotkey-badge">F7</span>엑셀 다운로드
      </button>
    </div>

    <!-- Table Body Container -->
    <div style="flex: 1; overflow: auto;">
      <table style="width: 100%; border-collapse: collapse;">
        <thead>
          <tr style="background: #E2E8F0; color: #2C3E50; position: sticky; top: 0; z-index: 1;">
            <th v-for="col in columns" :key="col.field" :style="{ width: col.width, textAlign: col.align || 'left' }" style="padding: 8px; border: 1px solid #CBD5E1; font-size: 12px;">
              {{ col.header }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(row, idx) in data"
            :key="idx"
            :style="{ background: selectedRow === row ? '#D6E4FF' : idx % 2 === 0 ? '#FFFFFF' : '#F8FAFC' }"
            style="cursor: pointer; border-bottom: 1px solid #ECF0F1;"
            @click="handleRowClick(row)">
            <td v-for="col in columns" :key="col.field" :style="{ textAlign: col.align || 'left' }" style="padding: 6px 8px; border: 1px solid #CBD5E1; font-size: 12px;">
              {{ row[col.field] }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
