<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 id="ai-review-section" 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-bar-chart me-2"></i>주간보고 작성 품질 결과</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>
                {{ qualityScore ? '재평가' : '품질 평가' }}
              </button>
            </div>
            <div class="card-body">
              <!-- 품질 점수가 있는 경우 -->
              <div v-if="qualityScore">
                <!-- 1. 총평 (맨 위) -->
                <div class="alert mb-4" :class="getOverallAlertClass(qualityScore.overall)">
                  <div class="d-flex align-items-start">
                    <i class="bi bi-chat-quote fs-4 me-3"></i>
                    <div>
                      <strong class="d-block mb-1">총평</strong>
                      {{ qualityScore.summary || '-' }}
                    </div>
                  </div>
                </div>
                
                <!-- 2. 점수 그리드 (2열) -->
                <div class="row g-3 mb-4">
                  <!-- 구체성 -->
                  <div class="col-md-6">
                    <div class="card h-100">
                      <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                          <strong>구체성</strong>
                          <span class="fs-5 fw-bold" :class="getScoreTextClass(qualityScore.specificity?.score)">
                            {{ getScoreGrade(qualityScore.specificity?.score || 0) }}
                          </span>
                        </div>
                        <div class="small text-muted">{{ qualityScore.specificity?.improvement || '-' }}</div>
                      </div>
                    </div>
                  </div>
                  <!-- 완결성 -->
                  <div class="col-md-6">
                    <div class="card h-100">
                      <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                          <strong>완결성</strong>
                          <span class="fs-5 fw-bold" :class="getScoreTextClass(qualityScore.completeness?.score)">
                            {{ getScoreGrade(qualityScore.completeness?.score || 0) }}
                          </span>
                        </div>
                        <div class="small text-muted">{{ qualityScore.completeness?.improvement || '-' }}</div>
                      </div>
                    </div>
                  </div>
                  <!-- 시간산정 -->
                  <div class="col-md-6">
                    <div class="card h-100">
                      <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                          <strong>시간산정</strong>
                          <span class="fs-5 fw-bold" :class="getScoreTextClass(qualityScore.timeEstimation?.score)">
                            {{ getScoreGrade(qualityScore.timeEstimation?.score || 0) }}
                          </span>
                        </div>
                        <div class="small text-muted">{{ qualityScore.timeEstimation?.improvement || '-' }}</div>
                      </div>
                    </div>
                  </div>
                  <!-- 계획성 -->
                  <div class="col-md-6">
                    <div class="card h-100">
                      <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                          <strong>계획성</strong>
                          <span class="fs-5 fw-bold" :class="getScoreTextClass(qualityScore.planning?.score)">
                            {{ getScoreGrade(qualityScore.planning?.score || 0) }}
                          </span>
                        </div>
                        <div class="small text-muted">{{ qualityScore.planning?.improvement || '-' }}</div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 3. 종합 점수 -->
                <div class="text-center mb-4">
                  <span class="badge fs-4 px-4 py-2" :class="getOverallBadgeClass(qualityScore.overall)">
                    종합: {{ getScoreGrade(qualityScore.overall || 0) }}
                  </span>
                </div>
                
                <!-- 4. 작성 가이드 (모범 답안) -->
                <div v-if="qualityScore.bestPractice" class="card bg-light">
                  <div class="card-header bg-secondary bg-opacity-10">
                    <strong><i class="bi bi-lightbulb me-2"></i>작성 가이드 (모범 답안)</strong>
                    <div class="small text-muted">아래 예시를 참고하여 주간보고를 보완해보세요</div>
                  </div>
                  <div class="card-body">
                    <!-- 금주 실적 모범 답안 -->
                    <div v-if="qualityScore.bestPractice.workTasks?.length" class="mb-3">
                      <h6 class="text-primary mb-2">
                        <i class="bi bi-check2-square me-1"></i>금주 실적
                      </h6>
                      <ul class="list-group list-group-flush">
                        <li v-for="(task, idx) in qualityScore.bestPractice.workTasks" :key="'bp-work-'+idx" 
                          class="list-group-item bg-transparent px-0 py-2">
                          <i class="bi bi-dot text-primary"></i>
                          <span class="small">{{ task }}</span>
                        </li>
                      </ul>
                    </div>
                    
                    <!-- 차주 계획 모범 답안 -->
                    <div v-if="qualityScore.bestPractice.planTasks?.length">
                      <h6 class="text-success mb-2">
                        <i class="bi bi-calendar-check me-1"></i>차주 계획
                      </h6>
                      <ul class="list-group list-group-flush">
                        <li v-for="(task, idx) in qualityScore.bestPractice.planTasks" :key="'bp-plan-'+idx" 
                          class="list-group-item bg-transparent px-0 py-2">
                          <i class="bi bi-dot text-success"></i>
                          <span class="small">{{ task }}</span>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
                
                <div class="text-muted small text-end mt-3">
                  <i class="bi bi-clock me-1"></i>평가일시: {{ formatDateTime(report.aiReviewAt) }}
                </div>
              </div>
              
              <!-- 품질 점수가 없는 경우 -->
              <div v-else class="text-muted text-center py-4">
                <i class="bi bi-bar-chart display-4 mb-3 d-block opacity-50"></i>
                <p class="mb-0">아직 품질 평가가 없습니다.<br>품질 평가 버튼을 클릭하여 AI 평가를 받아보세요.</p>
              </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>
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-outline-success" @click="showAiModal = true">
                  <i class="bi bi-robot me-1"></i>AI 자동채우기
                </button>
                <button type="button" class="btn btn-sm btn-outline-primary" @click="showProjectModal = true">
                  <i class="bi bi-plus"></i> 프로젝트 추가
                </button>
              </div>
            </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 auto-resize" v-model="task.description" rows="1" 
                            placeholder="작업 내용" @input="autoResize"></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 auto-resize" v-model="task.description" rows="1" 
                            placeholder="계획 내용" @input="autoResize"></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 class="modal fade show d-block" tabindex="-1" v-if="showAiReviewConfirmModal">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header bg-warning bg-opacity-10">
            <h5 class="modal-title">
              <i class="bi bi-exclamation-triangle text-warning me-2"></i>품질 평가 필요
            </h5>
            <button type="button" class="btn-close" @click="handleAiReviewCancel"></button>
          </div>
          <div class="modal-body">
            <p class="mb-0">
              제출 전에 <strong>작성 품질 평가</strong>를 선행하고 제출하셔야 합니다.<br><br>
              지금 품질 평가를 진행하시겠습니까?
            </p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="handleAiReviewCancel">아니오</button>
            <button type="button" class="btn btn-primary" @click="handleAiReviewConfirm">
              <i class="bi bi-bar-chart me-1"></i>예, 품질 평가 진행
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showAiReviewConfirmModal" @click="handleAiReviewCancel"></div>
    
    <!-- AI 자동채우기 모달 -->
    <div class="modal fade" :class="{ show: showAiModal }" :style="{ display: showAiModal ? 'block' : 'none' }">
      <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-robot me-2"></i>AI 자동채우기
              <span v-if="aiStep === 'matching'" class="badge bg-primary ms-2">프로젝트 매칭</span>
            </h5>
            <button type="button" class="btn-close" @click="closeAiModal"></button>
          </div>
          <div class="modal-body">
            <!-- Step 1: 입력 -->
            <template v-if="aiStep === 'input'">
              <!-- 입력 방식 탭 -->
              <ul class="nav nav-tabs mb-3">
                <li class="nav-item">
                  <a class="nav-link" :class="{ active: aiInputMode === 'text' }" href="#" @click.prevent="aiInputMode = 'text'">
                    <i class="bi bi-fonts me-1"></i>텍스트
                  </a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" :class="{ active: aiInputMode === 'image' }" href="#" @click.prevent="aiInputMode = 'image'">
                    <i class="bi bi-image me-1"></i>이미지
                  </a>
                </li>
              </ul>
              
              <!-- 텍스트 입력 -->
              <div v-if="aiInputMode === 'text'">
                <textarea 
                  class="form-control font-monospace" 
                  v-model="aiRawText" 
                  rows="12"
                  placeholder="주간보고 내용을 붙여넣으세요.

