@extends('layouts.app')

@section('title', '기안 작성')

@section('content')
    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-800">기안 작성</h1>
        <a href="{{ route('approvals.drafts') }}" class="text-gray-600 hover:text-gray-800 text-sm">
            &larr; 기안함으로 돌아가기
        </a>
    </div>

    <div>
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">문서 내용</h2>

            {{-- 양식 선택 --}}
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">양식 <span class="text-red-500">*</span></label>
                <div class="flex items-center gap-2">
                    <select id="form_id" class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                        @foreach($forms as $form)
                            <option value="{{ $form->id }}">{{ $form->name }}</option>
                        @endforeach
                    </select>
                    <button type="button" id="expense-load-btn" style="display: none;" onclick="openExpenseLoadModal()"
                            class="shrink-0 px-3 py-2 bg-amber-50 text-amber-700 hover:bg-amber-100 border border-amber-200 rounded-lg text-sm font-medium transition inline-flex items-center gap-1">
                        <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                        </svg>
                        불러오기
                    </button>
                </div>
            </div>

            {{-- 제목 --}}
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">제목 <span class="text-red-500">*</span></label>
                <input type="text" id="title" maxlength="200" placeholder="결재 제목을 입력하세요"
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            {{-- 결재선 --}}
            <div class="mb-4">
                <div class="flex items-center justify-between mb-1">
                    <label class="block text-sm font-medium text-gray-700">결재선</label>
                    <div class="flex items-center gap-2">
                        <select id="quick-line-select" onchange="applyQuickLine(this.value)"
                                class="px-2 py-1.5 border border-gray-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-blue-500"
                                style="min-width: 160px;">
                            <option value="">결재선 선택</option>
                            @foreach($lines as $line)
                                <option value="{{ $line->id }}" {{ ($defaultLine?->id ?? '') == $line->id ? 'selected' : '' }}>
                                    {{ $line->name }} ({{ count($line->steps ?? []) }}단계)
                                </option>
                            @endforeach
                        </select>
                        <button type="button" onclick="openApprovalLineModal()"
                                class="px-3 py-1.5 bg-blue-50 text-blue-600 hover:bg-blue-100 rounded-lg text-xs font-medium transition whitespace-nowrap">
                            세부 설정
                        </button>
                    </div>
                </div>
                <div id="approval-line-summary" class="p-3 bg-gray-50 rounded-lg border border-gray-200 flex items-center">
                    <span class="text-sm text-gray-400">결재선이 설정되지 않았습니다.</span>
                </div>
            </div>

            {{-- 긴급 여부 --}}
            <div class="mb-4">
                <label class="inline-flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" id="is_urgent" class="rounded border-gray-300 text-red-600 focus:ring-red-500">
                    <span class="text-sm text-gray-700">긴급</span>
                </label>
            </div>

            {{-- 본문 (일반 양식) --}}
            <div id="body-area" class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">
                    본문
                    <label class="inline-flex items-center gap-1 ml-3 cursor-pointer">
                        <input type="checkbox" id="useEditor" onchange="toggleEditor()"
                               class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        <span class="text-xs text-gray-500 font-normal">편집기</span>
                    </label>
                </label>
                <textarea id="body" rows="12" placeholder="기안 내용을 입력하세요..."
                          class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                          style="min-height: 300px;"></textarea>
                <div id="quill-container" style="display: none; min-height: 300px;"></div>
            </div>

            {{-- 지출결의서 전용 폼 --}}
            @include('approvals.partials._expense-form', [
                'initialData' => [],
                'cards' => $cards ?? collect(),
                'accounts' => $accounts ?? collect(),
            ])

            {{-- 액션 버튼 --}}
            <div class="border-t pt-4 mt-4 flex gap-2 justify-end">
                <button onclick="saveApproval('draft')"
                        class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition text-sm font-medium">
                    임시저장
                </button>
                <button onclick="saveApproval('submit')"
                        class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition text-sm font-medium">
                    상신
                </button>
            </div>
        </div>
    </div>

    {{-- 결재선 모달 --}}
    <div id="approval-line-modal" style="display: none;" class="fixed inset-0 z-50">
        <div class="absolute inset-0 bg-black/50" onclick="closeApprovalLineModal()"></div>
        <div class="relative flex items-center justify-center min-h-full p-4">
            <div class="bg-white rounded-xl shadow-2xl w-full overflow-hidden relative" style="max-width: 720px;">
                <button type="button" onclick="closeApprovalLineModal()"
                        class="absolute top-3 right-3 z-10 p-1 text-gray-400 hover:text-gray-600 transition bg-white rounded-full shadow-sm">
                    <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 class="overflow-y-auto" style="max-height: 70vh;">
                    @php
                        $defaultLine = collect($lines)->firstWhere('is_default', true);
                    @endphp
                    @include('approvals.partials._approval-line-editor', [
                        'lines' => $lines,
                        'initialSteps' => $defaultLine?->steps ?? [],
                        'selectedLineId' => $defaultLine?->id ?? '',
                    ])
                </div>
                <div class="px-5 py-3 border-t border-gray-200 flex justify-end">
                    <button type="button" onclick="closeApprovalLineModal()"
                            class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition">
                        확인
                    </button>
                </div>
            </div>
        </div>
    </div>
    {{-- 지출결의서 불러오기 모달 --}}
    <div id="expense-load-modal" style="display: none;" class="fixed inset-0 z-50">
        <div class="absolute inset-0 bg-black/50" onclick="closeExpenseLoadModal()"></div>
        <div class="relative flex items-center justify-center min-h-full p-4">
            <div class="bg-white rounded-xl shadow-2xl w-full overflow-hidden relative" style="max-width: 640px;">
                <div class="px-5 py-4 border-b border-gray-200 flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800">지출결의서 불러오기</h3>
                    <button type="button" onclick="closeExpenseLoadModal()"
                            class="p-1 text-gray-400 hover:text-gray-600 transition">
                        <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>
                <div class="overflow-y-auto" style="max-height: 60vh;">
                    <div id="expense-load-list" class="p-4">
                        <div class="text-center text-sm text-gray-400 py-8">불러오는 중...</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet">
