@extends('admin.layout')

@section('header-title', 'Menü Düzenle: ' . $menu->name)

@section('content')
<style>
    .menu-page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 28px;
    }
    .menu-page-title {
        font-size: 24px;
        font-weight: 800;
        color: #1f2937;
    }
    .menu-page-subtitle {
        font-size: 14px;
        color: #6b7280;
        margin-top: 4px;
    }
    .menu-btn {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 10px 18px;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
        text-decoration: none;
        transition: all 0.2s;
    }
    .menu-btn-primary { background: #1e40af; color: white; }
    .menu-btn-primary:hover { background: #1e3a8a; color: white; }
    .menu-btn-success { background: #059669; color: white; }
    .menu-btn-success:hover { background: #047857; color: white; }
    .menu-btn-warning { background: #d97706; color: white; }
    .menu-btn-warning:hover { background: #b45309; color: white; }
    .menu-btn-danger { background: #dc2626; color: white; }
    .menu-btn-danger:hover { background: #b91c1c; color: white; }
    .menu-btn-secondary { background: #e5e7eb; color: #1f2937; }
    .menu-btn-secondary:hover { background: #d1d5db; }
    .menu-btn-sm { padding: 6px 12px; font-size: 12px; }

    .menu-layout-grid {
        display: grid;
        grid-template-columns: 1fr 360px;
        gap: 24px;
        align-items: start;
    }

    .menu-card {
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0,0,0,0.08);
        margin-bottom: 20px;
    }
    .menu-card-header {
        background: #f9fafb;
        border-bottom: 1px solid #e5e7eb;
        padding: 16px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .menu-card-title {
        font-size: 15px;
        font-weight: 700;
        color: #1f2937;
        margin: 0;
    }
    .menu-card-body { padding: 20px; }
    .menu-card-footer {
        background: #f9fafb;
        border-top: 1px solid #e5e7eb;
        padding: 16px 20px;
        display: flex;
        gap: 10px;
        justify-content: flex-end;
    }

    .menu-form-group { margin-bottom: 16px; }
    .menu-form-label {
        display: block;
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 5px;
        font-size: 13px;
    }
    .menu-form-control {
        width: 100%;
        padding: 9px 12px;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        font-size: 13px;
        outline: none;
    }
    .menu-form-control:focus {
        border-color: #1e40af;
        box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
    }
    .menu-form-select {
        appearance: none;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
        background-position: right 10px center;
        background-repeat: no-repeat;
        background-size: 16px;
    }
    .menu-form-check {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
    }
    .menu-form-check input[type="checkbox"] {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }
    .menu-form-check label {
        cursor: pointer;
        font-weight: 500;
        color: #374151;
        font-size: 13px;
    }
    .menu-form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }

    /* Menu Items List */
    .menu-items-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    .menu-item {
        background: #f9fafb;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        margin-bottom: 8px;
        overflow: hidden;
    }
    .menu-item-header {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px 14px;
    }
    .menu-item-drag {
        cursor: grab;
        color: #9ca3af;
        font-size: 16px;
        flex-shrink: 0;
    }
    .menu-item-icon {
        font-size: 16px;
        flex-shrink: 0;
    }
    .menu-item-info {
        flex: 1;
        min-width: 0;
    }
    .menu-item-label {
        font-weight: 600;
        color: #1f2937;
        font-size: 14px;
    }
    .menu-item-url {
        font-size: 12px;
        color: #6b7280;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .menu-item-badge {
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 600;
    }
    .menu-badge-active { background: #d1fae5; color: #065f46; }
    .menu-badge-inactive { background: #fee2e2; color: #991b1b; }

    .menu-item-actions {
        display: flex;
        gap: 6px;
        flex-shrink: 0;
    }

    .menu-edit-form {
        display: none;
        padding: 14px;
        background: #f3f4f6;
        border-top: 1px solid #e5e7eb;
    }
    .menu-edit-form.active { display: block; }

    .menu-children-list {
        list-style: none;
        padding: 0;
        margin: 8px 0 0 24px;
    }
    .menu-children-list > .menu-item {
        background: #ffffff;
        border: 1px dashed #d1d5db;
    }

    .menu-empty-state {
        text-align: center;
        padding: 40px 20px;
        color: #9ca3af;
    }
    .menu-empty-state-icon {
        font-size: 48px;
        margin-bottom: 12px;
    }
    .menu-empty-state p {
        font-size: 14px;
        line-height: 1.6;
    }

    .menu-alert {
        padding: 12px 16px;
        border-radius: 8px;
        margin-bottom: 20px;
        font-size: 14px;
    }
    .menu-alert-success { background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0; }
    .menu-alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5; }

    .menu-badge-location-top { background: #dbeafe; color: #1e40af; }
    .menu-badge-location-footer { background: #f3e8ff; color: #6b21a8; }
    .menu-badge-location {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
    }

    @media (max-width: 900px) {
        .menu-layout-grid { grid-template-columns: 1fr; }
        .menu-form-row { grid-template-columns: 1fr; }
    }
</style>

<div class="menu-page-header">
    <div>
        <h1 class="menu-page-title">✏️ {{ $menu->name }}</h1>
        <p class="menu-page-subtitle">
            <span class="menu-badge-location menu-badge-location-{{ $menu->location }}">
                {{ $locations[$menu->location] ?? $menu->location }}
            </span>
            · {{ $rootItems->count() }} öğe
        </p>
    </div>
    <a href="{{ route('admin.menus.index') }}" class="menu-btn menu-btn-secondary">← Geri Dön</a>
</div>

@if(session('success'))
<div class="menu-alert menu-alert-success">✅ {{ session('success') }}</div>
@endif
@if(session('error'))
<div class="menu-alert menu-alert-error">❌ {{ session('error') }}</div>
@endif

<div class="menu-layout-grid">

    {{-- LEFT: Menu Items --}}
    <div>
        {{-- Add New Item Form --}}
        <div class="menu-card">
            <div class="menu-card-header">
                <h3 class="menu-card-title">➕ Yeni Menü Öğesi Ekle</h3>
            </div>
            <div class="menu-card-body">
                <form method="POST" action="{{ route('admin.menus.items.store', $menu) }}">
                    @csrf
                    <div class="menu-form-row">
                        <div class="menu-form-group">
                            <label class="menu-form-label">Etiket *</label>
                            <input type="text" name="label" class="menu-form-control" placeholder="Örn: Ana Sayfa" required>
                        </div>
                        <div class="menu-form-group">
                            <label class="menu-form-label">URL</label>
                            <input type="text" name="url" class="menu-form-control" placeholder="Örn: /blog">
                        </div>
                    </div>
                    <div class="menu-form-row">
                        <div class="menu-form-group">
                            <label class="menu-form-label">İkon (Emoji)</label>
                            <input type="text" name="icon" class="menu-form-control" placeholder="Örn: 📰">
                        </div>
                        <div class="menu-form-group">
                            <label class="menu-form-label">Üst Öğe (Alt menü için)</label>
                            <select name="parent_id" class="menu-form-control menu-form-select">
                                <option value="">— Ana Menü Öğesi —</option>
                                @foreach($rootItems as $rootItem)
                                <option value="{{ $rootItem->id }}">{{ $rootItem->label }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div style="display:flex; gap:16px; margin-bottom:12px;">
                        <div class="menu-form-check">
                            <input type="checkbox" id="is_active_new" name="is_active" value="1" checked>
                            <label for="is_active_new">Aktif</label>
                        </div>
                        <div class="menu-form-check">
                            <input type="checkbox" id="open_in_new_tab_new" name="open_in_new_tab" value="1">
                            <label for="open_in_new_tab_new">Yeni sekmede aç</label>
                        </div>
                    </div>
                    <button type="submit" class="menu-btn menu-btn-success menu-btn-sm">+ Ekle</button>
                </form>
            </div>
        </div>

        {{-- Menu Items List --}}
        <div class="menu-card">
            <div class="menu-card-header">
                <h3 class="menu-card-title">📋 Menü Öğeleri</h3>
                <span style="font-size:13px; color:#6b7280;">Sürükle-bırak ile sıralayın</span>
            </div>
            <div class="menu-card-body" style="padding: 12px;">
                @if($rootItems->isEmpty())
                <div class="menu-empty-state">
                    <div class="menu-empty-state-icon">📂</div>
                    <p>Henüz menü öğesi eklenmemiş.<br>Sol taraftaki formu kullanarak ekleyin.</p>
                </div>
                @else
                <ul class="menu-items-list" id="sortable-menu">
                    @foreach($rootItems as $item)
                    <li class="menu-item" data-id="{{ $item->id }}">
                        <div class="menu-item-header">
                            <span class="menu-item-drag">⠿</span>
                            @if($item->icon)
                            <span class="menu-item-icon">{{ $item->icon }}</span>
                            @endif
                            <div class="menu-item-info">
                                <div class="menu-item-label">{{ $item->label }}</div>
                                <div class="menu-item-url">{{ $item->url ?: '—' }}</div>
                            </div>
                            <span class="menu-item-badge {{ $item->is_active ? 'menu-badge-active' : 'menu-badge-inactive' }}">
                                {{ $item->is_active ? '✓' : '✗' }}
                            </span>
                            <div class="menu-item-actions">
                                <button type="button" class="menu-btn menu-btn-warning menu-btn-sm"
                                        onclick="toggleEditForm({{ $item->id }})">✏️</button>
                                <form action="{{ route('admin.menus.items.destroy', [$menu, $item]) }}" method="POST"
                                      onsubmit="return confirm('Bu öğeyi silmek istediğinizden emin misiniz?')">
                                    @csrf @method('DELETE')
                                    <button type="submit" class="menu-btn menu-btn-danger menu-btn-sm">🗑️</button>
                                </form>
                            </div>
                        </div>

                        {{-- Inline edit form --}}
                        <div id="edit-form-{{ $item->id }}" class="menu-edit-form">
                            <form method="POST" action="{{ route('admin.menus.items.update', [$menu, $item]) }}">
                                @csrf @method('PUT')
                                <div class="menu-form-row">
                                    <div class="menu-form-group">
                                        <label class="menu-form-label">Etiket</label>
                                        <input type="text" name="label" class="menu-form-control" value="{{ $item->label }}" required>
                                    </div>
                                    <div class="menu-form-group">
                                        <label class="menu-form-label">URL</label>
                                        <input type="text" name="url" class="menu-form-control" value="{{ $item->url }}">
                                    </div>
                                </div>
                                <div class="menu-form-group">
                                    <label class="menu-form-label">İkon</label>
                                    <input type="text" name="icon" class="menu-form-control" value="{{ $item->icon }}" placeholder="Emoji veya ikon kodu">
                                </div>
                                <div style="display:flex; gap:16px; margin-bottom:12px;">
                                    <div class="menu-form-check">
                                        <input type="checkbox" id="active_{{ $item->id }}" name="is_active" value="1" {{ $item->is_active ? 'checked' : '' }}>
                                        <label for="active_{{ $item->id }}">Aktif</label>
                                    </div>
                                    <div class="menu-form-check">
                                        <input type="checkbox" id="newtab_{{ $item->id }}" name="open_in_new_tab" value="1" {{ $item->open_in_new_tab ? 'checked' : '' }}>
                                        <label for="newtab_{{ $item->id }}">Yeni sekmede aç</label>
                                    </div>
                                </div>
                                <div style="display:flex; gap:8px;">
                                    <button type="submit" class="menu-btn menu-btn-primary menu-btn-sm">Kaydet</button>
                                    <button type="button" class="menu-btn menu-btn-secondary menu-btn-sm" onclick="toggleEditForm({{ $item->id }})">İptal</button>
                                </div>
                            </form>
                        </div>

                        {{-- Children --}}
                        @if($item->children->isNotEmpty())
                        <ul class="menu-children-list">
                            @foreach($item->children as $child)
                            <li class="menu-item" data-id="{{ $child->id }}" data-parent="{{ $item->id }}">
                                <div class="menu-item-header">
                                    <span class="menu-item-drag">⠿</span>
                                    @if($child->icon)
                                    <span class="menu-item-icon">{{ $child->icon }}</span>
                                    @endif
                                    <div class="menu-item-info">
                                        <div class="menu-item-label">{{ $child->label }}</div>
                                        <div class="menu-item-url">{{ $child->url ?: '—' }}</div>
                                    </div>
                                    <span class="menu-item-badge {{ $child->is_active ? 'menu-badge-active' : 'menu-badge-inactive' }}">
                                        {{ $child->is_active ? '✓' : '✗' }}
                                    </span>
                                    <div class="menu-item-actions">
                                        <button type="button" class="menu-btn menu-btn-warning menu-btn-sm"
                                                onclick="toggleEditForm({{ $child->id }})">✏️</button>
                                        <form action="{{ route('admin.menus.items.destroy', [$menu, $child]) }}" method="POST"
                                              onsubmit="return confirm('Bu alt öğeyi silmek istediğinizden emin misiniz?')">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="menu-btn menu-btn-danger menu-btn-sm">🗑️</button>
                                        </form>
                                    </div>
                                </div>

                                {{-- Inline edit form for child --}}
                                <div id="edit-form-{{ $child->id }}" class="menu-edit-form">
                                    <form method="POST" action="{{ route('admin.menus.items.update', [$menu, $child]) }}">
                                        @csrf @method('PUT')
                                        <div class="menu-form-row">
                                            <div class="menu-form-group">
                                                <label class="menu-form-label">Etiket</label>
                                                <input type="text" name="label" class="menu-form-control" value="{{ $child->label }}" required>
                                            </div>
                                            <div class="menu-form-group">
                                                <label class="menu-form-label">URL</label>
                                                <input type="text" name="url" class="menu-form-control" value="{{ $child->url }}">
                                            </div>
                                        </div>
                                        <div class="menu-form-group">
                                            <label class="menu-form-label">İkon</label>
                                            <input type="text" name="icon" class="menu-form-control" value="{{ $child->icon }}">
                                        </div>
                                        <div style="display:flex; gap:16px; margin-bottom:12px;">
                                            <div class="menu-form-check">
                                                <input type="checkbox" id="active_{{ $child->id }}" name="is_active" value="1" {{ $child->is_active ? 'checked' : '' }}>
                                                <label for="active_{{ $child->id }}">Aktif</label>
                                            </div>
                                            <div class="menu-form-check">
                                                <input type="checkbox" id="newtab_{{ $child->id }}" name="open_in_new_tab" value="1" {{ $child->open_in_new_tab ? 'checked' : '' }}>
                                                <label for="newtab_{{ $child->id }}">Yeni sekmede aç</label>
                                            </div>
                                        </div>
                                        <div style="display:flex; gap:8px;">
                                            <button type="submit" class="menu-btn menu-btn-primary menu-btn-sm">Kaydet</button>
                                            <button type="button" class="menu-btn menu-btn-secondary menu-btn-sm" onclick="toggleEditForm({{ $child->id }})">İptal</button>
                                        </div>
                                    </form>
                                </div>
                            </li>
                            @endforeach
                        </ul>
                        @endif
                    </li>
                    @endforeach
                </ul>
                @endif
            </div>
        </div>
    </div>

    {{-- RIGHT: Menu Settings --}}
    <div>
        {{-- Menu Basic Settings --}}
        <div class="menu-card">
            <div class="menu-card-header">
                <h3 class="menu-card-title">⚙️ Menü Ayarları</h3>
            </div>
            <div class="menu-card-body">
                <form method="POST" action="{{ route('admin.menus.update', $menu) }}">
                    @csrf @method('PUT')
                    <div class="menu-form-group">
                        <label class="menu-form-label">Menü Adı</label>
                        <input type="text" name="name" class="menu-form-control"
                               value="{{ old('name', $menu->name) }}" required>
                    </div>

                    <div class="menu-form-group">
                        <label class="menu-form-label">Konum</label>
                        <select name="location" class="menu-form-control menu-form-select" required>
                            @foreach($locations as $key => $label)
                            <option value="{{ $key }}" {{ $menu->location == $key ? 'selected' : '' }}>
                                {{ $label }}
                            </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="menu-form-group">
                        <label class="menu-form-label">Açıklama</label>
                        <textarea name="description" class="menu-form-control"
                                  rows="2">{{ old('description', $menu->description) }}</textarea>
                    </div>

                    <div class="menu-form-check" style="margin-bottom:16px;">
                        <input type="checkbox" id="is_active" name="is_active" value="1"
                               {{ $menu->is_active ? 'checked' : '' }}>
                        <label for="is_active">Aktif (göster)</label>
                    </div>

                    <button type="submit" class="menu-btn menu-btn-primary" style="width:100%;">Ayarları Kaydet</button>
                </form>
            </div>
        </div>

        {{-- Quick Links --}}
        <div class="menu-card">
            <div class="menu-card-header">
                <h3 class="menu-card-title">🔗 Hızlı Bağlantı Ekle</h3>
            </div>
            <div class="menu-card-body">
                <p style="font-size:13px; color:#6b7280; margin-bottom:14px;">Sık kullanılan sayfalara hızlıca bağlantı ekleyin:</p>
                <div style="display:flex; flex-direction:column; gap:8px;">
                    @php
                    $quickLinks = [
                        ['label' => '🏠 Ana Sayfa', 'url' => '/'],
                        ['label' => '📰 Blog', 'url' => '/blog'],
                        ['label' => '💬 Forum', 'url' => '/forum'],
                        ['label' => '📚 Kütüphane', 'url' => '/library'],
                        ['label' => '🎯 Mülakat', 'url' => '/interview'],
                        ['label' => '💭 Sohbet', 'url' => '/sohbet'],
                        ['label' => '🧮 Hesaplamalar', 'url' => '/hesaplamalar'],
                        ['label' => '🤖 AI Asistan', 'url' => '/ai'],
                        ['label' => 'ℹ️ Hakkımızda', 'url' => '/sayfa/hakkimizda'],
                        ['label' => '🔒 Gizlilik', 'url' => '/sayfa/gizlilik-politikasi'],
                    ];
                    @endphp
                    @foreach($quickLinks as $link)
                    <form method="POST" action="{{ route('admin.menus.items.store', $menu) }}" style="margin:0;">
                        @csrf
                        <input type="hidden" name="label" value="{{ $link['label'] }}">
                        <input type="hidden" name="url" value="{{ $link['url'] }}">
                        <input type="hidden" name="is_active" value="1">
                        <button type="submit" style="width:100%; text-align:left; background:#f9fafb; border:1px solid #e5e7eb; border-radius:6px; padding:8px 12px; font-size:13px; cursor:pointer; transition: background 0.15s;" onmouseover="this.style.background='#eff6ff'" onmouseout="this.style.background='#f9fafb'">
                            {{ $link['label'] }} <span style="color:#9ca3af; float:right;">+</span>
                        </button>
                    </form>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
<script>
function toggleEditForm(id) {
    const form = document.getElementById('edit-form-' + id);
    if (form) {
        form.classList.toggle('active');
    }
}

// ── Drag & Drop Sıralama ─────────────────────────────────────────────────
const REORDER_URL = '{{ route("admin.menus.items.reorder", $menu) }}';
const CSRF_TOKEN  = '{{ csrf_token() }}';

function saveOrder(items) {
    fetch(REORDER_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': CSRF_TOKEN,
            'Accept': 'application/json',
        },
        body: JSON.stringify({ items })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            showToast('✅ Sıralama kaydedildi', 'success');
        } else {
            showToast('❌ Kayıt hatası', 'error');
        }
    })
    .catch(() => showToast('❌ Bağlantı hatası', 'error'));
}

function getOrderFromList(listEl, parentId = null) {
    const items = [];
    listEl.querySelectorAll(':scope > .menu-item').forEach((el, idx) => {
        items.push({
            id:         parseInt(el.dataset.id),
            sort_order: idx,
            parent_id:  parentId
        });
    });
    return items;
}

// Main sortable list
const mainList = document.getElementById('sortable-menu');
if (mainList) {
    Sortable.create(mainList, {
        animation: 180,
        handle: '.menu-item-drag',
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen',
        onEnd: function () {
            saveOrder(getOrderFromList(mainList, null));
        }
    });

    // Child sortable lists
    mainList.querySelectorAll('.menu-children-list').forEach(childList => {
        const parentId = parseInt(childList.closest('.menu-item').dataset.id);
        Sortable.create(childList, {
            animation: 180,
            handle: '.menu-item-drag',
            ghostClass: 'sortable-ghost',
            chosenClass: 'sortable-chosen',
            onEnd: function () {
                saveOrder(getOrderFromList(childList, parentId));
            }
        });
    });
}

// ── Toast ───────────────────────────────────────────────────────────────
function showToast(msg, type) {
    let t = document.getElementById('menu-toast');
    if (!t) {
        t = document.createElement('div');
        t.id = 'menu-toast';
        Object.assign(t.style, {
            position: 'fixed', bottom: '24px', right: '24px', zIndex: '9999',
            padding: '12px 20px', borderRadius: '10px',
            fontWeight: '600', fontSize: '14px',
            boxShadow: '0 4px 16px rgba(0,0,0,0.15)',
            transition: 'opacity 0.3s', opacity: '0'
        });
        document.body.appendChild(t);
    }
    t.textContent = msg;
    t.style.background = type === 'success' ? '#d1fae5' : '#fee2e2';
    t.style.color       = type === 'success' ? '#065f46' : '#991b1b';
    t.style.border      = type === 'success' ? '1px solid #a7f3d0' : '1px solid #fca5a5';
    t.style.opacity = '1';
    clearTimeout(t._timeout);
    t._timeout = setTimeout(() => { t.style.opacity = '0'; }, 2500);
}
</script>

<style>
.sortable-ghost  { opacity: .4; background: #eff6ff !important; border: 2px dashed #3b82f6 !important; }
.sortable-chosen { box-shadow: 0 4px 16px rgba(30,64,175,.2) !important; }
.menu-item-drag  { cursor: grab !important; user-select: none; }
.menu-item-drag:active { cursor: grabbing !important; }
</style>
@endsection