예시:
- PIMS 고도화: API 개발 완료 (8시간), UI 수정 (4시간)
- 차주: 테스트 진행 예정 (16시간)
- 이슈: 서버 메모리 부족
- 휴가: 1/10(금) 연차"
                ></textarea>
              </div>
              
              <!-- 이미지 입력 -->
              <div v-if="aiInputMode === 'image'">
                <div 
                  class="upload-zone p-5 text-center border rounded"
                  :class="{ 'border-primary bg-light': aiIsDragging }"
                  tabindex="0"
                  @dragover.prevent="aiIsDragging = true"
                  @dragleave.prevent="aiIsDragging = false"
                  @drop.prevent="handleAiDrop"
                  @paste="handleAiPaste"
                  @click="($refs.aiFileInput as HTMLInputElement).click()"
                >
                  <input 
                    ref="aiFileInput" 
                    type="file" 
                    multiple 
                    accept="image/*" 
                    class="d-none" 
                    @change="handleAiFileSelect"
                  />
                  <i class="bi bi-cloud-arrow-up display-4 text-muted"></i>
                  <p class="mt-2 mb-0 text-muted">
                    이미지를 드래그하거나 클릭해서 업로드<br>
                    <small>또는 <strong>Ctrl+V</strong>로 붙여넣기 (최대 10장)</small>
                  </p>
                </div>
                
                <div v-if="aiUploadedImages.length > 0" class="mt-3">
                  <label class="form-label small">업로드된 이미지 ({{ aiUploadedImages.length }}장)</label>
                  <div class="d-flex flex-wrap gap-2">
                    <div v-for="(img, idx) in aiUploadedImages" :key="idx" class="position-relative">
                      <img :src="img" class="rounded border" style="width: 100px; height: 100px; object-fit: cover;" />
                      <button 
                        type="button" 
                        class="btn btn-sm btn-danger position-absolute top-0 end-0 rounded-circle"
                        style="transform: translate(30%, -30%); width: 20px; height: 20px; padding: 0; font-size: 10px;"
                        @click="aiUploadedImages.splice(idx, 1)"
                      >
                        <i class="bi bi-x"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="alert alert-info mt-3 mb-0 small">
                <i class="bi bi-info-circle me-1"></i>
                AI가 분석한 내용은 기존에 작성된 내용과 <strong>병합</strong>됩니다.
              </div>
            </template>
            
            <!-- Step 2: 프로젝트 매칭 -->
            <template v-if="aiStep === 'matching' && aiParsedResult">
              <div class="alert alert-warning small mb-3">
                <i class="bi bi-exclamation-triangle me-1"></i>
                AI가 분석한 프로젝트를 기존 프로젝트와 매칭해주세요.
              </div>
              
              <div v-for="(proj, pIdx) in aiParsedResult.projects" :key="pIdx" class="card mb-3">
                <div class="card-header bg-light">
                  <div class="row align-items-center">
                    <div class="col">
                      <small class="text-muted">AI 분석 결과:</small>
                      <strong class="ms-1">{{ proj.originalName }}</strong>
                    </div>
                  </div>
                </div>
                <div class="card-body">
                  <div class="mb-3">
                    <label class="form-label small fw-bold">매칭할 프로젝트 선택</label>
                    <select class="form-select" v-model="proj.matchedProjectId">
                      <option :value="null" class="text-muted">-- 선택하세요 (미선택시 제외) --</option>
                      <option v-for="p in allProjects" :key="p.projectId" :value="p.projectId">
                        {{ p.projectCode }} - {{ p.projectName }}
                      </option>
                    </select>
                  </div>
                  
                  <!-- 태스크 미리보기 -->
                  <div class="row">
                    <div class="col-md-6" v-if="proj.workTasks.length > 0">
                      <label class="form-label small text-primary fw-bold">
                        <i class="bi bi-check2-square me-1"></i>금주 실적 ({{ proj.workTasks.length }}건)
                      </label>
                      <ul class="list-unstyled small mb-0">
                        <li v-for="(task, tIdx) in proj.workTasks" :key="'w'+tIdx" class="text-truncate mb-1">
                          <i class="bi bi-dot"></i>{{ task.description }}
                          <span v-if="task.hours" class="text-muted">({{ task.hours }}h)</span>
                        </li>
                      </ul>
                    </div>
                    <div class="col-md-6" v-if="proj.planTasks.length > 0">
                      <label class="form-label small text-success fw-bold">
                        <i class="bi bi-calendar-check me-1"></i>차주 계획 ({{ proj.planTasks.length }}건)
                      </label>
                      <ul class="list-unstyled small mb-0">
                        <li v-for="(task, tIdx) in proj.planTasks" :key="'p'+tIdx" class="text-truncate mb-1">
                          <i class="bi bi-dot"></i>{{ task.description }}
                          <span v-if="task.hours" class="text-muted">({{ task.hours }}h)</span>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 공통사항 미리보기 -->
              <div v-if="aiParsedResult.issueDescription || aiParsedResult.vacationDescription || aiParsedResult.remarkDescription" 
                   class="card">
                <div class="card-header bg-light">
                  <strong><i class="bi bi-chat-text me-1"></i>공통사항</strong>
                </div>
                <div class="card-body small">
                  <div v-if="aiParsedResult.issueDescription" class="mb-2">
                    <span class="badge bg-danger me-1">이슈</span>{{ aiParsedResult.issueDescription }}
                  </div>
                  <div v-if="aiParsedResult.vacationDescription" class="mb-2">
                    <span class="badge bg-info me-1">휴가</span>{{ aiParsedResult.vacationDescription }}
                  </div>
                  <div v-if="aiParsedResult.remarkDescription">
                    <span class="badge bg-secondary me-1">기타</span>{{ aiParsedResult.remarkDescription }}
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="modal-footer">
            <!-- Step 1: 입력 -->
            <template v-if="aiStep === 'input'">
              <button type="button" class="btn btn-secondary" @click="closeAiModal">취소</button>
              <button 
                type="button" 
                class="btn btn-primary" 
                @click="runAiParse"
                :disabled="isAiParsing || (aiInputMode === 'text' ? !aiRawText.trim() : aiUploadedImages.length === 0)"
              >
                <span v-if="isAiParsing" class="spinner-border spinner-border-sm me-1"></span>
                <i v-else class="bi bi-robot me-1"></i>
                AI 분석
              </button>
            </template>
            
            <!-- Step 2: 매칭 -->
            <template v-if="aiStep === 'matching'">
              <button type="button" class="btn btn-outline-secondary" @click="aiStep = 'input'">
                <i class="bi bi-arrow-left me-1"></i>이전
              </button>
              <button type="button" class="btn btn-primary" @click="applyAiResult" :disabled="!hasMatchedProjects">
                <i class="bi bi-check-lg me-1"></i>적용하기
              </button>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showAiModal" @click="closeAiModal"></div>
  </div>