<style>
    #quill-container .ql-editor { min-height: 260px; font-size: 0.875rem; }
    #quill-container .ql-toolbar { border-radius: 0.5rem 0.5rem 0 0; border-color: #d1d5db; }
    #quill-container .ql-container { border-radius: 0 0 0.5rem 0.5rem; border-color: #d1d5db; }
    #summary-sortable .step-card {
        cursor: grab;
        position: relative;
        margin-right: 24px;
        user-select: none;
        transition: transform 0.15s ease, box-shadow 0.15s ease;
    }
    #summary-sortable .step-card:last-child { margin-right: 0; }
    #summary-sortable .step-card:not(:last-child)::after {
        content: '→';
        position: absolute;
        right: -18px;
        top: 50%;
        transform: translateY(-50%);
        color: #d1d5db;
        font-size: 14px;
        pointer-events: none;
    }
    #summary-sortable .step-card:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        transform: translateY(-1px);
    }
    #summary-sortable .step-card:active { cursor: grabbing; }
    #summary-sortable .step-card.sortable-ghost { opacity: 0.3; }
    #summary-sortable .step-card.sortable-chosen {
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        transform: translateY(-2px);
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<script>
let quillInstance = null;
var summarySortableInstance = null;
const formBodyTemplates = @json($forms->pluck('body_template', 'id'));
const formCodes = @json($forms->pluck('code', 'id'));
const linesData = @json($lines);
let isExpenseForm = false;

