@extends('layouts.app')

@section('title', '대시보드')
@section('page-title', '대시보드')

@section('content')
    <!-- Quick Actions -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div class="bg-white rounded-lg shadow p-6 hover:shadow-lg transition-shadow">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">사용자 관리</h3>
            <p class="text-sm text-gray-600 mb-4">시스템 사용자를 관리합니다.</p>
            <a href="#" class="inline-flex items-center text-primary hover:underline">
                바로가기
                <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg>
            </a>
        </div>

        <div class="bg-white rounded-lg shadow p-6 hover:shadow-lg transition-shadow">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">시스템 설정</h3>
            <p class="text-sm text-gray-600 mb-4">시스템 환경을 설정합니다.</p>
            <a href="#" class="inline-flex items-center text-primary hover:underline">
                바로가기
                <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg>
            </a>
        </div>

        <div class="bg-white rounded-lg shadow p-6 hover:shadow-lg transition-shadow">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">통계 및 리포트</h3>
            <p class="text-sm text-gray-600 mb-4">시스템 통계를 확인합니다.</p>
            <a href="{{ route('stats.dashboard') }}" class="inline-flex items-center text-primary hover:underline">
                바로가기
                <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg>
            </a>
        </div>
    </div>

    <!-- Weather Widget -->
    <div class="mt-6 bg-white rounded-lg shadow p-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-base font-semibold text-gray-900 flex items-center gap-2">
                <svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z"/>
                </svg>
                주간 날씨
            </h3>
            <span class="text-xs text-gray-400">서울</span>
        </div>
        <div id="weather-container"
             hx-get="{{ route('dashboard.weather') }}"
             hx-trigger="load"
             hx-swap="innerHTML">
            {{-- 스켈레톤 로딩 --}}
            <div class="flex gap-3" style="flex-wrap: nowrap;">
                @for($i = 0; $i < 7; $i++)
                    <div class="text-center rounded-xl border border-gray-100 px-3 py-4 animate-pulse" style="flex: 1 1 0; min-width: 90px;">
                        <div class="h-3 bg-gray-200 rounded mx-auto mb-1" style="width: 24px;"></div>
                        <div class="h-3 bg-gray-100 rounded mx-auto mb-3" style="width: 32px;"></div>
                        <div class="h-10 w-10 bg-gray-200 rounded-full mx-auto mb-3"></div>
                        <div class="h-4 bg-gray-200 rounded mx-auto mb-1" style="width: 28px;"></div>
                        <div class="h-3 bg-gray-100 rounded mx-auto" style="width: 28px;"></div>
                    </div>
                @endfor
            </div>
        </div>
    </div>

    <!-- Calendar Section -->
    <div class="mt-6 bg-white rounded-lg shadow p-6">
        <div id="calendar-container"
             hx-get="{{ route('dashboard.calendar', ['year' => now()->year, 'month' => now()->month]) }}"
             hx-trigger="load"
             hx-swap="innerHTML">
            <div class="flex items-center justify-center py-12">
                <svg class="animate-spin h-8 w-8 text-emerald-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-3 text-gray-500">달력을 불러오는 중...</span>
            </div>
        </div>
    </div>

    <!-- User Info Bar (floating bottom) -->
    <style>
        .dashboard-info-bar { left: 16rem; transition: left 0.3s ease-in-out; }
        html.sidebar-is-collapsed .dashboard-info-bar { left: 4rem; }
        @media (max-width: 1023px) { .dashboard-info-bar { left: 0; } }
    </style>
    <div class="dashboard-info-bar fixed bottom-0 right-0 z-40 bg-white/95 backdrop-blur border-t border-gray-200 px-4 py-1.5 flex items-center justify-between text-xs text-gray-500">
        <div class="flex items-center gap-4">
            <span>{{ auth()->user()->name ?? 'User' }} ({{ auth()->user()->email }})</span>
            <span class="text-gray-300">|</span>
            <span>로그인 {{ now()->format('Y-m-d H:i') }}</span>
        </div>
        <span class="inline-flex items-center gap-1">
            <span class="w-1.5 h-1.5 bg-green-500 rounded-full"></span>
            활성
        </span>
    </div>

    <!-- Schedule Modal -->
    <div id="schedule-modal" class="fixed inset-0 z-50 hidden">
        <div class="fixed inset-0 bg-black/50" onclick="closeModal()"></div>
        <div class="fixed inset-0 flex items-center justify-center p-4">
            <div class="bg-white rounded-xl shadow-2xl w-full max-w-lg relative max-h-[90vh] flex flex-col" onclick="event.stopPropagation()">
                <!-- Modal Header -->
                <div class="flex items-center justify-between px-6 py-4 border-b flex-shrink-0">
                    <h3 id="modal-title" class="text-lg font-bold text-gray-900">일정 추가</h3>
                    <button type="button" onclick="closeModal()" class="text-gray-400 hover:text-gray-600 transition-colors">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>

                <!-- Modal Body (scrollable) -->
                <div class="overflow-y-auto flex-1">
                    <form id="schedule-form" class="px-6 py-4 space-y-4">
                        <input type="hidden" id="schedule-id" value="">

                        <!-- 제목 -->
                        <div>
                            <label for="schedule-title" class="block text-sm font-medium text-gray-700 mb-1">제목 <span class="text-red-500">*</span></label>
                            <input type="text" id="schedule-title" name="title" required
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm"
                                placeholder="일정 제목을 입력하세요">
                        </div>

                        <!-- 유형 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">유형</label>
                            <div class="flex items-center gap-2">
                                <select id="schedule-type" name="type"
                                    class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm">
                                    @foreach(\App\Models\System\Schedule::TYPES as $key => $label)
                                        <option value="{{ $key }}">{{ $label }}</option>
                                    @endforeach
                                </select>
                                <button type="button" onclick="showAddTypeInput()"
                                    id="btn-add-type"
                                    class="p-2 text-gray-400 hover:text-emerald-600 hover:bg-emerald-50 border border-gray-300 rounded-lg transition-colors"
                                    title="유형 추가">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                    </svg>
                                </button>
                            </div>
                            <!-- 커스텀 유형 입력 -->
                            <div id="custom-type-input" class="hidden mt-2 flex items-center gap-2">
                                <input type="text" id="new-type-name" maxlength="50"
                                    class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm"
                                    placeholder="새 유형 이름 입력">
                                <button type="button" onclick="addCustomType()"
                                    class="px-3 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-sm transition-colors">
                                    추가
                                </button>
                                <button type="button" onclick="hideAddTypeInput()"
                                    class="px-3 py-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg text-sm transition-colors">
                                    취소
                                </button>
                            </div>
                        </div>

                        <!-- 날짜 -->
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label for="schedule-start-date" class="block text-sm font-medium text-gray-700 mb-1">시작일 <span class="text-red-500">*</span></label>
                                <input type="date" id="schedule-start-date" name="start_date" required
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm">
                            </div>
                            <div>
                                <label for="schedule-end-date" class="block text-sm font-medium text-gray-700 mb-1">종료일</label>
                                <input type="date" id="schedule-end-date" name="end_date"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm">
                            </div>
                        </div>

                        <!-- 종일 체크 + 시간 -->
                        <div>
                            <label class="inline-flex items-center gap-2 cursor-pointer">
                                <input type="checkbox" id="schedule-all-day" name="is_all_day" checked
                                    class="w-4 h-4 text-emerald-600 border-gray-300 rounded focus:ring-emerald-500"
                                    onchange="toggleTimeFields()">
                                <span class="text-sm text-gray-700">종일</span>
                            </label>
                        </div>

                        <div id="time-fields" class="grid grid-cols-2 gap-3 hidden">
                            <div>
                                <label for="schedule-start-time" class="block text-sm font-medium text-gray-700 mb-1">시작 시간</label>
                                <input type="time" id="schedule-start-time" name="start_time"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm">
                            </div>
                            <div>
                                <label for="schedule-end-time" class="block text-sm font-medium text-gray-700 mb-1">종료 시간</label>
                                <input type="time" id="schedule-end-time" name="end_time"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm">
                            </div>
                        </div>

                        <!-- 설명 -->
                        <div>
                            <label for="schedule-description" class="block text-sm font-medium text-gray-700 mb-1">설명</label>
                            <textarea id="schedule-description" name="description" rows="3"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-sm"
                                placeholder="일정에 대한 설명을 입력하세요 (선택)"></textarea>
                        </div>

                        <!-- 첨부파일 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">첨부파일</label>

                            <!-- 드래그앤드롭 영역 -->
                            <div id="file-drop-zone"
                                class="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center transition-colors cursor-pointer"
                                style="min-height: 5rem;"
                                onclick="document.getElementById('file-input').click()">
                                <input type="file" id="file-input" multiple class="hidden"
                                    accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.gif,.zip,.rar"
                                    onchange="handleFileSelect(event)">
                                <svg class="w-8 h-8 mx-auto mb-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                                </svg>
                                <p class="text-sm text-gray-600">파일을 드래그하거나 <span class="text-emerald-600 font-medium">클릭하여 선택</span></p>
                                <p class="text-xs text-gray-400 mt-1">최대 20MB / PDF, 문서, 이미지, 압축파일</p>
                            </div>

                            <!-- 업로드 진행률 -->
                            <div id="upload-progress" class="hidden mt-2">
                                <div class="flex items-center gap-2">
                                    <div class="flex-1 bg-gray-200 rounded-full h-2 overflow-hidden">
                                        <div id="upload-progress-bar" class="h-full bg-emerald-500 transition-all duration-300 rounded-full" style="width: 0%"></div>
                                    </div>
                                    <span id="upload-progress-text" class="text-xs text-gray-500">0%</span>
                                </div>
                            </div>

                            <!-- 첨부파일 목록 -->
                            <div id="file-list" class="mt-2 space-y-1"></div>
                        </div>
                    </form>
                </div>

                <!-- Modal Footer -->
                <div class="flex items-center justify-between px-6 py-4 border-t bg-gray-50 rounded-b-xl flex-shrink-0">
                    <div>
                        <button type="button" id="btn-delete" onclick="deleteSchedule()" class="hidden px-4 py-2 text-sm text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors">
                            삭제
                        </button>
                    </div>
                    <div class="flex items-center gap-2">
                        <button type="button" onclick="closeModal()" class="px-4 py-2 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                            취소
                        </button>
                        <button type="button" id="btn-save" onclick="saveSchedule()" class="px-4 py-2 text-sm bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg transition-colors">
                            저장
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    const CSRF_TOKEN = '{{ csrf_token() }}';
    let attachedFiles = []; // 현재 모달에 표시중인 서버 파일 목록
    let pendingFiles = [];  // 생성 모드에서 대기중인 로컬 파일

    // =========================================================================
    // 모달
    // =========================================================================

    function openCreateModal(dateKey) {
        document.getElementById('modal-title').textContent = '일정 추가';
        document.getElementById('schedule-id').value = '';
        document.getElementById('schedule-form').reset();
        document.getElementById('schedule-all-day').checked = true;
        document.getElementById('btn-delete').classList.add('hidden');
        toggleTimeFields();
        clearFileList();
        pendingFiles = [];

        if (dateKey) {
            document.getElementById('schedule-start-date').value = dateKey;
            document.getElementById('schedule-end-date').value = dateKey;
        } else {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('schedule-start-date').value = today;
            document.getElementById('schedule-end-date').value = today;
        }

        document.getElementById('schedule-modal').classList.remove('hidden');
    }

    async function openEditModal(id) {
        try {
            const res = await fetch(`/dashboard/schedules/${id}`, {
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': CSRF_TOKEN }
            });
            const json = await res.json();
            if (!json.success) throw new Error(json.message || '일정을 불러올 수 없습니다.');

            const s = json.data;
            document.getElementById('modal-title').textContent = '일정 수정';
            document.getElementById('schedule-id').value = s.id;
            document.getElementById('schedule-title').value = s.title || '';
            // 커스텀 타입이면 select에 동적 추가
            const typeSelect = document.getElementById('schedule-type');
            const typeValue = s.type || 'event';
            let typeExists = false;
            for (let i = 0; i < typeSelect.options.length; i++) {
                if (typeSelect.options[i].value === typeValue) { typeExists = true; break; }
            }
            if (!typeExists) {
                const opt = document.createElement('option');
                opt.value = typeValue;
                opt.textContent = typeValue;
                typeSelect.appendChild(opt);
            }
            typeSelect.value = typeValue;
            document.getElementById('schedule-start-date').value = s.start_date ? s.start_date.split('T')[0] : '';
            document.getElementById('schedule-end-date').value = s.end_date ? s.end_date.split('T')[0] : '';
            document.getElementById('schedule-all-day').checked = s.is_all_day;
            document.getElementById('schedule-start-time').value = s.start_time ? s.start_time.substring(0, 5) : '';
            document.getElementById('schedule-end-time').value = s.end_time ? s.end_time.substring(0, 5) : '';
            document.getElementById('schedule-description').value = s.description || '';
            document.getElementById('btn-delete').classList.remove('hidden');
            toggleTimeFields();

            clearFileList();
            pendingFiles = [];
            renderFileList(json.files || [], s.id);

            document.getElementById('schedule-modal').classList.remove('hidden');
        } catch (e) {
            alert(e.message || '일정을 불러올 수 없습니다.');
        }
    }

    function closeModal() {
        document.getElementById('schedule-modal').classList.add('hidden');
        clearFileList();
    }

    function toggleTimeFields() {
        const allDay = document.getElementById('schedule-all-day').checked;
        document.getElementById('time-fields').classList.toggle('hidden', allDay);
        if (allDay) {
            document.getElementById('schedule-start-time').value = '';
            document.getElementById('schedule-end-time').value = '';
        }
    }

    // =========================================================================
    // 일정 CRUD
    // =========================================================================

    async function saveSchedule() {
        const id = document.getElementById('schedule-id').value;
        const isEdit = !!id;

        const body = {
            title: document.getElementById('schedule-title').value.trim(),
            type: document.getElementById('schedule-type').value,
            start_date: document.getElementById('schedule-start-date').value,
            end_date: document.getElementById('schedule-end-date').value || document.getElementById('schedule-start-date').value,
            is_all_day: document.getElementById('schedule-all-day').checked,
            start_time: document.getElementById('schedule-start-time').value || null,
            end_time: document.getElementById('schedule-end-time').value || null,
            description: document.getElementById('schedule-description').value.trim() || null,
        };

        if (!body.title) { alert('제목을 입력하세요.'); return; }
        if (!body.start_date) { alert('시작일을 선택하세요.'); return; }

        const url = isEdit ? `/dashboard/schedules/${id}` : '/dashboard/schedules';
        const method = isEdit ? 'PUT' : 'POST';

        try {
            const res = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': CSRF_TOKEN,
                },
                body: JSON.stringify(body),
            });
            const json = await res.json();

            if (!res.ok) {
                if (json.errors) {
                    const msgs = Object.values(json.errors).flat().join('\n');
                    alert(msgs);
                } else {
                    alert(json.message || '저장에 실패했습니다.');
                }
                return;
            }

            // 신규 생성 후 → 대기 파일 자동 업로드
            if (!isEdit && json.data?.id && pendingFiles.length > 0) {
                await uploadFiles(pendingFiles, json.data.id);
                pendingFiles = [];
            }

            closeModal();
            refreshCalendar();
        } catch (e) {
            alert('저장 중 오류가 발생했습니다.');
        }
    }

    async function deleteSchedule() {
        const id = document.getElementById('schedule-id').value;
        if (!id) return;
        if (!confirm('이 일정을 삭제하시겠습니까?')) return;

        try {
            const res = await fetch(`/dashboard/schedules/${id}`, {
                method: 'DELETE',
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': CSRF_TOKEN },
            });
            const json = await res.json();
            if (!res.ok) { alert(json.message || '삭제에 실패했습니다.'); return; }

            closeModal();
            refreshCalendar();
        } catch (e) {
            alert('삭제 중 오류가 발생했습니다.');
        }
    }

    // =========================================================================
    // 파일 업로드 (드래그앤드롭 + 클릭)
    // =========================================================================

    // 드래그앤드롭 이벤트
    const dropZone = document.getElementById('file-drop-zone');

    document.addEventListener('DOMContentLoaded', () => {
        const dz = document.getElementById('file-drop-zone');
        if (!dz) return;

        dz.addEventListener('dragover', (e) => {
            e.preventDefault();
            dz.style.borderColor = '#10b981';
            dz.style.backgroundColor = '#ecfdf5';
        });
        dz.addEventListener('dragleave', (e) => {
            e.preventDefault();
            dz.style.borderColor = '';
            dz.style.backgroundColor = '';
        });
        dz.addEventListener('drop', (e) => {
            e.preventDefault();
            dz.style.borderColor = '';
            dz.style.backgroundColor = '';
            const files = Array.from(e.dataTransfer.files);
            handleNewFiles(files);
        });
    });

    function handleFileSelect(event) {
        const files = Array.from(event.target.files);
        handleNewFiles(files);
        event.target.value = '';
    }

    function handleNewFiles(files) {
        const maxSize = 20 * 1024 * 1024;
        const validFiles = files.filter(f => {
            if (f.size > maxSize) {
                alert(`${f.name}: 파일 크기가 20MB를 초과합니다.`);
                return false;
            }
            return true;
        });
        if (validFiles.length === 0) return;

        const scheduleId = document.getElementById('schedule-id').value;

        if (scheduleId) {
            // 수정 모드: 즉시 업로드
            uploadFiles(validFiles, scheduleId);
        } else {
            // 생성 모드: 대기 큐에 추가 + 미리보기 표시
            validFiles.forEach(f => {
                pendingFiles.push(f);
                appendPendingFileItem(f);
            });
        }
    }

    function appendPendingFileItem(file) {
        const container = document.getElementById('file-list');
        const idx = pendingFiles.indexOf(file);
        const div = document.createElement('div');
        div.id = `pending-file-${idx}`;
        div.className = 'flex items-center gap-2 px-3 py-2 bg-amber-50 rounded-lg border border-amber-200 text-sm';
        div.innerHTML = `
            <svg class="w-4 h-4 text-amber-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span class="flex-1 truncate text-gray-700">${file.name}</span>
            <span class="text-xs text-amber-600 flex-shrink-0">${formatFileSize(file.size)} (저장 시 업로드)</span>
            <button type="button" onclick="removePendingFile(${idx})" class="text-gray-400 hover:text-red-500 flex-shrink-0" title="제거">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        `;
        container.appendChild(div);
    }

    function removePendingFile(idx) {
        pendingFiles[idx] = null; // null 처리 (인덱스 유지)
        const el = document.getElementById(`pending-file-${idx}`);
        if (el) el.remove();
        // 실제 배열 정리
        pendingFiles = pendingFiles.filter(f => f !== null);
    }

    async function uploadFiles(files, scheduleId) {
        const formData = new FormData();
        files.forEach(f => formData.append('files[]', f));

        const progressEl = document.getElementById('upload-progress');
        const barEl = document.getElementById('upload-progress-bar');
        const textEl = document.getElementById('upload-progress-text');
        progressEl.classList.remove('hidden');

        try {
            const result = await new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', (e) => {
                    if (e.lengthComputable) {
                        const pct = Math.round((e.loaded / e.total) * 100);
                        barEl.style.width = pct + '%';
                        textEl.textContent = pct + '%';
                    }
                });
                xhr.onload = () => {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(JSON.parse(xhr.responseText));
                    } else {
                        try {
                            const err = JSON.parse(xhr.responseText);
                            reject(new Error(err.message || '업로드 실패'));
                        } catch { reject(new Error('업로드 실패')); }
                    }
                };
                xhr.onerror = () => reject(new Error('네트워크 오류'));

                xhr.open('POST', `/dashboard/schedules/${scheduleId}/files`);
                xhr.setRequestHeader('X-CSRF-TOKEN', CSRF_TOKEN);
                xhr.setRequestHeader('Accept', 'application/json');
                xhr.send(formData);
            });

            if (result.success && result.files) {
                result.files.forEach(f => {
                    attachedFiles.push(f);
                    appendFileItem(f, scheduleId);
                });
            }
        } catch (e) {
            alert(e.message || '파일 업로드에 실패했습니다.');
        } finally {
            setTimeout(() => {
                progressEl.classList.add('hidden');
                barEl.style.width = '0%';
                textEl.textContent = '0%';
            }, 500);
        }
    }

    // =========================================================================
    // 파일 목록 렌더링
    // =========================================================================

    function clearFileList() {
        attachedFiles = [];
        document.getElementById('file-list').innerHTML = '';
    }

    function renderFileList(files, scheduleId) {
        const container = document.getElementById('file-list');
        container.innerHTML = '';
        attachedFiles = files;

        files.forEach(f => appendFileItem({
            id: f.id,
            name: f.display_name || f.original_name,
            size: formatFileSize(f.file_size),
        }, scheduleId));
    }

    function appendFileItem(file, scheduleId) {
        const container = document.getElementById('file-list');
        const div = document.createElement('div');
        div.id = `file-item-${file.id}`;
        div.className = 'flex items-center gap-2 px-3 py-2 bg-gray-50 rounded-lg border border-gray-200 text-sm';
        div.innerHTML = `
            <svg class="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
            </svg>
            <a href="/dashboard/schedules/${scheduleId}/files/${file.id}/download" class="flex-1 truncate text-gray-700 hover:text-emerald-600" title="${file.name}">${file.name}</a>
            <span class="text-xs text-gray-400 flex-shrink-0">${file.size || ''}</span>
            <button type="button" onclick="deleteFileItem(${scheduleId}, ${file.id})" class="text-gray-400 hover:text-red-500 flex-shrink-0" title="삭제">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        `;
        container.appendChild(div);
    }

    async function deleteFileItem(scheduleId, fileId) {
        if (!confirm('이 파일을 삭제하시겠습니까?')) return;

        try {
            const res = await fetch(`/dashboard/schedules/${scheduleId}/files/${fileId}`, {
                method: 'DELETE',
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': CSRF_TOKEN },
            });
            const json = await res.json();
            if (json.success) {
                const el = document.getElementById(`file-item-${fileId}`);
                if (el) el.remove();
                attachedFiles = attachedFiles.filter(f => f.id !== fileId);
            } else {
                alert(json.message || '삭제에 실패했습니다.');
            }
        } catch (e) {
            alert('파일 삭제 중 오류가 발생했습니다.');
        }
    }

    function formatFileSize(bytes) {
        if (!bytes) return '';
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    }

    // =========================================================================
    // 커스텀 유형 추가
    // =========================================================================

    function showAddTypeInput() {
        document.getElementById('custom-type-input').classList.remove('hidden');
        document.getElementById('btn-add-type').classList.add('hidden');
        document.getElementById('new-type-name').focus();
    }

    function hideAddTypeInput() {
        document.getElementById('custom-type-input').classList.add('hidden');
        document.getElementById('btn-add-type').classList.remove('hidden');
        document.getElementById('new-type-name').value = '';
    }

    function addCustomType() {
        const input = document.getElementById('new-type-name');
        const name = input.value.trim();
        if (!name) { input.focus(); return; }

        const select = document.getElementById('schedule-type');
        const value = name.toLowerCase().replace(/\s+/g, '_');

        // 중복 확인
        for (let i = 0; i < select.options.length; i++) {
            if (select.options[i].value === value || select.options[i].text === name) {
                select.value = select.options[i].value;
                hideAddTypeInput();
                return;
            }
        }

        const option = document.createElement('option');
        option.value = value;
        option.textContent = name;
        select.appendChild(option);
        select.value = value;

        hideAddTypeInput();
    }

    // Enter 키로 유형 추가
    document.addEventListener('DOMContentLoaded', () => {
        const inp = document.getElementById('new-type-name');
        if (inp) {
            inp.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') { e.preventDefault(); addCustomType(); }
                if (e.key === 'Escape') { hideAddTypeInput(); }
            });
        }
    });

    // =========================================================================
    // 달력 갱신
    // =========================================================================

    function refreshCalendar() {
        const container = document.getElementById('calendar-container');
        const prevBtn = container.querySelector('button[hx-get]');
        if (prevBtn) {
            const url = prevBtn.getAttribute('hx-get');
            const params = new URLSearchParams(url.split('?')[1]);
            let year = parseInt(params.get('year'));
            let month = parseInt(params.get('month')) + 1;
            if (month > 12) { month = 1; year++; }
            htmx.ajax('GET', `/dashboard/calendar?year=${year}&month=${month}`, { target: '#calendar-container', swap: 'innerHTML' });
        } else {
            const now = new Date();
            htmx.ajax('GET', `/dashboard/calendar?year=${now.getFullYear()}&month=${now.getMonth()+1}`, { target: '#calendar-container', swap: 'innerHTML' });
        }
    }

    // ESC 키로 모달 닫기
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
    });
</script>
@endpush