</template>

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

const { currentUser, fetchCurrentUser, hasRole } = useAuth()
const { getWeekDates, getWeeksInYear, changeWeek: calcChangeWeek } = useWeekCalc()
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 showAiReviewConfirmModal = ref(false)

// AI 자동채우기 모달
const showAiModal = ref(false)
const aiStep = ref<'input' | 'matching'>('input')
const aiInputMode = ref<'text' | 'image'>('text')
const aiRawText = ref('')
const aiUploadedImages = ref<string[]>([])
const aiIsDragging = ref(false)
const isAiParsing = ref(false)
const aiParsedResult = ref<any>(null)

const isAdmin = computed(() => hasRole('ROLE_ADMIN'))

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 qualityScore = computed(() => {
  if (!report.value?.aiReview) return null
  try {
    return JSON.parse(report.value.aiReview)
  } catch {
    return null
  }
})

// 점수 → 등급 변환
function getScoreGrade(score: number): string {
  if (score >= 8) return '우수'
  if (score >= 5) return '적합'
  return '미흡'
}

// 점수별 텍스트 색상 (적합/우수=녹색, 미흡=노랑)
function getScoreTextClass(score: number): string {
  if (score >= 5) return 'text-success'
  return 'text-warning'
}

// 점수별 프로그레스바 색상
function getScoreColorClass(score: number): string {
  if (score >= 5) return 'bg-success'
  return 'bg-warning'
}

