<template>
  <div>
    <AppHeader />
    
    <div class="container py-4">
      <div v-if="isLoading" class="text-center py-5">
        <span class="spinner-border"></span>
        <p class="mt-2">로딩 중...</p>
      </div>
      
      <div v-else-if="report">
        <div class="d-flex justify-content-between align-items-center mb-4">
          <div>
            <h4 class="mb-1">
              <i class="bi bi-journal-text me-2"></i>주간보고
              <span :class="getStatusBadgeClass(report.reportStatus)" class="ms-2">
                {{ getStatusText(report.reportStatus) }}
              </span>
            </h4>
            <p class="text-muted mb-0">
              <span class="me-3">{{ report.authorName }}</span>
              {{ report.reportYear }}년 {{ report.reportWeek }}주차
              ({{ formatDate(report.weekStartDate) }} ~ {{ formatDate(report.weekEndDate) }})
            </p>
          </div>
          <div class="d-flex gap-2 align-items-center">
            <!-- 이전/다음 보고서 -->
            <div class="btn-group me-2">
              <NuxtLink v-if="prevReport" :to="`/report/weekly/${prevReport.reportId}`" class="btn btn-outline-secondary" :title="prevReport.authorName">
                <i class="bi bi-chevron-left"></i> 이전
              </NuxtLink>
              <button v-else class="btn btn-outline-secondary" disabled>
                <i class="bi bi-chevron-left"></i> 이전
              </button>
              <NuxtLink v-if="nextReport" :to="`/report/weekly/${nextReport.reportId}`" class="btn btn-outline-secondary" :title="nextReport.authorName">
                다음 <i class="bi bi-chevron-right"></i>
              </NuxtLink>
              <button v-else class="btn btn-outline-secondary" disabled>
                다음 <i class="bi bi-chevron-right"></i>
              </button>
            </div>
            <NuxtLink to="/report/weekly" class="btn btn-outline-secondary">목록</NuxtLink>
            <button v-if="canEdit" class="btn btn-primary" @click="isEditing = !isEditing">
              {{ isEditing ? '취소' : '수정' }}
            </button>
            <button v-if="canSubmit" class="btn btn-success" @click="handleSubmit" :disabled="isSubmitting">
              <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-1"></span>
              제출
            </button>
            <button v-if="canDelete" class="btn btn-outline-danger" @click="handleDelete" :disabled="isDeleting">
              <span v-if="isDeleting" class="spinner-border spinner-border-sm me-1"></span>
              <i v-else class="bi bi-trash me-1"></i>삭제
            </button>
          </div>
        </div>
        
        <!-- 보기 모드 -->
        <div v-if="!isEditing">
          <!-- 프로젝트별 Task -->
          <div v-for="proj in projects" :key="proj.projectId" class="card mb-4">
            <div class="card-header bg-light">
              <i class="bi bi-folder2 me-2"></i>
              <strong>{{ proj.projectName }}</strong>
              <small class="text-muted ms-2">({{ proj.projectCode }})</small>
            </div>
            <div class="card-body">
              <div class="row">
                <!-- 금주 실적 -->
                <div class="col-md-6">
                  <h6 class="text-primary mb-3">
                    <i class="bi bi-check2-square me-1"></i>금주 실적
                    <span class="badge bg-primary ms-1">{{ formatHoursDisplay(getProjectWorkHours(proj)) }}</span>
                  </h6>
                  <div v-if="proj.workTasks.length === 0" class="text-muted">-</div>
                  <div v-else class="list-group list-group-flush">
                    <div v-for="task in proj.workTasks" :key="task.taskId" class="list-group-item px-0 py-2 d-flex justify-content-between align-items-start">
                      <div>
                        <span class="badge me-2" :class="task.isCompleted ? 'bg-success' : 'bg-warning text-dark'">
                          {{ task.isCompleted ? '완료' : '진행' }}
                        </span>
                        <span style="white-space: pre-wrap;">{{ task.description }}</span>
                      </div>
                      <span class="badge bg-light text-dark">{{ formatHours(task.hours) }}</span>
                    </div>
                  </div>
                </div>
                
                <!-- 차주 계획 -->
                <div class="col-md-6">
                  <h6 class="text-success mb-3">
                    <i class="bi bi-calendar-check me-1"></i>차주 계획
                    <span class="badge bg-success ms-1">{{ formatHoursDisplay(getProjectPlanHours(proj)) }}</span>
                  </h6>
                  <div v-if="proj.planTasks.length === 0" class="text-muted">-</div>
                  <div v-else class="list-group list-group-flush">
                    <div v-for="task in proj.planTasks" :key="task.taskId" class="list-group-item px-0 py-2 d-flex justify-content-between align-items-start">
                      <span style="white-space: pre-wrap;">{{ task.description }}</span>
                      <span class="badge bg-light text-dark">{{ formatHours(task.hours) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 총계 -->
          <div class="card mb-4 border-primary">
            <div class="card-body py-2">
              <div class="row text-center">
                <div class="col">
                  <span class="text-muted">금주 실적 합계</span>
                  <h5 class="mb-0 text-primary">{{ formatHoursDisplay(totalWorkHours) }}</h5>
                </div>
                <div class="col">
                  <span class="text-muted">차주 계획 합계</span>
                  <h5 class="mb-0 text-success">{{ formatHoursDisplay(totalPlanHours) }}</h5>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 공통 사항 -->
          <div class="card mb-4">
            <div class="card-header"><strong><i class="bi bi-chat-left-text me-2"></i>공통 사항</strong></div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-4 mb-3">
                  <label class="form-label text-muted small">이슈/리스크</label>
                  <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ report.issueDescription || '-' }}</div>
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label text-muted small">휴가일정</label>
                  <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ report.vacationDescription || '-' }}</div>
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label text-muted small">기타사항</label>
                  <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ report.remarkDescription || '-' }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- PMO AI 리뷰 -->
          <div class="card mb-4 border-info">
            <div class="card-header bg-info bg-opacity-10 d-flex justify-content-between align-items-center">
              <strong><i class="bi bi-robot me-2"></i>PMO AI 리뷰</strong>
              <button class="btn btn-sm btn-outline-info" @click="requestAiReview" :disabled="isReviewing">
                <span v-if="isReviewing" class="spinner-border spinner-border-sm me-1"></span>
                <i v-else class="bi bi-arrow-repeat me-1"></i>
                {{ report.aiReview ? '리뷰 재요청' : '리뷰 요청' }}
              </button>
            </div>
            <div class="card-body">
              <div v-if="report.aiReview" class="ai-review-content" v-html="renderMarkdown(report.aiReview)"></div>
              <div v-else class="text-muted text-center py-3">
                <i class="bi bi-chat-left-dots me-2"></i>
                아직 AI 리뷰가 없습니다. 리뷰 요청 버튼을 클릭하세요.
              </div>
              <div v-if="report.aiReviewAt" class="text-muted small mt-3 text-end">
                <i class="bi bi-clock me-1"></i>리뷰 생성: {{ formatDateTime(report.aiReviewAt) }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 수정 모드 -->
        <form v-else @submit.prevent="handleUpdate">
          <!-- 주차 정보 수정 -->
          <div class="card mb-4">
            <div class="card-header"><strong>보고 주차</strong></div>
            <div class="card-body">
              <div class="row align-items-end">
                <div class="col-auto">
                  <div class="input-group">
                    <button type="button" class="btn btn-outline-secondary" @click="changeEditWeek(-1)">
                      <i class="bi bi-chevron-left"></i>
                    </button>
                    <span class="input-group-text bg-white" style="min-width: 160px;">
                      <strong>{{ editForm.reportYear }}년 {{ editForm.reportWeek }}주차</strong>
                    </span>
                    <button type="button" class="btn btn-outline-secondary" @click="changeEditWeek(1)">
                      <i class="bi bi-chevron-right"></i>
                    </button>
                  </div>
                </div>
                <div class="col-auto">
                  <span class="text-muted">
                    {{ editForm.weekStartDate }} ~ {{ editForm.weekEndDate }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 프로젝트별 Task -->
          <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <strong><i class="bi bi-folder me-2"></i>프로젝트별 실적/계획</strong>
              <button type="button" class="btn btn-sm btn-outline-primary" @click="showProjectModal = true">
                <i class="bi bi-plus"></i> 프로젝트 추가
              </button>
            </div>
            <div class="card-body">
              <div v-for="(group, gIdx) in editProjectGroups" :key="group.projectId" class="border rounded mb-4">
                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                  <span>
                    <i class="bi bi-folder2 me-2"></i>
                    <strong>{{ group.projectName }}</strong>
                    <small class="text-muted ms-2">({{ group.projectCode }})</small>
                  </span>
                  <button type="button" class="btn btn-sm btn-outline-danger" @click="removeEditProjectGroup(gIdx)">
                    <i class="bi bi-x"></i>
                  </button>
                </div>
                <div class="card-body">
                  <div class="row">
                    <!-- 금주 실적 -->
                    <div class="col-md-6">
                      <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0 fw-bold text-primary">금주 실적</label>
                        <button type="button" class="btn btn-sm btn-outline-primary" @click="addEditTask(group.projectId, 'WORK')">
                          <i class="bi bi-plus"></i>
                        </button>
                      </div>
                      <div v-for="(task, tIdx) in getEditWorkTasks(group.projectId)" :key="'work-'+tIdx" class="mb-2">
                        <div class="d-flex gap-2 align-items-start">
                          <div class="form-check pt-1">
                            <input type="checkbox" class="form-check-input" v-model="task.isCompleted" 
                              :id="'edit-work-chk-'+group.projectId+'-'+tIdx" />
                            <label class="form-check-label small" :for="'edit-work-chk-'+group.projectId+'-'+tIdx"
                              :class="task.isCompleted ? 'text-success' : 'text-warning'">
                              {{ task.isCompleted ? '완료' : '진행' }}
                            </label>
                          </div>
                          <textarea class="form-control form-control-sm" v-model="task.description" rows="2" placeholder="작업 내용"></textarea>
                          <div class="text-nowrap">
                            <input type="number" class="form-control form-control-sm text-end mb-1" style="width: 70px;" 
                              v-model.number="task.hours" min="0" step="0.5" placeholder="h" />
                            <div class="small text-muted text-end">{{ formatHours(task.hours) }}</div>
                          </div>
                          <button type="button" class="btn btn-sm btn-outline-danger" @click="removeEditTask(group.projectId, 'WORK', tIdx)">
                            <i class="bi bi-x"></i>
                          </button>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 차주 계획 -->
                    <div class="col-md-6">
                      <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0 fw-bold text-success">차주 계획</label>
                        <button type="button" class="btn btn-sm btn-outline-success" @click="addEditTask(group.projectId, 'PLAN')">
                          <i class="bi bi-plus"></i>
                        </button>
                      </div>
                      <div v-for="(task, tIdx) in getEditPlanTasks(group.projectId)" :key="'plan-'+tIdx" class="mb-2">
                        <div class="d-flex gap-2 align-items-start">
                          <textarea class="form-control form-control-sm" v-model="task.description" rows="2" placeholder="계획 내용"></textarea>
                          <div class="text-nowrap">
                            <input type="number" class="form-control form-control-sm text-end mb-1" style="width: 70px;" 
                              v-model.number="task.hours" min="0" step="0.5" placeholder="h" />
                            <div class="small text-muted text-end">{{ formatHours(task.hours) }}</div>
                          </div>
                          <button type="button" class="btn btn-sm btn-outline-danger" @click="removeEditTask(group.projectId, 'PLAN', tIdx)">
                            <i class="bi bi-x"></i>
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 공통 사항 -->
          <div class="card mb-4">
            <div class="card-header"><strong><i class="bi bi-chat-left-text me-2"></i>공통 사항</strong></div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-4 mb-3">
                  <label class="form-label">이슈/리스크</label>
                  <textarea class="form-control" rows="3" v-model="editForm.issueDescription"></textarea>
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label">휴가일정</label>
                  <textarea class="form-control" rows="3" v-model="editForm.vacationDescription"></textarea>
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label">기타사항</label>
                  <textarea class="form-control" rows="3" v-model="editForm.remarkDescription"></textarea>
                </div>
              </div>
            </div>
          </div>
          
          <div class="d-flex justify-content-end gap-2">
            <button type="button" class="btn btn-secondary" @click="isEditing = false">취소</button>
            <button type="submit" class="btn btn-primary" :disabled="isSaving">
              <span v-if="isSaving" class="spinner-border spinner-border-sm me-1"></span>
              저장
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 프로젝트 선택 모달 -->
    <div class="modal fade" :class="{ show: showProjectModal }" :style="{ display: showProjectModal ? 'block' : 'none' }">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">프로젝트 선택</h5>
            <button type="button" class="btn-close" @click="showProjectModal = false"></button>
          </div>
          <div class="modal-body">
            <div v-if="availableProjects.length === 0" class="text-center text-muted py-4">
              추가할 수 있는 프로젝트가 없습니다.
            </div>
            <div v-else class="list-group">
              <button type="button" class="list-group-item list-group-item-action"
                v-for="p in availableProjects" :key="p.projectId"
                @click="addEditProjectGroup(p)">
                <strong>{{ p.projectName }}</strong>
                <small class="text-muted ms-2">({{ p.projectCode }})</small>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showProjectModal" @click="showProjectModal = false"></div>
  </div>
</template>

<script setup lang="ts">
const { currentUser, fetchCurrentUser } = useAuth()
const router = useRouter()
const route = useRoute()

const reportId = computed(() => route.params.id as string)

const report = ref<any>(null)
const projects = ref<any[]>([])
const allProjects = ref<any[]>([])
const prevReport = ref<any>(null)
const nextReport = ref<any>(null)
const isLoading = ref(true)
const isEditing = ref(false)
const isSaving = ref(false)
const isSubmitting = ref(false)
const isDeleting = ref(false)
const isReviewing = ref(false)
const showProjectModal = ref(false)

const isAdmin = computed(() => currentUser.value?.employeeEmail === 'coziny@gmail.com')

interface EditTask {
  projectId: number
  taskType: 'WORK' | 'PLAN'
  description: string
  hours: number
  isCompleted: boolean
}

const editForm = ref({
  reportYear: 0,
  reportWeek: 0,
  weekStartDate: '',
  weekEndDate: '',
  tasks: [] as EditTask[],
  issueDescription: '',
  vacationDescription: '',
  remarkDescription: ''
})

const editProjectGroups = computed(() => {
  const projectIds = [...new Set(editForm.value.tasks.map(t => t.projectId))]
  return projectIds.map(pid => {
    const proj = allProjects.value.find(p => p.projectId === pid)
    return {
      projectId: pid,
      projectCode: proj?.projectCode || '',
      projectName: proj?.projectName || ''
    }
  })
})

const availableProjects = computed(() => {
  const usedIds = editProjectGroups.value.map(g => g.projectId)
  return allProjects.value.filter(p => !usedIds.includes(p.projectId))
})

const totalWorkHours = computed(() => {
  return projects.value.reduce((sum, proj) => sum + getProjectWorkHours(proj), 0)
})

const totalPlanHours = computed(() => {
  return projects.value.reduce((sum, proj) => sum + getProjectPlanHours(proj), 0)
})

const canEdit = computed(() => {
  if (!report.value || !currentUser.value) return false
  // 관리자는 항상 수정 가능
  if (isAdmin.value) return true
  // 본인 보고서이고 AGGREGATED가 아니면 수정 가능
  return report.value.authorId === currentUser.value.employeeId && report.value.reportStatus !== 'AGGREGATED'
})

const canSubmit = computed(() => {
  if (!report.value || !currentUser.value) return false
  return report.value.authorId === currentUser.value.employeeId && report.value.reportStatus === 'DRAFT'
})

const canDelete = computed(() => {
  if (!report.value || !currentUser.value) return false
  if (isAdmin.value) return true
  return report.value.authorId === currentUser.value.employeeId && report.value.reportStatus !== 'AGGREGATED'
})

onMounted(async () => {
  const user = await fetchCurrentUser()
  if (!user) {
    router.push('/login')
    return
  }
  await loadReport()
  await loadAllProjects()
})

async function loadReport() {
  isLoading.value = true
  try {
    const res = await $fetch<any>(`/api/report/weekly/${reportId.value}/detail`)
    report.value = res.report
    projects.value = res.projects
    prevReport.value = res.prevReport
    nextReport.value = res.nextReport
  } catch (e: any) {
    alert(e.data?.message || '보고서를 불러올 수 없습니다.')
    router.push('/report/weekly')
  } finally {
    isLoading.value = false
  }
}

// route param 변경 시 다시 로드
watch(reportId, async () => {
  isEditing.value = false
  await loadReport()
})

async function loadAllProjects() {
  try {
    const res = await $fetch<any>('/api/project/list')
    allProjects.value = res.projects || []
  } catch (e) {
    console.error(e)
  }
}

watch(isEditing, (val) => {
  if (val) {
    // 기존 데이터를 editForm으로 변환
    const tasks: EditTask[] = []
    for (const proj of projects.value) {
      for (const task of proj.workTasks) {
        tasks.push({
          projectId: proj.projectId,
          taskType: 'WORK',
          description: task.description,
          hours: task.hours,
          isCompleted: task.isCompleted !== false
        })
      }
      for (const task of proj.planTasks) {
        tasks.push({
          projectId: proj.projectId,
          taskType: 'PLAN',
          description: task.description,
          hours: task.hours,
          isCompleted: true
        })
      }
    }
    
    editForm.value = {
      reportYear: report.value.reportYear,
      reportWeek: report.value.reportWeek,
      weekStartDate: report.value.weekStartDate,
      weekEndDate: report.value.weekEndDate,
      tasks,
      issueDescription: report.value.issueDescription || '',
      vacationDescription: report.value.vacationDescription || '',
      remarkDescription: report.value.remarkDescription || ''
    }
  }
})

// 프로젝트별 시간 계산
function getProjectWorkHours(proj: any) {
  return proj.workTasks.reduce((sum: number, t: any) => sum + (t.hours || 0), 0)
}

function getProjectPlanHours(proj: any) {
  return proj.planTasks.reduce((sum: number, t: any) => sum + (t.hours || 0), 0)
}

// 수정 모드 주차 변경
function changeEditWeek(delta: number) {
  let year = editForm.value.reportYear
  let week = editForm.value.reportWeek + delta
  
  // 주차 범위 조정
  if (week < 1) {
    year--
    week = getWeeksInYear(year)
  } else if (week > getWeeksInYear(year)) {
    year++
    week = 1
  }
  
  editForm.value.reportYear = year
  editForm.value.reportWeek = week
  
  // 해당 주차의 월요일~일요일 계산
  const { monday, sunday } = getWeekDates(year, week)
  editForm.value.weekStartDate = monday
  editForm.value.weekEndDate = sunday
}

// 연도의 총 주차 수 계산
function getWeeksInYear(year: number): number {
  const dec31 = new Date(year, 11, 31)
  const dayOfWeek = dec31.getDay()
  // 12월 31일이 목요일 이후면 53주, 아니면 52주
  return dayOfWeek >= 4 || dayOfWeek === 0 ? 53 : 52
}

// 연도와 주차로 해당 주의 월요일~일요일 계산
function getWeekDates(year: number, week: number): { monday: string, sunday: string } {
  // 해당 연도의 첫 번째 목요일이 속한 주가 1주차
  const jan4 = new Date(year, 0, 4)
  const jan4DayOfWeek = jan4.getDay() || 7 // 일요일=7로 변환
  
  // 1주차의 월요일
  const week1Monday = new Date(jan4)
  week1Monday.setDate(jan4.getDate() - jan4DayOfWeek + 1)
  
  // 요청된 주차의 월요일
  const monday = new Date(week1Monday)
  monday.setDate(week1Monday.getDate() + (week - 1) * 7)
  
  // 일요일
  const sunday = new Date(monday)
  sunday.setDate(monday.getDate() + 6)
  
  return {
    monday: formatDateStr(monday),
    sunday: formatDateStr(sunday)
  }
}

function formatDateStr(date: Date): string {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

// 수정 모드 함수들
function getEditWorkTasks(projectId: number) {
  return editForm.value.tasks.filter(t => t.projectId === projectId && t.taskType === 'WORK')
}

function getEditPlanTasks(projectId: number) {
  return editForm.value.tasks.filter(t => t.projectId === projectId && t.taskType === 'PLAN')
}

function addEditProjectGroup(project: any) {
  editForm.value.tasks.push({
    projectId: project.projectId,
    taskType: 'WORK',
    description: '',
    hours: 0,
    isCompleted: true
  })
  editForm.value.tasks.push({
    projectId: project.projectId,
    taskType: 'PLAN',
    description: '',
    hours: 0,
    isCompleted: true
  })
  showProjectModal.value = false
}

function removeEditProjectGroup(gIdx: number) {
  const group = editProjectGroups.value[gIdx]
  editForm.value.tasks = editForm.value.tasks.filter(t => t.projectId !== group.projectId)
}

function addEditTask(projectId: number, taskType: 'WORK' | 'PLAN') {
  editForm.value.tasks.push({ projectId, taskType, description: '', hours: 0, isCompleted: true })
}

function removeEditTask(projectId: number, taskType: 'WORK' | 'PLAN', idx: number) {
  const tasks = editForm.value.tasks.filter(t => t.projectId === projectId && t.taskType === taskType)
  if (tasks.length <= 1) return
  
  const targetTask = tasks[idx]
  const targetIndex = editForm.value.tasks.indexOf(targetTask)
  if (targetIndex > -1) {
    editForm.value.tasks.splice(targetIndex, 1)
  }
}

// 시간 표시 함수
function formatHours(hours: number): string {
  if (!hours || hours <= 0) return '-'
  const days = Math.floor(hours / 8)
  const remainHours = hours % 8
  
  if (days === 0) return `${remainHours}h`
  if (remainHours === 0) return `${days}일`
  return `${days}일 ${remainHours}h`
}

function formatHoursDisplay(hours: number): string {
  if (!hours || hours <= 0) return '0h'
  const days = Math.floor(hours / 8)
  const remainHours = hours % 8
  
  if (days === 0) return `${remainHours}시간`
  if (remainHours === 0) return `${days}일`
  return `${days}일 ${remainHours}시간`
}

async function handleUpdate() {
  const validTasks = editForm.value.tasks.filter(t => t.description.trim())
  if (validTasks.length === 0) {
    alert('최소 1개 이상의 Task를 입력해주세요.')
    return
  }
  
  isSaving.value = true
  try {
    await $fetch(`/api/report/weekly/${reportId.value}/update`, {
      method: 'PUT',
      body: {
        reportYear: editForm.value.reportYear,
        reportWeek: editForm.value.reportWeek,
        weekStartDate: editForm.value.weekStartDate,
        weekEndDate: editForm.value.weekEndDate,
        tasks: validTasks.map(t => ({
          projectId: t.projectId,
          taskType: t.taskType,
          taskDescription: t.description,
          taskHours: t.hours || 0,
          isCompleted: t.isCompleted
        })),
        issueDescription: editForm.value.issueDescription,
        vacationDescription: editForm.value.vacationDescription,
        remarkDescription: editForm.value.remarkDescription
      }
    })
    alert('저장되었습니다.')
    isEditing.value = false
    await loadReport()
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

async function handleSubmit() {
  if (!confirm('제출하시겠습니까? 제출 후에는 수정할 수 없습니다.')) return
  
  isSubmitting.value = true
  try {
    await $fetch(`/api/report/weekly/${reportId.value}/submit`, { method: 'POST' })
    alert('제출되었습니다.')
    await loadReport()
  } catch (e: any) {
    alert(e.data?.message || '제출에 실패했습니다.')
  } finally {
    isSubmitting.value = false
  }
}

async function handleDelete() {
  const authorName = report.value?.authorName || ''
  const weekInfo = `${report.value?.reportYear}년 ${report.value?.reportWeek}주차`
  
  if (!confirm(`정말 삭제하시겠습니까?\n\n작성자: ${authorName}\n주차: ${weekInfo}\n\n삭제된 보고서는 복구할 수 없습니다.`)) return
  
  isDeleting.value = true
  try {
    await $fetch(`/api/report/weekly/${reportId.value}/delete`, { method: 'DELETE' })
    alert('삭제되었습니다.')
    router.push('/report/weekly')
  } catch (e: any) {
    alert(e.data?.message || '삭제에 실패했습니다.')
  } finally {
    isDeleting.value = false
  }
}

async function requestAiReview() {
  isReviewing.value = true
  try {
    const res = await $fetch<{ review: string; reviewedAt: string }>('/api/report/review', {
      method: 'POST',
      body: { reportId: parseInt(reportId.value) }
    })
    report.value.aiReview = res.review
    report.value.aiReviewAt = res.reviewedAt
  } catch (e: any) {
    alert(e.data?.message || 'AI 리뷰 요청에 실패했습니다.')
  } finally {
    isReviewing.value = false
  }
}

function renderMarkdown(text: string): string {
  if (!text) return ''
  return text
    .replace(/^### (.+)$/gm, '<h6 class="fw-bold mt-3">$1</h6>')
    .replace(/^## (.+)$/gm, '<h5 class="fw-bold mt-3">$1</h5>')
    .replace(/^# (.+)$/gm, '<h5 class="fw-bold mt-3">$1</h5>')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/^- (.+)$/gm, '• $1<br>')
    .replace(/\n/g, '<br>')
}

function formatDateTime(dateStr: string): string {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`
}

function formatDate(dateStr: string) {
  if (!dateStr) return ''
  return dateStr.split('T')[0]
}

function getStatusBadgeClass(status: string) {
  const classes: Record<string, string> = {
    'DRAFT': 'badge bg-secondary',
    'SUBMITTED': 'badge bg-success',
    'AGGREGATED': 'badge bg-info'
  }
  return classes[status] || 'badge bg-secondary'
}

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    'DRAFT': '작성중',
    'SUBMITTED': '제출완료',
    'AGGREGATED': '취합완료'
  }
  return texts[status] || status
}
</script>

<style scoped>
.modal.show {
  background-color: rgba(0, 0, 0, 0.5);
}
.ai-review-content {
  line-height: 1.8;
  font-size: 0.95rem;
}
.ai-review-content h5, .ai-review-content h6 {
  color: #0d6efd;
  margin-top: 1rem;
}
</style>