function escapeHtml(str) {
    if (!str) return '';
    const div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

function toggleEditor() {
    const useEditor = document.getElementById('useEditor').checked;
    const textarea = document.getElementById('body');
    const container = document.getElementById('quill-container');

    if (useEditor) {
        container.style.display = '';
        textarea.style.display = 'none';
        if (!quillInstance) {
            quillInstance = new Quill('#quill-container', {
                theme: 'snow',
                modules: {
                    toolbar: [
                        [{ 'header': [1, 2, 3, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                        [{ 'align': [] }],
                        ['blockquote', 'code-block'],
                        ['link'],
                        ['clean'],
                    ],
                },
                placeholder: '기안 내용을 입력하세요...',
            });
        }
        const text = textarea.value.trim();
        if (text) {
            if (/<[a-z][\s\S]*>/i.test(text)) {
                quillInstance.root.innerHTML = text;
            } else {
                quillInstance.setText(text);
            }
        }
    } else {
        container.style.display = 'none';
        textarea.style.display = '';
        if (quillInstance) {
            const html = quillInstance.root.innerHTML;
            textarea.value = (html === '<p><br></p>') ? '' : html;
        }
    }
}

function getBodyContent() {
    const useEditor = document.getElementById('useEditor')?.checked;
    if (useEditor && quillInstance) {
        const html = quillInstance.root.innerHTML;
        return (html === '<p><br></p>') ? '' : html;
    }
    return document.getElementById('body').value;
}

function openApprovalLineModal() {
    document.getElementById('approval-line-modal').style.display = '';
    document.body.style.overflow = 'hidden';
}

function closeApprovalLineModal() {
    document.getElementById('approval-line-modal').style.display = 'none';
    document.body.style.overflow = '';
    updateApprovalLineSummary();

    // 모달 내부 결재선 선택과 외부 드롭다운 동기화
    const editorEl = document.getElementById('approval-line-editor');
    if (editorEl && editorEl._x_dataStack) {
        document.getElementById('quick-line-select').value = editorEl._x_dataStack[0].selectedLineId || '';
    }
}

function updateApprovalLineSummary() {
    const editorEl = document.getElementById('approval-line-editor');
    if (!editorEl || !editorEl._x_dataStack) return;

    const steps = editorEl._x_dataStack[0].steps;
    const summaryEl = document.getElementById('approval-line-summary');

    if (summarySortableInstance) { summarySortableInstance.destroy(); summarySortableInstance = null; }

    if (!steps || steps.length === 0) {
        summaryEl.className = 'p-3 bg-gray-50 rounded-lg border border-gray-200 flex items-center';
        summaryEl.innerHTML = '<span class="text-sm text-gray-400">결재선이 설정되지 않았습니다.</span>';
        return;
    }

    const typeCounters = { approval: 0, agreement: 0, reference: 0 };
    const typeLabels = { approval: '결재', agreement: '합의', reference: '참조' };
    const typeBg = { approval: 'bg-blue-50 border-blue-100', agreement: 'bg-green-50 border-green-100', reference: 'bg-gray-100 border-gray-200' };
    const typeLabelColor = { approval: 'text-blue-600', agreement: 'text-green-600', reference: 'text-gray-500' };

    const cards = [];
    steps.forEach(function(s, i) {
        typeCounters[s.step_type] = (typeCounters[s.step_type] || 0) + 1;
        var count = typeCounters[s.step_type];
        var label = typeLabels[s.step_type] || s.step_type;
        var bg = typeBg[s.step_type] || typeBg.reference;
        var labelColor = typeLabelColor[s.step_type] || typeLabelColor.reference;
        var stepLabel = s.step_type === 'reference' ? label : count + '차 ' + label;
        var position = s.position || '';

        cards.push(
            '<div class="step-card text-center px-3 py-2 rounded-lg border ' + bg + '" data-index="' + i + '" style="min-width: 72px;">' +
            '<div class="text-xs font-medium ' + labelColor + '">' + escapeHtml(stepLabel) + '</div>' +
            (position ? '<div class="text-xs text-gray-400 mt-0.5">' + escapeHtml(position) + '</div>' : '') +
            '<div class="text-sm font-semibold text-gray-800 mt-0.5">' + escapeHtml(s.user_name) + '</div>' +
            '</div>'
        );
    });

    summaryEl.className = 'p-3 bg-gray-50 rounded-lg border border-gray-200';
    summaryEl.innerHTML = '<div id="summary-sortable" class="flex flex-wrap items-center">' + cards.join('') + '</div>' +
        (steps.length > 1 ? '<div class="text-xs text-gray-400 mt-2">드래그하여 순서를 변경할 수 있습니다</div>' : '');

    initSummarySortable();
}

function initSummarySortable() {
    if (summarySortableInstance) { summarySortableInstance.destroy(); summarySortableInstance = null; }
    var el = document.getElementById('summary-sortable');
    if (!el || typeof Sortable === 'undefined') return;

    summarySortableInstance = Sortable.create(el, {
        animation: 150,
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen',
        onEnd: function(evt) {
            if (evt.oldIndex === evt.newIndex) return;
            var editorEl = document.getElementById('approval-line-editor');
            if (!editorEl || !editorEl._x_dataStack) return;
            var steps = editorEl._x_dataStack[0].steps;
            var item = steps.splice(evt.oldIndex, 1)[0];
            steps.splice(evt.newIndex, 0, item);
            updateApprovalLineSummary();
        }
    });
}

function applyQuickLine(lineId) {
    const editorEl = document.getElementById('approval-line-editor');
    if (!editorEl || !editorEl._x_dataStack) return;
    const alpineData = editorEl._x_dataStack[0];

    if (!lineId) {
        alpineData.selectedLineId = '';
        alpineData.steps = [];
    } else {
        alpineData.selectedLineId = lineId;
        alpineData.loadLine();
    }

    setTimeout(updateApprovalLineSummary, 100);
}

function switchFormMode(formId) {
    const code = formCodes[formId];
    const expenseContainer = document.getElementById('expense-form-container');
    const bodyArea = document.getElementById('body-area');
    const expenseLoadBtn = document.getElementById('expense-load-btn');

    if (code === 'expense') {
        isExpenseForm = true;
        expenseContainer.style.display = '';
        expenseLoadBtn.style.display = '';
        bodyArea.style.display = 'none';
    } else {
        isExpenseForm = false;
        expenseContainer.style.display = 'none';
        expenseLoadBtn.style.display = 'none';
        bodyArea.style.display = '';
    }
}

function applyBodyTemplate(formId) {
    // 먼저 폼 모드 전환
    switchFormMode(formId);

    // 전용 폼이면 제목만 자동 설정하고 body template 적용 건너뜀
    if (isExpenseForm) {
        const titleEl = document.getElementById('title');
        if (!titleEl.value.trim()) {
            const formSelect = document.getElementById('form_id');
            titleEl.value = formSelect.options[formSelect.selectedIndex].text;
        }
        return;
    }

    const template = formBodyTemplates[formId];
    if (!template) return;

    const bodyContent = getBodyContent();
    if (bodyContent.trim()) {
        if (!confirm('현재 본문 내용을 양식 템플릿으로 교체하시겠습니까?')) return;
    }

    // 제목 자동 설정 (비어있을 때만)
    const titleEl = document.getElementById('title');
    if (!titleEl.value.trim()) {
        const formSelect = document.getElementById('form_id');
        titleEl.value = formSelect.options[formSelect.selectedIndex].text;
    }

    // 편집기 활성화 후 HTML 삽입
    const useEditorEl = document.getElementById('useEditor');
    if (!useEditorEl.checked) {
        useEditorEl.checked = true;
        toggleEditor();
    }

    if (quillInstance) {
        quillInstance.root.innerHTML = template;
    }
    document.getElementById('body').value = template;
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const expModal = document.getElementById('expense-load-modal');
        if (expModal && expModal.style.display !== 'none') {
            closeExpenseLoadModal();
            return;
        }
        const modal = document.getElementById('approval-line-modal');
        if (modal && modal.style.display !== 'none') {
            closeApprovalLineModal();
        }
    }
});

document.addEventListener('DOMContentLoaded', function() {
    setTimeout(updateApprovalLineSummary, 200);

    // 초기 양식에 대한 폼 모드 전환
    switchFormMode(document.getElementById('form_id').value);

    // 양식 변경 시 본문 템플릿 자동 채움
    document.getElementById('form_id').addEventListener('change', function() {
        applyBodyTemplate(this.value);
    });
});

async function saveApproval(action) {
    const title = document.getElementById('title').value.trim();
    if (!title) {
        showToast('제목을 입력해주세요.', 'warning');
        return;
    }

    const editorEl = document.getElementById('approval-line-editor');
    const steps = editorEl._x_dataStack[0].getStepsData();

    if (action === 'submit' && steps.filter(s => s.step_type !== 'reference').length === 0) {
        showToast('결재자를 1명 이상 추가해주세요.', 'warning');
        return;
    }

    let expenseContent = {};
    let attachmentFileIds = [];
    if (isExpenseForm) {
        const expenseEl = document.getElementById('expense-form-container');
        if (expenseEl && expenseEl._x_dataStack) {
            expenseContent = expenseEl._x_dataStack[0].getFormData();
            attachmentFileIds = expenseEl._x_dataStack[0].getFileIds();
        }
    }

    const payload = {
        form_id: document.getElementById('form_id').value,
        title: title,
        body: isExpenseForm ? null : getBodyContent(),
        content: isExpenseForm ? expenseContent : {},
        attachment_file_ids: attachmentFileIds,
        is_urgent: document.getElementById('is_urgent').checked,
        steps: steps,
    };

    try {
        const response = await fetch('/api/admin/approvals', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
            body: JSON.stringify(payload),
        });

        const data = await response.json();

        if (!data.success && !data.data) {
            showToast(data.message || '저장에 실패했습니다.', 'error');
            return;
        }

        if (action === 'submit') {
            const submitResponse = await fetch(`/api/admin/approvals/${data.data.id}/submit`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json',
                },
            });

            const submitData = await submitResponse.json();

            if (submitData.success) {
                showToast('결재가 상신되었습니다.', 'success');
                setTimeout(() => location.href = '/approval-mgmt/drafts', 500);
            } else {
                showToast(submitData.message || '상신에 실패했습니다.', 'error');
            }
        } else {
            showToast('임시저장되었습니다.', 'success');
            setTimeout(() => location.href = `/approval-mgmt/${data.data.id}/edit`, 500);
        }
    } catch (e) {
        showToast('서버 오류가 발생했습니다.', 'error');
    }
}