// 종합 점수 배지 색상
function getOverallBadgeClass(score: number): string {
  if (score >= 5) return 'bg-success'
  return 'bg-warning text-dark'
}

// 종합 점수 알림 색상
function getOverallAlertClass(score: number): string {
  if (score >= 5) return 'alert-success'
  return 'alert-warning'
}

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 || ''
    }
    
    // 수정 모드 진입 시 textarea 높이 조절
    initAutoResize()
  }
})

// === textarea 자동 높이 조절 ===
function autoResize(e: Event) {
  const textarea = e.target as HTMLTextAreaElement
  textarea.style.height = 'auto'
  textarea.style.height = textarea.scrollHeight + 'px'
}

function initAutoResize() {
  nextTick(() => {
    document.querySelectorAll('textarea.auto-resize').forEach((el) => {
      const textarea = el as HTMLTextAreaElement
      textarea.style.height = 'auto'
      textarea.style.height = textarea.scrollHeight + 'px'
    })
  })
}

// editForm.tasks 변경 시 textarea 높이 조절
watch(() => editForm.value.tasks, () => {
  initAutoResize()
}, { deep: true })

// 프로젝트별 시간 계산
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) {
  const { year, week } = calcChangeWeek(editForm.value.reportYear, editForm.value.reportWeek, delta)
  editForm.value.reportYear = year
  editForm.value.reportWeek = week
  
  // 해당 주차의 월요일~일요일 계산
  const weekInfo = getWeekDates(year, week)
  editForm.value.weekStartDate = weekInfo.startDateStr
  editForm.value.weekEndDate = weekInfo.endDateStr
}

