@extends('layouts.app')

@section('title', '글로벌 메뉴 수정')

@section('content')
    <div class="max-w-4xl mx-auto">
        <!-- 페이지 헤더 -->
        <div class="flex justify-between items-center mb-6">
            <div>
                <h1 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                    <x-sidebar.menu-icon icon="menu" class="w-6 h-6" />
                    글로벌 메뉴 수정
                </h1>
                <p class="text-sm text-gray-500 mt-1">시스템 전체에서 사용되는 기본 메뉴를 수정합니다.</p>
            </div>
            <a href="{{ route('menus.global.index') }}" class="text-gray-600 hover:text-gray-800">
                ← 목록으로
            </a>
        </div>

        <!-- 폼 카드 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <form id="menuForm" action="/api/admin/global-menus/{{ $menu->id }}" method="POST">
                @csrf
                @method('PUT')

                <!-- 부모 메뉴 -->
                <div class="mb-4">
                    <label for="parent_id" class="block text-sm font-medium text-gray-700 mb-2">
                        부모 메뉴
                    </label>
                    <select name="parent_id" id="parent_id"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500">
                        <option value="">최상위 메뉴</option>
                        @foreach($parentMenus as $parent)
                            @if($parent->id != $menu->id)
                                <option value="{{ $parent->id }}" {{ $menu->parent_id == $parent->id ? 'selected' : '' }}>
                                    {{ str_repeat('── ', $parent->depth ?? 0) }}{{ $parent->name }}
                                </option>
                            @endif
                        @endforeach
                    </select>
                </div>

                <!-- 메뉴명 -->
                <div class="mb-4">
                    <label for="name" class="block text-sm font-medium text-gray-700 mb-2">
                        메뉴명 <span class="text-red-500">*</span>
                    </label>
                    <input type="text" name="name" id="name" required
                           value="{{ old('name', $menu->name) }}"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500">
                </div>

                <!-- URL -->
                <div class="mb-4">
                    <label for="url" class="block text-sm font-medium text-gray-700 mb-2">
                        URL
                    </label>
                    <input type="text" name="url" id="url"
                           value="{{ old('url', $menu->url) }}"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                           placeholder="/dashboard">
                </div>

                <!-- 아이콘 -->
                @php $currentIcon = old('icon', $menu->icon); @endphp
                @include('partials.icon-picker', ['currentIcon' => $currentIcon, 'theme' => 'purple'])

                <!-- 정렬 순서 -->
                <div class="mb-4">
                    <label for="sort_order" class="block text-sm font-medium text-gray-700 mb-2">
                        정렬 순서
                    </label>
                    <input type="number" name="sort_order" id="sort_order"
                           value="{{ old('sort_order', $menu->sort_order ?? 0) }}" min="0"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500">
                </div>

                <!-- 체크박스 그룹 -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <!-- 활성 상태 -->
                    <div class="flex items-center">
                        <input type="checkbox" name="is_active" id="is_active" value="1"
                               {{ old('is_active', $menu->is_active) ? 'checked' : '' }}
                               class="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500">
                        <label for="is_active" class="ml-2 text-sm text-gray-700">
                            활성 상태
                        </label>
                    </div>

                    <!-- 숨김 -->
                    <div class="flex items-center">
                        <input type="checkbox" name="hidden" id="hidden" value="1"
                               {{ old('hidden', $menu->hidden) ? 'checked' : '' }}
                               class="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500">
                        <label for="hidden" class="ml-2 text-sm text-gray-700">
                            숨김
                        </label>
                    </div>

                    <!-- 외부 링크 -->
                    <div class="flex items-center">
                        <input type="checkbox" name="is_external" id="is_external" value="1"
                               {{ old('is_external', $menu->is_external) ? 'checked' : '' }}
                               class="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500">
                        <label for="is_external" class="ml-2 text-sm text-gray-700">
                            외부 링크
                        </label>
                    </div>
                </div>

                <!-- 외부 URL (is_external 체크 시 표시) -->
                <div id="external-url-group" class="mb-4 {{ $menu->is_external ? '' : 'hidden' }}">
                    <label for="external_url" class="block text-sm font-medium text-gray-700 mb-2">
                        외부 URL
                    </label>
                    <input type="text" name="external_url" id="external_url"
                           value="{{ old('external_url', $menu->external_url) }}"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                           placeholder="https://example.com">
                </div>

                <!-- 확장 옵션 섹션 -->
                @php
                    $hasOptions = $menu->options && count($menu->options) > 0;
                    $currentSection = $menu->getSection() ?? 'main';
                    $currentMeta = $menu->getMeta();
                    $currentMetaJson = $currentMeta ? json_encode($currentMeta, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) : '';
                @endphp
                <div class="border-t border-gray-200 pt-4 mt-6 mb-4">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-sm font-semibold text-gray-700">
                            확장 옵션
                            @if($hasOptions)
                                <span class="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-700">{{ count($menu->options) }}</span>
                            @endif
                        </h3>
                        <button type="button" onclick="toggleOptionsSection()" class="text-xs text-purple-600 hover:text-purple-800">
                            <span id="options-toggle-text">접기</span>
                        </button>
                    </div>

                    <div id="options-section" class="space-y-4">
                        <!-- section -->
                        <div>
                            <label for="option_section" class="block text-sm font-medium text-gray-700 mb-1">
                                section
                            </label>
                            <select name="option_section" id="option_section"
                                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500">
                                <option value="main" {{ $currentSection === 'main' ? 'selected' : '' }}>main (기본)</option>
                                <option value="tools" {{ $currentSection === 'tools' ? 'selected' : '' }}>tools (도구)</option>
                                <option value="labs" {{ $currentSection === 'labs' ? 'selected' : '' }}>labs (실험실)</option>
                            </select>
                            <p class="text-xs text-gray-400 mt-1">사이드바 영역 구분. main: 메인 메뉴, tools: 개발도구 영역, labs: R&D 실험실 영역</p>
                        </div>

                        <!-- meta (JSON) -->
                        <div>
                            <label for="option_meta" class="block text-sm font-medium text-gray-700 mb-1">
                                meta <span class="text-xs text-gray-400">(JSON)</span>
                            </label>
                            <textarea name="option_meta" id="option_meta" rows="3"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 font-mono text-sm"
                                      placeholder='{"tab": "S", "badge": "new"}'>{{ $currentMetaJson }}</textarea>
                            <p class="text-xs text-gray-400 mt-1">추가 메타 데이터 (JSON 형식). 탭 구분, 뱃지 표시 등 커스텀 속성 저장</p>
                        </div>
                    </div>
                </div>

                <!-- 버튼 그룹 -->
                <div class="flex justify-end gap-4 mt-6">
                    <a href="{{ route('menus.global.index') }}"
                       class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                        취소
                    </a>
                    <button type="submit"
                            class="px-6 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition">
                        수정
                    </button>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    // 외부 링크 체크박스 토글
    document.getElementById('is_external').addEventListener('change', function() {
        const externalUrlGroup = document.getElementById('external-url-group');
        if (this.checked) {
            externalUrlGroup.classList.remove('hidden');
        } else {
            externalUrlGroup.classList.add('hidden');
        }
    });

    // 확장 옵션 섹션 토글
    window.toggleOptionsSection = function() {
        const section = document.getElementById('options-section');
        const toggleText = document.getElementById('options-toggle-text');
        if (section.classList.contains('hidden')) {
            section.classList.remove('hidden');
            toggleText.textContent = '접기';
        } else {
            section.classList.add('hidden');
            toggleText.textContent = '펼치기';
        }
    };

    // options 객체 생성
    function buildOptionsObject() {
        const options = {};

        const section = document.getElementById('option_section').value;
        if (section && section !== 'main') {
            options.section = section;
        }

        const metaStr = document.getElementById('option_meta').value.trim();
        if (metaStr) {
            try {
                options.meta = JSON.parse(metaStr);
            } catch (e) {
                showToast('meta 필드의 JSON 형식이 올바르지 않습니다.', 'error');
                throw e;
            }
        }

        return Object.keys(options).length > 0 ? options : null;
    }

    // 폼 제출 처리
    document.getElementById('menuForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        // option_ 접두사 필드 제거
        delete data.option_section;
        delete data.option_meta;

        // options 객체 추가
        try {
            const options = buildOptionsObject();
            if (options) {
                data.options = options;
            }
        } catch (e) {
            return; // JSON 파싱 에러
        }

        try {
            const response = await fetch('/api/admin/global-menus/{{ $menu->id }}', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                showToast(result.message, 'success');
                window.location.href = result.redirect;
            } else {
                showToast(result.message, 'error');
            }
        } catch (error) {
            showToast('글로벌 메뉴 수정 중 오류가 발생했습니다.', 'error');
            console.error(error);
        }
    });
</script>
@endpush