// =========================================================================
// 지출결의서 불러오기
// =========================================================================

const expenseTypeLabels = {
    corporate_card: '법인카드', transfer: '송금', auto_transfer: '자동이체 출금',
    cash_advance: '현금/가지급정산',
};
const statusColors = {
    draft: 'bg-gray-100 text-gray-600', pending: 'bg-blue-100 text-blue-600',
    approved: 'bg-green-100 text-green-600', rejected: 'bg-red-100 text-red-600',
    cancelled: 'bg-yellow-100 text-yellow-600',
};

async function openExpenseLoadModal() {
    const modal = document.getElementById('expense-load-modal');
    const list = document.getElementById('expense-load-list');
    modal.style.display = '';
    document.body.style.overflow = 'hidden';
    list.innerHTML = '<div class="text-center text-sm text-gray-400 py-8">불러오는 중...</div>';

    try {
        const res = await fetch('/api/admin/approvals/expense-history', {
            headers: { 'Accept': 'application/json' },
        });
        const json = await res.json();

        if (!json.success || !json.data.length) {
            list.innerHTML = '<div class="text-center text-sm text-gray-400 py-8">이전 지출결의서가 없습니다.</div>';
            return;
        }

        list.innerHTML = json.data.map(item => {
            const amount = parseInt(item.total_amount || 0).toLocaleString('ko-KR');
            const typeLabel = expenseTypeLabels[item.expense_type] || item.expense_type;
            const color = statusColors[item.status] || statusColors.draft;
            return `<div class="flex items-center justify-between p-3 border border-gray-200 rounded-lg hover:bg-blue-50 cursor-pointer transition mb-2" onclick="loadExpenseData(${item.id})">
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                        <span class="text-sm font-medium text-gray-800 truncate">${escapeHtml(item.title)}</span>
                        <span class="shrink-0 px-1.5 py-0.5 rounded text-xs font-medium ${color}">${escapeHtml(item.status_label)}</span>
                    </div>
                    <div class="flex items-center gap-3 mt-1 text-xs text-gray-500">
                        <span>${escapeHtml(item.created_at)}</span>
                        <span>${escapeHtml(typeLabel)}</span>
                        <span class="font-medium text-gray-700">${amount}원</span>
                    </div>
                </div>
                <svg class="w-4 h-4 text-gray-400 shrink-0 ml-2" 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>
            </div>`;
        }).join('');
    } catch (e) {
        list.innerHTML = '<div class="text-center text-sm text-red-400 py-8">불러오기 실패</div>';
    }
}