// 수정 모드 함수들
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() {
  // AI 리뷰가 없으면 먼저 확인
  if (!report.value?.aiReview) {
    showAiReviewConfirmModal.value = true
    return
  }
  
  await doSubmit()
}

async function doSubmit() {
  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
  }
}

// AI 리뷰 확인 모달에서 "예" 클릭
async function handleAiReviewConfirm() {
  showAiReviewConfirmModal.value = false
  await requestAiReview()
  
  // AI 리뷰 섹션으로 포커스 이동
  nextTick(() => {
    const aiReviewSection = document.getElementById('ai-review-section')
    if (aiReviewSection) {
      aiReviewSection.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  })
}

// AI 리뷰 확인 모달에서 "아니오" 클릭
function handleAiReviewCancel() {
  showAiReviewConfirmModal.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<{ qualityScore: any; reviewedAt: string }>('/api/report/review', {
      method: 'POST',
      body: { reportId: parseInt(reportId.value) }
    })
    report.value.aiReview = JSON.stringify(res.qualityScore)
    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-warning',
    'SUBMITTED': 'badge bg-success',
    'AGGREGATED': 'badge bg-success'
  }
  return classes[status] || 'badge bg-secondary'
}

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

// === AI 자동채우기 관련 ===
function closeAiModal() {
  showAiModal.value = false
  aiStep.value = 'input'
  aiRawText.value = ''
  aiUploadedImages.value = []
  aiParsedResult.value = null
}

function handleAiDrop(e: DragEvent) {
  aiIsDragging.value = false
  const files = e.dataTransfer?.files
  if (files) processAiFiles(Array.from(files))
}

function handleAiPaste(e: ClipboardEvent) {
  const items = e.clipboardData?.items
  if (!items) return
  
  const imageFiles: File[] = []
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.startsWith('image/')) {
      const file = items[i].getAsFile()
      if (file) imageFiles.push(file)
    }
  }
  
  if (imageFiles.length > 0) {
    e.preventDefault()
    processAiFiles(imageFiles)
  }
}

