<template>
  <div>
    <AppHeader />
    
    <div class="container py-4">
      <h4 class="mb-4">
        <i class="bi bi-pencil-square me-2"></i>주간보고 작성
      </h4>
      
      <form @submit.prevent="handleSubmit">
        <!-- 주차 정보 -->
        <div class="card mb-4">
          <div class="card-header"><strong>보고 주차</strong></div>
          <div class="card-body">
            <div class="d-flex align-items-center">
              <h5 class="mb-0">
                <i class="bi bi-calendar-week me-2 text-primary"></i>
                <strong>{{ form.reportYear }}년 {{ form.reportWeek }}주차</strong>
                <span class="text-muted ms-2">({{ form.weekStartDate }} ~ {{ form.weekEndDate }})</span>
              </h5>
            </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-warning" @click="openMaintenanceModal">
                <i class="bi bi-tools me-1"></i>유지보수 불러오기
              </button>
              <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-if="projectGroups.length === 0" class="text-center text-muted py-4">
              프로젝트를 추가해주세요.
            </div>
            
            <div v-for="(group, gIdx) in projectGroups" :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="removeProjectGroup(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">
                        <i class="bi bi-check2-square me-1"></i>금주 실적
                        <span class="badge bg-primary ms-1">{{ formatHoursDisplay(getGroupWorkHours(group)) }}</span>
                      </label>
                      <button type="button" class="btn btn-sm btn-outline-primary" @click="addTask(group.projectId, 'WORK')">
                        <i class="bi bi-plus"></i>
                      </button>
                    </div>
                    <div v-for="(task, tIdx) in getWorkTasks(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="'work-chk-'+group.projectId+'-'+tIdx" />
                          <label class="form-check-label small" :for="'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="removeTask(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">
                        <i class="bi bi-calendar-check me-1"></i>차주 계획
                        <span class="badge bg-success ms-1">{{ formatHoursDisplay(getGroupPlanHours(group)) }}</span>
                      </label>
                      <button type="button" class="btn btn-sm btn-outline-success" @click="addTask(group.projectId, 'PLAN')">
                        <i class="bi bi-plus"></i>
                      </button>
                    </div>
                    <div v-for="(task, tIdx) in getPlanTasks(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="removeTask(group.projectId, 'PLAN', tIdx)">
                          <i class="bi bi-x"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 총계 -->
        <div class="card mb-4 border-primary" v-if="form.tasks.length > 0">
          <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">이슈/리스크</label>
                <textarea class="form-control" rows="3" v-model="form.issueDescription"></textarea>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">휴가일정</label>
                <textarea class="form-control" rows="3" v-model="form.vacationDescription"></textarea>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">기타사항</label>
                <textarea class="form-control" rows="3" v-model="form.remarkDescription"></textarea>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 버튼 -->
        <div class="d-flex justify-content-end gap-2">
          <NuxtLink to="/report/weekly" class="btn btn-secondary">취소</NuxtLink>
          <button type="submit" class="btn btn-primary" :disabled="isSaving || !canSubmit">
            <span v-if="isSaving" class="spinner-border spinner-border-sm me-1"></span>
            저장
          </button>
        </div>
      </form>
    </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="addProjectGroup(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" :class="{ show: showLoadConfirmModal }" :style="{ display: showLoadConfirmModal ? 'block' : 'none' }">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-clipboard-check me-2"></i>이전 계획 불러오기
            </h5>
            <button type="button" class="btn-close" @click="showLoadConfirmModal = false"></button>
          </div>
          <div class="modal-body">
            <p class="mb-0">
              지난주에 작성된 주간보고 내용이 없습니다.<br>
              최근에 작성한 <strong>{{ recentReportInfo?.reportYear }}년 {{ recentReportInfo?.reportWeek }}주차</strong> 계획을 불러오시겠습니까?
            </p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showLoadConfirmModal = false">취소</button>
            <button type="button" class="btn btn-primary" @click="confirmLoadRecentPlan">
              <i class="bi bi-download me-1"></i>불러오기
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showLoadConfirmModal" @click="showLoadConfirmModal = false"></div>
    
    <!-- 기존 보고서 존재 확인 모달 -->
    <div class="modal fade" :class="{ show: showExistingReportModal }" :style="{ display: showExistingReportModal ? 'block' : 'none' }">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-exclamation-circle me-2 text-warning"></i>주간보고 존재
            </h5>
          </div>
          <div class="modal-body">
            <p class="mb-0">
              <strong>{{ existingReportInfo?.reportYear }}년 {{ existingReportInfo?.reportWeek }}주차</strong>에 작성된 주간보고가 이미 존재합니다.<br>
              수정화면으로 이동합니다.
            </p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="goToList">취소</button>
            <button type="button" class="btn btn-primary" @click="goToExistingReport">
              <i class="bi bi-pencil me-1"></i>확인
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showExistingReportModal"></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': isDragging }"
                  tabindex="0"
                  @dragover.prevent="isDragging = true"
                  @dragleave.prevent="isDragging = 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 class="modal fade" :class="{ show: showMaintenanceModal }" :style="{ display: showMaintenanceModal ? 'block' : 'none' }">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title"><i class="bi bi-tools me-2"></i>유지보수 업무 불러오기</h5>
            <button type="button" class="btn-close" @click="showMaintenanceModal = false"></button>
          </div>
          <div class="modal-body">
            <!-- Step 1: 프로젝트 선택 -->
            <div v-if="maintenanceStep === 'select'">
              <div class="mb-3">
                <label class="form-label">프로젝트 선택</label>
                <select class="form-select" v-model="maintenanceProjectId" @change="loadMaintenanceTasks">
                  <option value="">선택하세요</option>
                  <option v-for="p in allProjects" :key="p.projectId" :value="p.projectId">{{ p.projectName }}</option>
                </select>
              </div>
              <div v-if="isLoadingMaintenance" class="text-center py-4">
                <div class="spinner-border spinner-border-sm"></div> 유지보수 업무 조회 중...
              </div>
              <div v-else-if="maintenanceTasks.length === 0 && maintenanceProjectId" class="alert alert-info">
                해당 주차에 완료된 유지보수 업무가 없습니다.
              </div>
              <div v-else-if="maintenanceTasks.length > 0">
                <div class="mb-2 text-muted small">{{ form.weekStartDate }} ~ {{ form.weekEndDate }} 완료 업무</div>
                <div class="list-group">
                  <label v-for="t in maintenanceTasks" :key="t.taskId" class="list-group-item list-group-item-action">
                    <div class="d-flex align-items-start">
                      <input type="checkbox" class="form-check-input me-2 mt-1" v-model="t.selected" />
                      <div class="flex-grow-1">
                        <div class="fw-bold">{{ t.requestTitle }}</div>
                        <small class="text-muted">
                          [{{ getTypeLabel(t.taskType) }}] {{ t.requesterName || '-' }}
                          <span v-if="t.resolutionContent"> → {{ truncate(t.resolutionContent, 30) }}</span>
                        </small>
                      </div>
                    </div>
                  </label>
                </div>
              </div>
            </div>
            <!-- Step 2: AI 변환 결과 -->
            <div v-if="maintenanceStep === 'convert'">
              <div class="mb-2 text-muted small">AI가 생성한 실적 문장 (수정 가능)</div>
              <div v-for="(g, idx) in generatedTasks" :key="idx" class="mb-2">
                <div class="input-group">
                  <span class="input-group-text">{{ getTypeLabel(g.taskType) }}</span>
                  <input type="text" class="form-control" v-model="g.description" />
                  <button class="btn btn-outline-danger" type="button" @click="generatedTasks.splice(idx, 1)">
                    <i class="bi bi-x"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showMaintenanceModal = false">취소</button>
            <template v-if="maintenanceStep === 'select'">
              <button type="button" class="btn btn-primary" @click="convertMaintenance" 
                :disabled="!selectedMaintenanceCount || isConverting">
                <span v-if="isConverting"><span class="spinner-border spinner-border-sm me-1"></span></span>
                AI 실적 변환 ({{ selectedMaintenanceCount }}건)
              </button>
            </template>
            <template v-else>
              <button type="button" class="btn btn-outline-secondary" @click="maintenanceStep = 'select'">이전</button>
              <button type="button" class="btn btn-primary" @click="applyMaintenanceTasks" :disabled="generatedTasks.length === 0">
                <i class="bi bi-check-lg me-1"></i>실적 추가
              </button>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showMaintenanceModal"></div>

    <!-- TODO 연계 확인 모달 -->
    <div class="modal fade" :class="{ show: showTodoLinkModal }" :style="{ display: showTodoLinkModal ? 'block' : 'none' }">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title"><i class="bi bi-check2-square me-2 text-success"></i>TODO 완료 확인</h5>
            <button type="button" class="btn-close" @click="closeTodoLinkModal"></button>
          </div>
          <div class="modal-body">
            <p class="text-muted small">작성한 실적과 유사한 TODO가 발견되었습니다. 완료 처리할 항목을 선택하세요.</p>
            <div class="list-group">
              <label v-for="todo in similarTodos" :key="todo.todoId" class="list-group-item list-group-item-action">
                <div class="d-flex align-items-start">
                  <input type="checkbox" class="form-check-input me-2 mt-1" v-model="todo.selected" />
                  <div class="flex-grow-1">
                    <div class="fw-bold">{{ todo.todoTitle }}</div>
                    <small class="text-muted">
                      {{ todo.projectName || '프로젝트 없음' }}
                      <span v-if="todo.dueDate"> · 마감: {{ todo.dueDate.split('T')[0] }}</span>
                    </small>
                  </div>
                </div>
              </label>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="closeTodoLinkModal">건너뛰기</button>
            <button type="button" class="btn btn-success" @click="completeTodos" :disabled="!hasSelectedTodos || isLinkingTodos">
              <span v-if="isLinkingTodos" class="spinner-border spinner-border-sm me-1"></span>
              <i v-else class="bi bi-check-lg me-1"></i>완료 처리
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showTodoLinkModal"></div>
  </div>
</template>

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

const { fetchCurrentUser } = useAuth()
const route = useRoute()
const { getWeekInfo, getWeekDates, getLastWeekInfo, getActualCurrentWeekInfo, getMonday, changeWeek: calcChangeWeek } = useWeekCalc()
const router = useRouter()
const toast = useToast()

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

interface ProjectGroup {
  projectId: number
  projectCode: string
  projectName: string
}

const allProjects = ref<any[]>([])
const showProjectModal = ref(false)
const isSaving = ref(false)

// 이전 계획 로드 확인 모달
const showLoadConfirmModal = ref(false)
const recentReportInfo = ref<{ reportId: number; reportYear: number; reportWeek: number } | null>(null)

// 기존 보고서 존재 확인 모달
const showExistingReportModal = ref(false)
const existingReportInfo = ref<{ reportId: number; reportYear: number; reportWeek: number } | null>(null)

// 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 isAiParsing = ref(false)
const isDragging = ref(false)

// AI 분석 결과 (매칭 전 임시 저장)
interface AiParsedProject {
  originalName: string
  matchedProjectId: number | null
  workTasks: { description: string; hours: number; isCompleted: boolean }[]
  planTasks: { description: string; hours: number }[]
}
const aiParsedResult = ref<{
  projects: AiParsedProject[]
  issueDescription: string | null
  vacationDescription: string | null
  remarkDescription: string | null
} | null>(null)

// 유지보수 불러오기 모달
const showMaintenanceModal = ref(false)
const maintenanceStep = ref<'select' | 'convert'>('select')
const maintenanceProjectId = ref('')
const maintenanceTasks = ref<any[]>([])
const isLoadingMaintenance = ref(false)
const isConverting = ref(false)
const generatedTasks = ref<{ description: string; taskType: string; sourceTaskIds: number[] }[]>([])

const selectedMaintenanceCount = computed(() => maintenanceTasks.value.filter(t => t.selected).length)

// TODO 연계 모달
const showTodoLinkModal = ref(false)
const similarTodos = ref<any[]>([])
const savedReportId = ref<number | null>(null)
const isLinkingTodos = ref(false)
const hasSelectedTodos = computed(() => similarTodos.value.some(t => t.selected))

const form = ref({
  reportYear: new Date().getFullYear(),
  reportWeek: 1,
  weekStartDate: '',
  weekEndDate: '',
  tasks: [] as TaskItem[],
  issueDescription: '',
  vacationDescription: '',
  remarkDescription: ''
})

const projectGroups = computed<ProjectGroup[]>(() => {
  const projectIds = [...new Set(form.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 = projectGroups.value.map(g => g.projectId)
  return allProjects.value.filter(p => !usedIds.includes(p.projectId))
})

const totalWorkHours = computed(() => 
  form.value.tasks.filter(t => t.taskType === 'WORK').reduce((sum, t) => sum + (t.hours || 0), 0)
)

const totalPlanHours = computed(() => 
  form.value.tasks.filter(t => t.taskType === 'PLAN').reduce((sum, t) => sum + (t.hours || 0), 0)
)

const canSubmit = computed(() => form.value.tasks.some(t => t.description?.trim()))

onMounted(async () => {
  const user = await fetchCurrentUser()
  if (!user) {
    router.push('/login')
    return
  }
  
  await loadProjects()
  const weekValid = await setDefaultWeek(user.employeeId)
  
  // 미래 주차로 접근한 경우 중단
  if (weekValid === false) {
    return
  }
  
  // 이번 주차에 이미 작성한 보고서가 있는지 확인
  const existingReport = await checkExistingReport(user.employeeId)
  if (existingReport) {
    // 이미 작성한 보고서가 있으면 모달로 확인
    existingReportInfo.value = {
      reportId: existingReport.reportId,
      reportYear: form.value.reportYear,
      reportWeek: form.value.reportWeek
    }
    showExistingReportModal.value = true
    return
  }
  
  await loadLastWeekPlan(user.employeeId)
  initAutoResize()
})

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

// 이번 주차에 이미 작성한 보고서 확인
async function checkExistingReport(userId: number) {
  try {
    const res = await $fetch<any>(`/api/report/weekly/list?year=${form.value.reportYear}&week=${form.value.reportWeek}&authorId=${userId}`)
    if (res.reports && res.reports.length > 0) {
      return res.reports[0]
    }
  } catch (e) {
    console.error('기존 보고서 확인 실패:', e)
  }
  return null
}

// 기존 보고서 모달 - 확인 (수정화면으로 이동)
function goToExistingReport() {
  if (existingReportInfo.value) {
    router.replace(`/report/weekly/${existingReportInfo.value.reportId}`)
  }
}

// 기존 보고서 모달 - 취소 (목록으로 이동)
function goToList() {
  // 쿼리 파라미터가 있으면 해당 주차 목록으로 이동
  if (route.query.year && route.query.week) {
    router.replace(`/report/weekly?year=${route.query.year}&week=${route.query.week}`)
  } else {
    router.replace('/report/weekly')
  }
}

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

// 주차 관련 함수들 (useWeekCalc 사용)
function setWeekFromInfo(info: { year: number; week: number; startDateStr: string; endDateStr: string }) {
  form.value.reportYear = info.year
  form.value.reportWeek = info.week
  form.value.weekStartDate = info.startDateStr
  form.value.weekEndDate = info.endDateStr
}

function changeWeek(delta: number) {
  const { year, week } = calcChangeWeek(form.value.reportYear, form.value.reportWeek, delta)
  const weekInfo = getWeekDates(year, week)
  setWeekFromInfo(weekInfo)
}

function setLastWeek() {
  const lastWeek = getLastWeekInfo()
  setWeekFromInfo(lastWeek)
}

function setThisWeek() {
  const thisWeek = getActualCurrentWeekInfo()
  setWeekFromInfo(thisWeek)
}

async function setDefaultWeek(userId: number) {
  // 쿼리 파라미터가 있으면 해당 주차로 설정
  if (route.query.year && route.query.week) {
    const year = parseInt(route.query.year as string)
    const week = parseInt(route.query.week as string)
    
    // 미래 주차 검증
    const currentWeek = getActualCurrentWeekInfo()
    const isFutureWeek = year > currentWeek.year || (year === currentWeek.year && week > currentWeek.week)
    
    if (isFutureWeek) {
      toast.warning('작성할 수 없는 주차입니다.')
      router.replace('/report/weekly')
      return false
    }
    
    const weekInfo = getWeekDates(year, week)
    setWeekFromInfo(weekInfo)
    return true
  }
  
  const now = new Date()
  const dayOfWeek = now.getDay() // 0=일, 1=월, ...
  const hour = now.getHours()
  
  // 기본값: 이번 주
  const thisWeek = getActualCurrentWeekInfo()
  setWeekFromInfo(thisWeek)
  
  // 월요일 9시 전인 경우, 지난주 보고서 확인
  if (dayOfWeek === 1 && hour < 9) {
    const lastWeek = getLastWeekInfo()
    
    try {
      // 현재 사용자의 지난주 보고서가 있는지 확인
      const res = await $fetch<any>(`/api/report/weekly/list?year=${lastWeek.year}&week=${lastWeek.week}&authorId=${userId}`)
      const hasLastWeekReport = res.reports && res.reports.length > 0
      
      // 지난주 보고서가 없으면 지난주로 설정
      if (!hasLastWeekReport) {
        setWeekFromInfo(lastWeek)
      }
    } catch (e) {
      console.error('지난주 보고서 확인 실패:', e)
    }
  }
  
  return true
}

// 지난주 계획을 이번주 실적에 로드
async function loadLastWeekPlan(userId: number) {
  try {
    // 작성하려는 주차
    const targetYear = form.value.reportYear
    const targetWeek = form.value.reportWeek
    
    // 직전 주차 계산
    const prevWeek = calcChangeWeek(targetYear, targetWeek, -1)
    
    // 작성하려는 주차 이전의 보고서만 조회 (최신순, 1건)
    const res = await $fetch<any>(`/api/report/weekly/list?authorId=${userId}&beforeYear=${targetYear}&beforeWeek=${targetWeek}&limit=1`)
    
    if (!res.reports || res.reports.length === 0) {
      return
    }
    
    const recent = res.reports[0]
    
    if (recent.reportYear === prevWeek.year && recent.reportWeek === prevWeek.week) {
      // 직전 주차면 → 자동 로드
      await loadPlanFromReport(recent.reportId)
    } else {
      // 직전 주차가 아니면 → 모달로 물어봄
      recentReportInfo.value = {
        reportId: recent.reportId,
        reportYear: recent.reportYear,
        reportWeek: recent.reportWeek
      }
      showLoadConfirmModal.value = true
    }
  } catch (e) {
    console.error('이전 계획 로드 실패:', e)
  }
}

// 보고서에서 계획 로드 (공통 함수)
async function loadPlanFromReport(reportId: number) {
  try {
    const detail = await $fetch<any>(`/api/report/weekly/${reportId}/detail`)
    
    if (!detail.projects || detail.projects.length === 0) {
      return
    }
    
    // 모든 프로젝트의 planTasks를 WORK로 변환
    const tasks: TaskItem[] = []
    for (const proj of detail.projects) {
      if (proj.planTasks && proj.planTasks.length > 0) {
        for (const t of proj.planTasks) {
          tasks.push({
            projectId: proj.projectId,
            projectCode: proj.projectCode || '',
            projectName: proj.projectName || '',
            taskType: 'WORK',
            description: t.description || '',
            hours: t.hours || 0,
            isCompleted: false
          })
        }
      }
    }
    
    if (tasks.length > 0) {
      form.value.tasks = tasks
    }
  } catch (e) {
    console.error('계획 로드 실패:', e)
  }
}

// 모달에서 확인 클릭 시
async function confirmLoadRecentPlan() {
  if (recentReportInfo.value) {
    await loadPlanFromReport(recentReportInfo.value.reportId)
  }
  showLoadConfirmModal.value = false
}

function updateWeekFromDate() {
  const startDate = new Date(form.value.weekStartDate)
  const weekInfo = getWeekInfo(startDate)
  setWeekFromInfo(weekInfo)
}

// Task 관련 함수들
function getWorkTasks(projectId: number) {
  return form.value.tasks.filter(t => t.projectId === projectId && t.taskType === 'WORK')
}

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

function getGroupWorkHours(group: ProjectGroup) {
  return getWorkTasks(group.projectId).reduce((sum, t) => sum + (t.hours || 0), 0)
}

function getGroupPlanHours(group: ProjectGroup) {
  return getPlanTasks(group.projectId).reduce((sum, t) => sum + (t.hours || 0), 0)
}

function addProjectGroup(project: any) {
  // 기본 Task 1개씩 추가
  form.value.tasks.push({
    projectId: project.projectId,
    taskType: 'WORK',
    description: '',
    hours: 0,
    isCompleted: true
  })
  form.value.tasks.push({
    projectId: project.projectId,
    taskType: 'PLAN',
    description: '',
    hours: 0,
    isCompleted: true
  })
  showProjectModal.value = false
}

function removeProjectGroup(gIdx: number) {
  const group = projectGroups.value[gIdx]
  form.value.tasks = form.value.tasks.filter(t => t.projectId !== group.projectId)
}

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

function removeTask(projectId: number, taskType: 'WORK' | 'PLAN', idx: number) {
  const tasks = form.value.tasks.filter(t => t.projectId === projectId && t.taskType === taskType)
  if (tasks.length <= 1) return // 최소 1개는 유지
  
  const targetTask = tasks[idx]
  const targetIndex = form.value.tasks.indexOf(targetTask)
  if (targetIndex > -1) {
    form.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 handleSubmit() {
  const validTasks = form.value.tasks.filter(t => t.description.trim())
  if (validTasks.length === 0) {
    toast.warning('최소 1개 이상의 Task를 입력해주세요.')
    return
  }
  
  isSaving.value = true
  try {
    const res = await $fetch<{ reportId: number }>('/api/report/weekly/create', {
      method: 'POST',
      body: {
        reportYear: form.value.reportYear,
        reportWeek: form.value.reportWeek,
        weekStartDate: form.value.weekStartDate,
        weekEndDate: form.value.weekEndDate,
        tasks: validTasks.map(t => ({
          projectId: t.projectId,
          taskType: t.taskType,
          taskDescription: t.description,
          taskHours: t.hours || 0,
          isCompleted: t.taskType === 'WORK' ? t.isCompleted : undefined
        })),
        issueDescription: form.value.issueDescription,
        vacationDescription: form.value.vacationDescription,
        remarkDescription: form.value.remarkDescription
      }
    })
    
    toast.success('주간보고가 작성되었습니다.')
    savedReportId.value = res.reportId
    
    // 완료된 WORK 실적에 대해 유사 TODO 검색
    const completedWorks = validTasks.filter(t => t.taskType === 'WORK' && t.isCompleted)
    if (completedWorks.length > 0) {
      await searchSimilarTodos(completedWorks)
    } else {
      router.push('/report/weekly')
    }
  } catch (e: any) {
    toast.error(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

// === TODO 연계 기능 ===
async function searchSimilarTodos(completedWorks: TaskItem[]) {
  try {
    const allTodos: any[] = []
    
    for (const work of completedWorks) {
      const res = await $fetch<{ todos: any[] }>('/api/todo/report/similar', {
        method: 'POST',
        body: {
          taskDescription: work.description,
          projectId: work.projectId
        }
      })
      if (res.todos && res.todos.length > 0) {
        for (const todo of res.todos) {
          if (!allTodos.find(t => t.todoId === todo.todoId)) {
            allTodos.push({ ...todo, selected: true })
          }
        }
      }
    }
    
    if (allTodos.length > 0) {
      similarTodos.value = allTodos
      showTodoLinkModal.value = true
    } else {
      router.push('/report/weekly')
    }
  } catch (e) {
    console.error('TODO 검색 실패:', e)
    router.push('/report/weekly')
  }
}

function closeTodoLinkModal() {
  showTodoLinkModal.value = false
  router.push('/report/weekly')
}

async function completeTodos() {
  const selected = similarTodos.value.filter(t => t.selected)
  if (selected.length === 0) return
  
  isLinkingTodos.value = true
  try {
    for (const todo of selected) {
      await $fetch('/api/todo/report/link', {
        method: 'POST',
        body: {
          todoId: todo.todoId,
          weeklyReportId: savedReportId.value,
          markCompleted: true
        }
      })
    }
    toast.success(`${selected.length}개의 TODO가 완료 처리되었습니다.`)
    showTodoLinkModal.value = false
    router.push('/report/weekly')
  } catch (e: any) {
    toast.error('TODO 완료 처리에 실패했습니다.')
  } finally {
    isLinkingTodos.value = false
  }
}

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

// 초기 로드 시 모든 textarea 높이 조절
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'
    })
  })
}

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

// 유지보수 불러오기 함수들
function openMaintenanceModal() {
  showMaintenanceModal.value = true
  maintenanceStep.value = 'select'
  maintenanceProjectId.value = ''
  maintenanceTasks.value = []
  generatedTasks.value = []
}

async function loadMaintenanceTasks() {
  if (!maintenanceProjectId.value) {
    maintenanceTasks.value = []
    return
  }
  isLoadingMaintenance.value = true
  try {
    const res = await $fetch<{ tasks: any[] }>('/api/maintenance/report/available', {
      query: {
        projectId: maintenanceProjectId.value,
        weekStartDate: form.value.weekStartDate,
        weekEndDate: form.value.weekEndDate
      }
    })
    maintenanceTasks.value = (res.tasks || []).map(t => ({ ...t, selected: true }))
  } catch (e) {
    console.error(e)
    maintenanceTasks.value = []
  } finally {
    isLoadingMaintenance.value = false
  }
}

async function convertMaintenance() {
  const selected = maintenanceTasks.value.filter(t => t.selected)
  if (selected.length === 0) return
  
  isConverting.value = true
  try {
    const res = await $fetch<{ generatedTasks: any[] }>('/api/maintenance/report/generate-text', {
      method: 'POST',
      body: { tasks: selected }
    })
    generatedTasks.value = res.generatedTasks || []
    maintenanceStep.value = 'convert'
  } catch (e) {
    console.error(e)
    // 실패 시 기본 변환
    generatedTasks.value = selected.map(t => ({
      description: `[${getTypeLabel(t.taskType)}] ${t.requestTitle}`,
      taskType: t.taskType,
      sourceTaskIds: [t.taskId]
    }))
    maintenanceStep.value = 'convert'
  } finally {
    isConverting.value = false
  }
}

function applyMaintenanceTasks() {
  const projectId = Number(maintenanceProjectId.value)
  const proj = allProjects.value.find(p => p.projectId === projectId)
  
  for (const g of generatedTasks.value) {
    form.value.tasks.push({
      projectId,
      projectCode: proj?.projectCode || '',
      projectName: proj?.projectName || '',
      taskType: 'WORK',
      description: g.description,
      hours: 0,
      isCompleted: true
    })
  }
  
  showMaintenanceModal.value = false
  toast.success(`${generatedTasks.value.length}건의 실적이 추가되었습니다.`)
}

function getTypeLabel(type: string): string {
  const labels: Record<string, string> = { bug: '버그수정', feature: '기능개선', inquiry: '문의대응', other: '기타' }
  return labels[type] || '기타'
}

function truncate(s: string, len: number): string {
  if (!s) return ''
  return s.length > len ? s.substring(0, len) + '...' : s
}

function handleAiDrop(e: DragEvent) {
  isDragging.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 }
      })
    }
    
    console.log('=== AI 분석 응답 ===')
    console.log(res)
    
    // 파싱 결과를 임시 저장하고 매칭 단계로 이동
    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 {
      toast.warning('분석된 내용이 없습니다.')
    }
  } catch (e: any) {
    console.error('=== AI 분석 에러 ===', e)
    toast.error(e.data?.message || 'AI 분석에 실패했습니다.')
  } finally {
    isAiParsing.value = false
  }
}

