{{-- 결재선 편집 컴포넌트 (2패널 구조 — Alpine.js + SortableJS) --}}
<div id="approval-line-editor"
     x-data="approvalLineEditor()"
     x-init="init()"
     class="bg-white rounded-lg shadow-sm">

    <div class="p-4 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800">결재선</h3>
    </div>

    {{-- 2패널 컨테이너 --}}
    <div class="flex" style="min-height: 400px;">

        {{-- 좌측: 인원 목록 --}}
        <div class="border-r border-gray-200" style="flex: 0 0 280px; max-width: 280px;">
            {{-- 검색 --}}
            <div class="p-3 border-b border-gray-100">
                <div class="relative">
                    <svg class="absolute left-2.5 top-2.5 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                    <input type="text"
                           x-model="searchQuery"
                           placeholder="이름/부서 검색..."
                           class="w-full pl-8 pr-3 py-2 border border-gray-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            {{-- 부서별 인원 목록 (스크롤) --}}
            <div class="overflow-y-auto" style="max-height: 420px;">
                <template x-if="loading">
                    <div class="flex items-center justify-center py-8 text-gray-400 text-sm">
                        <svg class="animate-spin w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                        </svg>
                        로딩 중...
                    </div>
                </template>

                <template x-if="!loading && filteredDepartments.length === 0">
                    <div class="py-8 text-center text-gray-400 text-xs">
                        <template x-if="searchQuery">
                            <span>검색 결과가 없습니다.</span>
                        </template>
                        <template x-if="!searchQuery">
                            <span>인원 정보가 없습니다.</span>
                        </template>
                    </div>
                </template>

                <template x-for="dept in filteredDepartments" :key="dept.department_id ?? 'none'">
                    <div class="border-b border-gray-50">
                        {{-- 부서 헤더 --}}
                        <button type="button"
                                @click="toggleDept(dept.department_id)"
                                class="w-full flex items-center justify-between px-3 py-2 text-xs font-semibold text-gray-600 bg-gray-50 hover:bg-gray-100 transition">
                            <span class="flex items-center gap-1">
                                <svg :class="isDeptExpanded(dept.department_id) ? 'rotate-90' : ''"
                                     class="w-3 h-3 transition-transform" 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>
                                <span x-text="dept.department_name"></span>
                            </span>
                            <span class="text-gray-400" x-text="dept.users.length + '명'"></span>
                        </button>

                        {{-- 부서 인원 --}}
                        <div x-show="isDeptExpanded(dept.department_id)"
                             x-collapse>
                            <template x-for="user in dept.users" :key="user.id">
                                <div class="flex items-center justify-between px-3 py-1.5 hover:bg-blue-50 transition"
                                     :class="isAdded(user.id) ? 'opacity-50' : ''">
                                    <div class="flex-1 min-w-0">
                                        <span class="text-xs font-medium text-gray-800" x-text="user.name"></span>
                                        <span class="text-xs text-gray-400 ml-1" x-text="user.position || user.job_title || ''"></span>
                                    </div>
                                    <button type="button"
                                            @click="addStep(user, dept.department_name)"
                                            :disabled="isAdded(user.id)"
                                            class="shrink-0 ml-2 text-xs px-2 py-0.5 rounded transition"
                                            :class="isAdded(user.id)
                                                ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                                                : 'bg-blue-50 text-blue-600 hover:bg-blue-100'">
                                        <span x-text="isAdded(user.id) ? '추가됨' : '+ 추가'"></span>
                                    </button>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        {{-- 우측: 결재선 --}}
        <div class="flex-1 flex flex-col min-w-0">
            {{-- 결재선 템플릿 --}}
            <div class="p-3 border-b border-gray-100">
                <label class="block text-xs font-medium text-gray-500 mb-1">결재선 템플릿</label>
                <select x-model="selectedLineId"
                        @change="loadLine()"
                        class="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">직접 설정</option>
                    <template x-for="line in lines" :key="line.id">
                        <option :value="line.id" x-text="line.name + ' (' + (line.steps?.length || 0) + '단계)'"></option>
                    </template>
                </select>
            </div>

            {{-- 결재자 목록 (드래그 가능) --}}
            <div class="flex-1 overflow-y-auto p-3" style="max-height: 380px;">
                <div x-ref="sortableList" class="space-y-2">
                    <template x-for="(step, index) in steps" :key="step._key">
                        <div class="flex items-center gap-2 p-2 bg-gray-50 rounded-lg border border-gray-200 group"
                             :data-index="index">
                            {{-- 드래그 핸들 --}}
                            <span class="drag-handle shrink-0 cursor-grab active:cursor-grabbing text-gray-300 hover:text-gray-500 transition">
                                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                    <circle cx="9" cy="5" r="1.5"/><circle cx="15" cy="5" r="1.5"/>
                                    <circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/>
                                    <circle cx="9" cy="19" r="1.5"/><circle cx="15" cy="19" r="1.5"/>
                                </svg>
                            </span>

                            {{-- 순번 --}}
                            <span class="shrink-0 flex items-center justify-center bg-blue-100 text-blue-700 rounded-full font-medium text-xs"
                                  style="width: 22px; height: 22px;"
                                  x-text="index + 1"></span>

                            {{-- 이름/부서/직위 --}}
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-1">
                                    <span class="font-medium text-xs text-gray-800" x-text="step.user_name"></span>
                                </div>
                                <div class="text-xs text-gray-400 truncate"
                                     x-text="[step.department, step.position].filter(Boolean).join(' / ')"></div>
                            </div>

                            {{-- 유형 선택 --}}
                            <select x-model="step.step_type"
                                    class="shrink-0 px-1.5 py-1 border border-gray-300 rounded text-xs focus:outline-none focus:ring-1 focus:ring-blue-500"
                                    style="width: 60px;">
                                <option value="approval">결재</option>
                                <option value="agreement">합의</option>
                                <option value="reference">참조</option>
                            </select>

                            {{-- 삭제 --}}
                            <button type="button"
                                    @click="removeStep(index)"
                                    class="shrink-0 p-1 text-gray-300 hover:text-red-500 transition opacity-0 group-hover:opacity-100">
                                <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>
                        </div>
                    </template>
                </div>

                {{-- 빈 상태 --}}
                <div x-show="steps.length === 0" class="flex flex-col items-center justify-center py-12 text-gray-400">
                    <svg class="w-10 h-10 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                              d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>
                    <span class="text-xs">좌측에서 결재자를 추가하세요</span>
                </div>
            </div>
        </div>
    </div>

    {{-- 하단: 요약 바 --}}
    <div class="px-4 py-2 border-t border-gray-200 bg-gray-50 rounded-b-lg flex items-center justify-between text-xs text-gray-500">
        <div>
            <span>결재: <strong class="text-gray-700" x-text="countByType('approval')"></strong>명</span>
            <span class="mx-1">|</span>
            <span>합의: <strong class="text-gray-700" x-text="countByType('agreement')"></strong>명</span>
            <span class="mx-1">|</span>
            <span>참조: <strong class="text-gray-700" x-text="countByType('reference')"></strong>명</span>
        </div>
        <div>
            합계 <strong class="text-gray-700" x-text="steps.length"></strong>명
        </div>
    </div>

    {{-- hidden inputs --}}
    <template x-for="(step, index) in steps" :key="'hidden-' + step._key">
        <div>
            <input type="hidden" :name="'steps[' + index + '][user_id]'" :value="step.user_id">
            <input type="hidden" :name="'steps[' + index + '][step_type]'" :value="step.step_type">
        </div>
    </template>
