<template>
  <div class="data-table-wrapper">
    <table class="data-table">
      <thead>
        <tr>
          <th v-for="col in columns" :key="col.key" :style="{ width: col.width }">
            {{ col.label }}
          </th>
          <th v-if="$slots.actions" class="actions-col">작업</th>
        </tr>
      </thead>
      <tbody>
        <tr v-if="loading">
          <td :colspan="columns.length + ($slots.actions ? 1 : 0)" class="loading-cell">
            로딩 중...
          </td>
        </tr>
        <tr v-else-if="!data || data.length === 0">
          <td :colspan="columns.length + ($slots.actions ? 1 : 0)" class="empty-cell">
            {{ emptyText }}
          </td>
        </tr>
        <tr v-else v-for="(row, idx) in data" :key="row.id || idx" @click="$emit('row-click', row)">
          <td v-for="col in columns" :key="col.key">
            <slot :name="col.key" :row="row" :value="row[col.key]">
              {{ formatValue(row[col.key], col) }}
            </slot>
          </td>
          <td v-if="$slots.actions" class="actions-col">
            <slot name="actions" :row="row"></slot>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
const props = defineProps({
  columns: {
    type: Array,
    required: true
    // { key: 'name', label: '이름', width: '100px', type: 'date' }
  },
  data: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  emptyText: {
    type: String,
    default: '데이터가 없습니다.'
  }
})

defineEmits(['row-click'])

const formatValue = (value, col) => {
  if (value === null || value === undefined) return '-'
  
  if (col.type === 'date' && value) {
    return new Date(value).toLocaleString('ko-KR')
  }
  if (col.type === 'boolean') {
    return value ? 'Y' : 'N'
  }
  return value
}
</script>

<style scoped>
.data-table-wrapper {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.data-table th,
.data-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.data-table tbody tr:last-child td {
  border-bottom: none;
}

.actions-col {
  width: 120px;
  text-align: center;
}

.loading-cell,
.empty-cell {
  text-align: center;
  color: #6c757d;
  padding: 40px !important;
}
</style>