function handleAiFileSelect(e: Event) {
  const input = e.target as HTMLInputElement
  if (input.files) processAiFiles(Array.from(input.files))
}

function processAiFiles(files: File[]) {
  const maxFiles = 10 - aiUploadedImages.value.length
  const toProcess = files.slice(0, maxFiles)
  
  toProcess.forEach(file => {
    if (!file.type.startsWith('image/')) return
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target?.result) {
        aiUploadedImages.value.push(e.target.result as string)
      }
    }
    reader.readAsDataURL(file)
  })
}

async function runAiParse() {
  isAiParsing.value = true
  try {
    let res: any
    if (aiInputMode.value === 'text') {
      res = await $fetch<any>('/api/ai/parse-my-report', {
        method: 'POST',
        body: { rawText: aiRawText.value }
      })
    } else {
      res = await $fetch<any>('/api/ai/parse-my-report-image', {
        method: 'POST',
        body: { images: aiUploadedImages.value }
      })
    }
    
    // 파싱 결과를 임시 저장하고 매칭 단계로 이동
    if (res.parsed?.projects?.length > 0) {
      aiParsedResult.value = {
        projects: res.parsed.projects.map((p: any) => ({
          originalName: p.projectName || '알 수 없음',
          matchedProjectId: p.matchedProjectId || null,
          workTasks: p.workTasks || [],
          planTasks: p.planTasks || []
        })),
        issueDescription: res.parsed.issueDescription,
        vacationDescription: res.parsed.vacationDescription,
        remarkDescription: res.parsed.remarkDescription
      }
      aiStep.value = 'matching'
    } else {
      alert('분석된 내용이 없습니다.')
    }
  } catch (e: any) {
    alert(e.data?.message || 'AI 분석에 실패했습니다.')
  } finally {
    isAiParsing.value = false
  }
}

// 매칭된 프로젝트가 있는지 확인
const hasMatchedProjects = computed(() => {
  if (!aiParsedResult.value) return false
  return aiParsedResult.value.projects.some((p: any) => p.matchedProjectId !== null)
})

// 매칭 완료 후 적용
function applyAiResult() {
  if (!aiParsedResult.value) return
  
  const parsed = aiParsedResult.value
  
  // 프로젝트별 태스크 병합
  for (const proj of parsed.projects) {
    const projectId = proj.matchedProjectId
    if (!projectId) continue  // 미선택은 제외
    
    // 금주 실적 추가
    for (const task of proj.workTasks) {
      if (task.description?.trim()) {
        editForm.value.tasks.push({
          projectId,
          taskType: 'WORK',
          description: task.description,
          hours: task.hours || 0,
          isCompleted: task.isCompleted !== false
        })
      }
    }
    
    // 차주 계획 추가
    for (const task of proj.planTasks) {
      if (task.description?.trim()) {
        editForm.value.tasks.push({
          projectId,
          taskType: 'PLAN',
          description: task.description,
          hours: task.hours || 0,
          isCompleted: false
        })
      }
    }
  }
  
  // 공통사항 병합
  if (parsed.issueDescription) {
    editForm.value.issueDescription = editForm.value.issueDescription 
      ? editForm.value.issueDescription + '\n' + parsed.issueDescription 
      : parsed.issueDescription
  }
  if (parsed.vacationDescription) {
    editForm.value.vacationDescription = editForm.value.vacationDescription 
      ? editForm.value.vacationDescription + '\n' + parsed.vacationDescription 
      : parsed.vacationDescription
  }
  if (parsed.remarkDescription) {
    editForm.value.remarkDescription = editForm.value.remarkDescription 
      ? editForm.value.remarkDescription + '\n' + parsed.remarkDescription 
      : parsed.remarkDescription
  }
  
  closeAiModal()
}
</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;
}
textarea.auto-resize {
  overflow: hidden;
  resize: none;
  min-height: 32px;
}
.upload-zone {
  cursor: pointer;
  transition: all 0.2s;
}
.upload-zone:hover {
  background-color: #f8f9fa;
}
</style>
