<template>
  <div class="douzone-viewport-container d-flex flex-column h-100">
    <!-- 1. Douzone Top Toolbar -->
    <header class="douzone-header-toolbar d-flex justify-content-between align-items-center p-2 bg-navy text-white">
      <div class="d-flex align-items-center gap-3">
        <span class="fw-bold fs-4 text-warning">QuantEngine ERP v4.0 (Vue 3 / AG Grid)</span>
        <span class="badge bg-success">PostgreSQL 3NF Connected</span>
      </div>
      <div>
        <button class="btn btn-sm btn-secondary me-1" @click="fetchData"><span class="hotkey-badge">F3</span>조회</button>
        <button class="btn btn-sm btn-primary me-1"><span class="hotkey-badge">F4</span>저장</button>
        <button class="btn btn-sm btn-danger me-1"><span class="hotkey-badge">F5</span>삭제</button>
        <button class="btn btn-sm btn-success"><span class="hotkey-badge">F7</span>엑셀</button>
      </div>
    </header>

    <!-- 2. Master-Detail AG Grid Viewport (No Page Scroll) -->
    <div class="flex-grow-1 row g-0 overflow-hidden">
      <!-- Left: AG Grid Master List (65%) -->
      <div class="col-8 border-end h-100 p-2">
        <ag-grid-vue
          style="width: 100%; height: 100%;"
          class="ag-theme-alpine"
          :columnDefs="columnDefs"
          :rowData="rowData"
          :defaultColDef="defaultColDef"
          @row-selected="onRowSelected"
          rowSelection="single"
        >
        </ag-grid-vue>
      </div>

      <!-- Right: Detail & Audit Provenance Inspector (35%) -->
      <div class="col-4 h-100 p-3 bg-light overflow-auto">
        <h5 class="fw-bold text-navy mb-3"><i class="ti ti-info-circle me-1"></i>상세 및 Provenance 검토</h5>
        <div v-if="selectedRow" class="card p-3 shadow-sm border">
          <div class="mb-2"><strong>실행 ID:</strong> {{ selectedRow.runId }}</div>
          <div class="mb-2"><strong>시작 시간:</strong> {{ selectedRow.startedAt }}</div>
          <div class="mb-2"><strong>종료 시간:</strong> {{ selectedRow.finishedAt || '-' }}</div>
          <div class="mb-2">
            <strong>상태:</strong> 
            <span :class="getStatusBadgeClass(selectedRow.status)">{{ selectedRow.status }}</span>
          </div>
          <div class="mb-2"><strong>총 스냅샷:</strong> {{ selectedRow.totalSnapshots }} 건</div>
          <div class="mb-2"><strong>오류 건수:</strong> {{ selectedRow.totalErrors }} 건</div>
          <hr/>
          <div class="text-muted small">
            <strong>Data Integrity:</strong> 3NF Relational Parity Verified<br/>
            <strong>Provenance:</strong> FastEndpoints /api/admin/grid-data
          </div>
        </div>
        <div v-else class="text-muted text-center py-5">
          좌측 AG Grid에서 행을 선택하면 상세 정보가 표출됩니다.
        </div>
      </div>
    </div>

    <!-- 3. Bottom Hotkey Guidance Footer -->
    <footer class="douzone-summary-footer bg-dark text-white p-2 d-flex justify-content-between fs-7">
      <div>
        <span><span class="hotkey-badge">Enter</span>다음 포커스</span>
        <span class="ms-3"><span class="hotkey-badge">F2</span>코드 lookup</span>
        <span class="ms-3"><span class="hotkey-badge">F3</span>조회</span>
        <span class="ms-3"><span class="hotkey-badge">F4</span>저장</span>
        <span class="ms-3"><span class="hotkey-badge">F7</span>엑셀 다운로드</span>
      </div>
      <div>
        <span class="opacity-75">Vue 3 + PrimeVue / AG Grid Modern Frontend Standard</span>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { AgGridVue } from 'ag-grid-vue3';
import axios from 'axios';

const rowData = ref([]);
const selectedRow = ref(null);

const columnDefs = ref([
  { field: 'runId', headerName: '실행 ID', flex: 1, sortable: true, filter: true },
  { field: 'startedAt', headerName: '시작 시간', flex: 1.5, sortable: true },
  { field: 'finishedAt', headerName: '종료 시간', flex: 1.5, sortable: true },
  { field: 'status', headerName: '상태', flex: 1, sortable: true, filter: true },
  { field: 'totalSnapshots', headerName: '스냅샷 수', flex: 1, sortable: true },
  { field: 'totalErrors', headerName: '오류 수', flex: 1, sortable: true }
]);

const defaultColDef = ref({
  resizable: true
});

const fetchData = async () => {
  try {
    const response = await axios.get('/api/admin/grid-data');
    if (response.data && response.data.items) {
      rowData.value = response.data.items;
    }
  } catch (err) {
    console.error('Failed to fetch grid data:', err);
  }
};

const onRowSelected = (event) => {
  if (event.node.isSelected()) {
    selectedRow.value = event.data;
  }
};

const getStatusBadgeClass = (status) => {
  const s = (status || '').toLowerCase();
  if (s === 'completed' || s === 'pass') return 'badge bg-success';
  if (s === 'running' || s === 'warn') return 'badge bg-warning text-dark';
  return 'badge bg-danger';
};

onMounted(() => {
  fetchData();
});
</script>