// 매칭된 프로젝트가 있는지 확인
const hasMatchedProjects = computed(() => {
  if (!aiParsedResult.value) return false
  return aiParsedResult.value.projects.some(p => 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()) {
        form.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()) {
        form.value.tasks.push({
          projectId,
          taskType: 'PLAN',
          description: task.description,
          hours: task.hours || 0,
          isCompleted: false
        })
      }
    }
  }
  
  // 공통사항 병합
  if (parsed.issueDescription) {
    form.value.issueDescription = form.value.issueDescription 
      ? form.value.issueDescription + '\n' + parsed.issueDescription 
      : parsed.issueDescription
  }
  if (parsed.vacationDescription) {
    form.value.vacationDescription = form.value.vacationDescription 
      ? form.value.vacationDescription + '\n' + parsed.vacationDescription 
      : parsed.vacationDescription
  }
  if (parsed.remarkDescription) {
    form.value.remarkDescription = form.value.remarkDescription 
      ? form.value.remarkDescription + '\n' + parsed.remarkDescription 
      : parsed.remarkDescription
  }
  
  closeAiModal()
}

function mergeAiResult(parsed: any) {
  console.log('=== mergeAiResult 시작 ===')
  console.log('parsed:', parsed)
  console.log('allProjects:', allProjects.value)
  
  // 프로젝트별 태스크 병합
  if (parsed.projects && Array.isArray(parsed.projects)) {
    for (const proj of parsed.projects) {
      console.log('처리 중인 프로젝트:', proj.projectName, 'matchedProjectId:', proj.matchedProjectId)
      
      // 기존 프로젝트 찾기 (이름으로 매칭)
      const existingProject = allProjects.value.find(p => 
        p.projectName.toLowerCase().includes(proj.projectName?.toLowerCase()) ||
        proj.projectName?.toLowerCase().includes(p.projectName.toLowerCase())
      )
      
      const projectId = proj.matchedProjectId || existingProject?.projectId
      
      if (!projectId) {
        console.warn('매칭되는 프로젝트 없음:', proj.projectName)
        continue
      }
      
      // 금주 실적 추가
      if (proj.workTasks && Array.isArray(proj.workTasks)) {
        for (const task of proj.workTasks) {
          if (task.description?.trim()) {
            form.value.tasks.push({
              projectId,
              taskType: 'WORK',
              description: task.description,
              hours: task.hours || 0,
              isCompleted: task.isCompleted !== false
            })
          }
        }
      }
      
      // 차주 계획 추가
      if (proj.planTasks && Array.isArray(proj.planTasks)) {
        for (const task of proj.planTasks) {
          if (task.description?.trim()) {
            form.value.tasks.push({
              projectId,
              taskType: 'PLAN',
              description: task.description,
              hours: task.hours || 0,
              isCompleted: true
            })
          }
        }
      }
    }
  }
  
  // 공통사항 병합 (기존 내용 + 새 내용)
  if (parsed.issueDescription) {
    form.value.issueDescription = form.value.issueDescription 
      ? form.value.issueDescription + '\n' + parsed.issueDescription 
      : parsed.issueDescription
  }
  if (parsed.vacationDescription) {
    form.value.vacationDescription = form.value.vacationDescription 
      ? form.value.vacationDescription + '\n' + parsed.vacationDescription 
      : parsed.vacationDescription
  }
  if (parsed.remarkDescription) {
    form.value.remarkDescription = form.value.remarkDescription 
      ? form.value.remarkDescription + '\n' + parsed.remarkDescription 
      : parsed.remarkDescription
  }
}
</script>

<style scoped>
.modal.show {
  background-color: rgba(0, 0, 0, 0.5);
}

.upload-zone {
  cursor: pointer;
  transition: all 0.2s;
  border-style: dashed !important;
  border-width: 2px !important;
}

.upload-zone:hover {
  border-color: #0d6efd !important;
  background-color: #f8f9fa;
}

textarea.auto-resize {
  overflow: hidden;
  resize: none;
  min-height: 32px;
}
</style>