function closeExpenseLoadModal() {
    document.getElementById('expense-load-modal').style.display = 'none';
    document.body.style.overflow = '';
}

async function loadExpenseData(approvalId) {
    try {
        const res = await fetch(`/api/admin/approvals/${approvalId}`, {
            headers: { 'Accept': 'application/json' },
        });
        const json = await res.json();

        if (!json.success || !json.data?.content) {
            showToast('데이터를 불러올 수 없습니다.', 'error');
            return;
        }

        const content = json.data.content;
        const expenseEl = document.getElementById('expense-form-container');
        if (!expenseEl || !expenseEl._x_dataStack) return;

        const alpine = expenseEl._x_dataStack[0];
        const today = new Date().toISOString().slice(0, 10);

        // 폼 데이터 복사 (날짜는 오늘로 초기화)
        alpine.formData.expense_type = content.expense_type || 'corporate_card';
        alpine.formData.tax_invoice = content.tax_invoice || 'normal';
        alpine.formData.write_date = today;
        alpine.formData.approval_date = today;
        alpine.formData.department = content.department || '경리부';
        alpine.formData.writer_name = content.writer_name || '';
        alpine.formData.attachment_memo = content.attachment_memo || '';
        alpine.formData.selected_card = content.selected_card || null;
        alpine.formData.selected_account = content.selected_account || null;

        // 내역 항목 복사 (날짜는 오늘로)
        if (content.items && content.items.length > 0) {
            let keyCounter = alpine.formData.items.length + 100;
            alpine.formData.items = content.items.map(item => ({
                _key: ++keyCounter,
                date: today,
                description: item.description || '',
                amount: parseInt(item.amount) || 0,
                vendor: item.vendor || '',
                bank: item.bank || '',
                account_no: item.account_no || '',
                depositor: item.depositor || '',
                remark: item.remark || '',
            }));
        }

        // 제목 설정
        const titleEl = document.getElementById('title');
        if (!titleEl.value.trim()) {
            titleEl.value = json.data.title || '지출결의서';
        }

        closeExpenseLoadModal();
        showToast('지출결의서를 불러왔습니다. 내용을 확인 후 수정해주세요.', 'success');
    } catch (e) {
        showToast('불러오기 실패', 'error');
    }
}


</script>
@endpush
