@extends('layouts.app')

@section('title', '메뉴 동기화')

@section('content')
<div class="flex flex-col h-full">
    <!-- 페이지 헤더 -->
    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6 flex-shrink-0">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">메뉴 동기화</h1>
            <p class="text-sm text-gray-500 mt-1">로컬과 원격 환경 간 메뉴를 동기화합니다.</p>
        </div>
        <button type="button" onclick="openSettingsModal()"
                class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white font-medium rounded-lg transition-colors flex items-center gap-2 text-sm">
            <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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
            환경 설정
        </button>
    </div>

    <!-- 환경 선택 탭 + 동기화 요약 -->
    <div class="bg-white rounded-lg shadow-sm mb-4 flex-shrink-0">
        <div class="flex items-center justify-between border-b border-gray-200">
            <nav class="flex -mb-px" aria-label="Tabs">
                @foreach($environments as $key => $env)
                    <a href="{{ route('menus.sync.index', ['env' => $key]) }}"
                       class="px-6 py-3 text-sm font-medium border-b-2 transition-colors
                              {{ $selectedEnv === $key
                                  ? 'border-blue-500 text-blue-600'
                                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">
                        로컬 ↔ {{ $env['name'] ?? strtoupper($key) }}
                        @if(empty($env['url']))
                            <span class="ml-1 text-xs text-gray-400">(미설정)</span>
                        @endif
                    </a>
                @endforeach
            </nav>
            @if(!empty($environments[$selectedEnv]['url']) && !$remoteError)
                <div class="flex items-center gap-4 pr-5">
                    <span class="inline-flex items-center gap-2 px-3.5 py-1.5 bg-green-50 border border-green-200 rounded-lg text-sm">
                        <span class="w-2.5 h-2.5 bg-green-500 rounded-full"></span>
                        <span class="text-green-700">로컬에만</span>
                        <strong class="text-base text-green-600">{{ count($diff['local_only']) }}</strong>
                    </span>
                    <span class="inline-flex items-center gap-2 px-3.5 py-1.5 bg-blue-50 border border-blue-200 rounded-lg text-sm">
                        <span class="w-2.5 h-2.5 bg-blue-500 rounded-full"></span>
                        <span class="text-blue-700">양쪽 모두</span>
                        <strong class="text-base text-blue-600">{{ count($diff['both']) }}</strong>
                    </span>
                    <span class="inline-flex items-center gap-2 px-3.5 py-1.5 bg-purple-50 border border-purple-200 rounded-lg text-sm">
                        <span class="w-2.5 h-2.5 bg-purple-500 rounded-full"></span>
                        <span class="text-purple-700">원격에만</span>
                        <strong class="text-base text-purple-600">{{ count($diff['remote_only']) }}</strong>
                    </span>
                </div>
            @endif
        </div>
        @if($remoteError)
            <div class="px-4 py-2.5 bg-red-50 text-red-700 text-sm flex items-center gap-2">
                <svg class="w-4 h-4 text-red-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 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                원격 서버 연결 실패: {{ $remoteError }}
            </div>
        @endif
        @if(empty($environments[$selectedEnv]['url']))
            <div class="px-4 py-2.5 bg-yellow-50 text-yellow-700 text-sm flex items-center gap-2">
                <svg class="w-4 h-4 text-yellow-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 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
                환경 설정에서 {{ $environments[$selectedEnv]['name'] ?? strtoupper($selectedEnv) }} 서버 URL을 설정해주세요.
            </div>
        @endif
    </div>

    <!-- 메뉴 비교 테이블 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 flex-1 min-h-0 overflow-hidden">
        <!-- 로컬 메뉴 -->
        <div class="bg-white rounded-lg shadow-sm flex flex-col min-h-0">
            <div class="px-4 py-3 border-b border-gray-200 flex items-center justify-between flex-shrink-0">
                <div class="flex items-center gap-2">
                    <input type="checkbox" id="selectAllLocal" onchange="toggleSelectAll('local', this.checked)"
                           class="w-4 h-4 text-green-600 border-gray-300 rounded focus:ring-green-500">
                    <span class="w-6 h-6 bg-green-100 rounded flex items-center justify-center">
                        <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                        </svg>
                    </span>
                    <h3 class="font-semibold text-gray-800">로컬 - {{ $localTenantName }}</h3>
                    <span class="text-xs text-gray-500">({{ count($localMenus) }}개 그룹)</span>
                </div>
                @if(!empty($environments[$selectedEnv]['url']) && !$remoteError)
                    <div class="flex items-center gap-2">
                        <span id="localSelectedCount" class="text-xs text-gray-500">0개 선택</span>
                        <button type="button" onclick="pushSelected()"
                                class="px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white text-xs font-medium rounded transition-colors flex items-center gap-1">
                            Push →
                        </button>
                    </div>
                @endif
            </div>
            <div class="overflow-auto flex-1 p-2">
                @foreach($localMenus as $menu)
                    @include('menus._sync_menu_item', [
                        'menu' => $menu,
                        'side' => 'local',
                        'diff' => $diff,
                        'depth' => 0
                    ])
                @endforeach
            </div>
        </div>

        <!-- 원격 메뉴 -->
        <div class="bg-white rounded-lg shadow-sm flex flex-col min-h-0">
            <div class="px-4 py-3 border-b border-gray-200 flex items-center justify-between flex-shrink-0">
                <div class="flex items-center gap-2">
                    <input type="checkbox" id="selectAllRemote" onchange="toggleSelectAll('remote', this.checked)"
                           class="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500">
                    <span class="w-6 h-6 bg-purple-100 rounded flex items-center justify-center">
                        <svg class="w-4 h-4 text-purple-600" 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>
                    </span>
                    <h3 class="font-semibold text-gray-800">{{ $environments[$selectedEnv]['name'] ?? strtoupper($selectedEnv) }}{{ $remoteTenantName ? ' - ' . $remoteTenantName : '' }}</h3>
                    <span class="text-xs text-gray-500">({{ count($remoteMenus) }}개 그룹)</span>
                </div>
                @if(!empty($environments[$selectedEnv]['url']) && !$remoteError)
                    <div class="flex items-center gap-2">
                        <span id="remoteSelectedCount" class="text-xs text-gray-500">0개 선택</span>
                        <button type="button" onclick="pullSelected()"
                                class="px-3 py-1.5 bg-purple-600 hover:bg-purple-700 text-white text-xs font-medium rounded transition-colors flex items-center gap-1">
                            ← Pull
                        </button>
                    </div>
                @endif
            </div>
            <div class="overflow-auto flex-1 p-2">
                @if(empty($environments[$selectedEnv]['url']))
                    <div class="flex items-center justify-center h-full text-gray-400">
                        <p>환경을 설정해주세요</p>
                    </div>
                @elseif($remoteError)
                    <div class="flex items-center justify-center h-full text-red-400">
                        <p>연결 실패</p>
                    </div>
                @elseif(empty($remoteMenus))
                    <div class="flex items-center justify-center h-full text-gray-400">
                        <p>메뉴가 없습니다</p>
                    </div>
                @else
                    @foreach($remoteMenus as $menu)
                        @include('menus._sync_menu_item', [
                            'menu' => $menu,
                            'side' => 'remote',
                            'diff' => $diff,
                            'depth' => 0
                        ])
                    @endforeach
                @endif
            </div>
        </div>
    </div>
</div>

@include('partials.sync-settings-modal')
@endsection

@push('scripts')
<script>
    const selectedEnv = '{{ $selectedEnv }}';
    const csrfToken = '{{ csrf_token() }}';

    // 선택된 메뉴 Push
    async function pushSelected() {
        const checkboxes = document.querySelectorAll('input[name="local_menu"]:checked');
        if (checkboxes.length === 0) {
            alert('Push할 메뉴를 선택해주세요.');
            return;
        }

        const menuIds = Array.from(checkboxes).map(cb => parseInt(cb.dataset.menuId));

        if (!confirm(`${menuIds.length}개 메뉴를 ${selectedEnv === 'dev' ? '개발' : '운영'} 서버로 Push 하시겠습니까?`)) {
            return;
        }

        try {
            const response = await fetch('{{ route("menus.sync.push") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json'
                },
                credentials: 'same-origin',
                body: JSON.stringify({ env: selectedEnv, menu_ids: menuIds })
            });

            const result = await response.json();
            if (result.success) {
                alert(result.message);
                location.reload();
            } else {
                alert(result.error || 'Push 실패');
            }
        } catch (e) {
            alert('오류 발생: ' + e.message);
        }
    }

    // 선택된 메뉴 Pull
    async function pullSelected() {
        const checkboxes = document.querySelectorAll('input[name="remote_menu"]:checked');
        if (checkboxes.length === 0) {
            alert('Pull할 메뉴를 선택해주세요.');
            return;
        }

        const menuNames = Array.from(checkboxes).map(cb => cb.value);

        if (!confirm(`${menuNames.length}개 메뉴를 로컬로 Pull 하시겠습니까?`)) {
            return;
        }

        try {
            const response = await fetch('{{ route("menus.sync.pull") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json'
                },
                credentials: 'same-origin',
                body: JSON.stringify({ env: selectedEnv, menu_names: menuNames })
            });

            const result = await response.json();
            if (result.success) {
                alert(result.message);
                location.reload();
            } else {
                alert(result.error || 'Pull 실패');
            }
        } catch (e) {
            alert('오류 발생: ' + e.message);
        }
    }

    // 전체 선택 (활성화된 체크박스만)
    function toggleSelectAll(side, checked) {
        const checkboxes = document.querySelectorAll(`input[name="${side}_menu"]:not(:disabled)`);
        checkboxes.forEach(cb => cb.checked = checked);
        updateSelectedCount(side);
    }

    // 선택된 개수 업데이트
    function updateSelectedCount(side) {
        const checkboxes = document.querySelectorAll(`input[name="${side}_menu"]:checked`);
        const countEl = document.getElementById(`${side}SelectedCount`);
        if (countEl) {
            countEl.textContent = `${checkboxes.length}개 선택`;
        }
    }

    // 체크박스 변경 이벤트 리스너
    document.addEventListener('change', function(e) {
        if (e.target.name === 'local_menu') {
            updateSelectedCount('local');
        } else if (e.target.name === 'remote_menu') {
            updateSelectedCount('remote');
        }
    });

    // 상위 메뉴 체크 시 하위 메뉴도 선택/해제
    function toggleChildren(checkbox) {
        const menuGroup = checkbox.closest('.menu-group');
        if (!menuGroup) return;

        const childrenContainer = menuGroup.querySelector(':scope > .children-container');
        if (!childrenContainer) return;

        const childCheckboxes = childrenContainer.querySelectorAll('input[type="checkbox"]:not(:disabled)');
        childCheckboxes.forEach(cb => {
            cb.checked = checkbox.checked;
        });

        // 선택 개수 업데이트
        const side = checkbox.name.replace('_menu', '');
        updateSelectedCount(side);
    }
</script>
@endpush