</div>

<script>
function approvalLineEditor() {
    let keyCounter = 0;

    return {
        departments: [],
        steps: (@json($initialSteps ?? [])).map(s => ({ ...s, _key: ++keyCounter })),
        lines: @json($lines ?? []),
        selectedLineId: {!! $selectedLineId ? $selectedLineId : "''" !!},
        searchQuery: '',
        expandedDepts: {},
        loading: true,
        sortableInstance: null,

        async init() {
            try {
                const res = await fetch('/api/admin/tenant-users/list');
                const data = await res.json();
                if (data.success) {
                    this.departments = data.data;
                    // 기본적으로 모든 부서 펼침
                    this.departments.forEach(d => {
                        this.expandedDepts[d.department_id ?? 'none'] = true;
                    });
                }
            } catch (e) {
                console.error('인원 목록 로딩 실패:', e);
            }
            this.loading = false;

            this.$nextTick(() => this.initSortable());
        },

        get filteredDepartments() {
            if (!this.searchQuery.trim()) return this.departments;
            const q = this.searchQuery.trim().toLowerCase();
            return this.departments
                .map(dept => {
                    const deptMatch = dept.department_name.toLowerCase().includes(q);
                    const matchedUsers = dept.users.filter(u =>
                        u.name.toLowerCase().includes(q) ||
                        (u.position && u.position.toLowerCase().includes(q)) ||
                        (u.job_title && u.job_title.toLowerCase().includes(q))
                    );
                    if (deptMatch) return dept;
                    if (matchedUsers.length > 0) return { ...dept, users: matchedUsers };
                    return null;
                })
                .filter(Boolean);
        },

        toggleDept(deptId) {
            const key = deptId ?? 'none';
            this.expandedDepts[key] = !this.expandedDepts[key];
        },

        isDeptExpanded(deptId) {
            const key = deptId ?? 'none';
            return this.expandedDepts[key] ?? false;
        },

        isAdded(userId) {
            return this.steps.some(s => s.user_id === userId);
        },

        addStep(user, deptName) {
            if (this.isAdded(user.id)) {
                if (typeof showToast === 'function') showToast('이미 추가된 결재자입니다.', 'warning');
                return;
            }
            this.steps.push({
                _key: ++keyCounter,
                user_id: user.id,
                user_name: user.name,
                department: deptName || '',
                position: user.position || user.job_title || '',
                step_type: 'approval',
            });
            this.$nextTick(() => this.initSortable());
        },

        removeStep(index) {
            this.steps.splice(index, 1);
            this.$nextTick(() => this.initSortable());
        },

        loadLine() {
            if (!this.selectedLineId) return;
            const line = this.lines.find(l => l.id == this.selectedLineId);
            if (line && line.steps) {
                this.steps = line.steps.map(s => ({
                    _key: ++keyCounter,
                    user_id: s.user_id,
                    user_name: s.user_name || '사용자 ' + s.user_id,
                    department: s.department || '',
                    position: s.position || '',
                    step_type: s.step_type || 'approval',
                }));
                this.$nextTick(() => this.initSortable());
            }
        },

        initSortable() {
            if (this.sortableInstance) {
                this.sortableInstance.destroy();
                this.sortableInstance = null;
            }

            const el = this.$refs.sortableList;
            if (!el || typeof Sortable === 'undefined') return;

            this.sortableInstance = Sortable.create(el, {
                handle: '.drag-handle',
                animation: 150,
                ghostClass: 'opacity-30',
                onEnd: (evt) => {
                    const item = this.steps.splice(evt.oldIndex, 1)[0];
                    this.steps.splice(evt.newIndex, 0, item);
                },
            });
        },

        countByType(type) {
            return this.steps.filter(s => s.step_type === type).length;
        },

        getStepsData() {
            return this.steps.map(s => ({
                user_id: s.user_id,
                step_type: s.step_type,
            }));
        },
    };
}
</script>
