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

const props = defineProps<{
  initialData?: Record<string, any>
  fields: Array<{ name: string; label: string; type: 'text' | 'currency' | 'date' | 'combo' | 'check' | 'radio' | 'textarea' | 'autocomplete'; required?: boolean; options?: any[] }>
}>()

const emit = defineEmits(['create', 'update', 'delete', 'cancel'])

const formData = ref<Record<string, any>>({ ...(props.initialData || {}) })
const isEditing = ref(!!props.initialData)

const handleCreate = () => {
  emit('create', formData.value)
}

const handleUpdate = () => {
  emit('update', formData.value)
}

const handleDelete = () => {
  if (confirm('정말로 해당 데이터를 삭제하시겠습니까? (F5)')) {
    emit('delete', formData.value)
  }
}
</script>

<template>
  <div style="background: white; border: 1px solid #CBD5E1; padding: 16px; border-radius: 4px; display: flex; flex-direction: column; height: 100%;">
    <!-- Form Action Toolbar (CRUD Standard UX) -->
    <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #2C3E50; padding-bottom: 8px; margin-bottom: 12px;">
      <h4 style="margin: 0; color: #2C3E50;">
        <i class="ti ti-edit me-1"></i> {{ isEditing ? '데이터 상세 / 수정' : '신규 데이터 등록' }}
      </h4>
      <div style="display: flex; gap: 8px;">
        <button v-if="!isEditing" style="background: #2980B9; color: white; border: none; padding: 4px 12px; font-weight: bold; border-radius: 2px; cursor: pointer;" @click="handleCreate">
          <span class="hotkey-badge">F4</span>신규 저장
        </button>
        <button v-else style="background: #27AE60; color: white; border: none; padding: 4px 12px; font-weight: bold; border-radius: 2px; cursor: pointer;" @click="handleUpdate">
          <span class="hotkey-badge">F4</span>수정 저장
        </button>
        <button v-if="isEditing" style="background: #C0392B; color: white; border: none; padding: 4px 12px; font-weight: bold; border-radius: 2px; cursor: pointer;" @click="handleDelete">
          <span class="hotkey-badge">F5</span>삭제
        </button>
      </div>
    </div>

    <!-- High-Density Form Fields Grid -->
    <div style="flex: 1; overflow-y: auto;">
      <table style="width: 100%; border-collapse: collapse;">
        <tbody>
          <tr v-for="field in fields" :key="field.name" style="border-bottom: 1px solid #ECF0F1;">
            <td style="width: 130px; padding: 8px; background: #F8FAFC; border: 1px solid #CBD5E1; font-weight: bold; text-align: right;">
              <span v-if="field.required" style="color: red; margin-right: 2px;">*</span>{{ field.label }}
            </td>
            <td style="padding: 8px; border: 1px solid #CBD5E1;">
              <input v-model="formData[field.name]" type="text" style="width: 100%; box-sizing: border-box; padding: 4px 8px; border: 1px solid #CBD5E1; font-weight: bold;" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
