@php
    $user = Auth::user();
    $sidebarItems = app(\App\Support\MenuManager::class)->editorItems($user);
    $menuIcons = \App\Support\MenuManager::iconOptions();
    $defaultMenuIcon = array_key_exists('fa-solid fa-link', $menuIcons)
        ? 'fa-solid fa-link'
        : (array_key_first($menuIcons) ?: 'fa-solid fa-link');
    $hiddenSidebarItemIds = $sidebarItems
        ->filter(fn (array $item) => ! (bool) ($item['is_visible'] ?? true))
        ->pluck('id')
        ->map(fn ($id) => (int) $id)
        ->values()
        ->all();

    $roleLabelMap = [
        'admin' => __('Administrator'),
        'manager' => __('Manager'),
        'employee' => __('Employee'),
    ];

    $roleLabel = $roleLabelMap[$user->role] ?? $user->role;
    $brand = app(\App\Support\BrandingManager::class)->sidebarBrand($user);
    $brandName = (string) ($brand['name'] ?? config('app.name', 'CRM25'));
    $brandLogoUrl = (string) ($brand['logo_url'] ?? asset('logo_crm25.png'));
@endphp

<div class="relative z-40 lg:z-auto">
    <aside
        x-data="{
            collapsed: @js((bool) $user->sidebar_collapsed),
            hoverExpanded: false,
            menuEditMode: false,
            menuSaving: false,
            draggingItemId: null,
            removedCustomMenuIds: [],
            hiddenMenuItemIds: @js($hiddenSidebarItemIds),
            createMenuModalOpen: @js((bool) old('label') || (bool) old('url') || $errors->has('icon') || $errors->has('open_in_new_tab')),
            selectedMenuIcon: @js(old('icon', $defaultMenuIcon)),
            menuIconSearch: '',
            csrfToken: document.querySelector('meta[name=csrf-token]')?.getAttribute('content') ?? '',
            saveState() {
                fetch(@js(route('profile.menu.sidebar')), {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').getAttribute('content'),
                    },
                    body: JSON.stringify({ collapsed: this.collapsed }),
                }).catch(() => {});
            },
            toggle() {
                this.collapsed = !this.collapsed;
                this.hoverExpanded = false;
                this.saveState();
            },
            isUiCollapsed() {
                return this.collapsed && !this.hoverExpanded;
            },
            onSidebarMouseEnter() {
                if (this.collapsed) {
                    this.hoverExpanded = true;
                }
            },
            onSidebarMouseLeave() {
                if (!this.collapsed) {
                    return;
                }

                this.hoverExpanded = false;
                if (this.menuEditMode) {
                    this.menuEditMode = false;
                    this.draggingItemId = null;
                }
            },
            toggleMenuEditMode() {
                this.menuEditMode = !this.menuEditMode;
                if (!this.menuEditMode) {
                    this.draggingItemId = null;
                }
            },
            saveMenuStructure() {
                if (this.menuSaving) {
                    return;
                }

                const menuItemsContainer = this.$refs.sidebarMenuItems;
                if (!menuItemsContainer) {
                    return;
                }

                const order = [];
                const visible = {};
                menuItemsContainer.querySelectorAll('[data-menu-item][data-item-id]').forEach((element) => {
                    const itemId = Number(element.dataset.itemId || 0);
                    if (!itemId) {
                        return;
                    }

                    order.push(itemId);
                    if (!this.hiddenMenuItemIds.includes(itemId)) {
                        visible[itemId] = true;
                    }
                });
                this.removedCustomMenuIds.forEach((itemId) => {
                    if (!order.includes(itemId)) {
                        order.push(itemId);
                    }
                });

                if (order.length === 0) {
                    return;
                }

                const custom = {};
                this.removedCustomMenuIds.forEach((itemId) => {
                    custom[itemId] = { delete: true };
                });

                const payload = {
                    order,
                    visible,
                };

                if (Object.keys(custom).length > 0) {
                    payload.custom = custom;
                }

                this.menuSaving = true;

                fetch(@js(route('profile.menu.update')), {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': this.csrfToken,
                    },
                    body: JSON.stringify(payload),
                })
                    .then((response) => {
                        if (!response.ok) {
                            throw new Error('Menu update failed');
                        }

                        this.removedCustomMenuIds = [];
                    })
                    .catch(() => {
                        window.location.reload();
                    })
                    .finally(() => {
                        this.menuSaving = false;
                    });
            },
            openCreateMenuModal() {
                this.createMenuModalOpen = true;
                this.menuEditMode = false;
            },
            closeCreateMenuModal() {
                this.createMenuModalOpen = false;
            },
            findMenuItemRow(itemId) {
                const id = Number(itemId);
                if (!id) {
                    return null;
                }

                return Array.from(this.$refs.sidebarMenuItems?.querySelectorAll('[data-menu-item][data-item-id]') ?? [])
                    .find((element) => Number(element.dataset.itemId || 0) === id) ?? null;
            },
            removeMenuItem(itemId) {
                if (!this.menuEditMode || this.menuSaving) {
                    return;
                }

                const id = Number(itemId);
                const row = this.findMenuItemRow(id);
                if (!row) {
                    return;
                }

                row.remove();
                if (!this.removedCustomMenuIds.includes(id)) {
                    this.removedCustomMenuIds.push(id);
                }

                this.saveMenuStructure();
            },
            toggleCoreMenuItem(itemId) {
                if (!this.menuEditMode || this.menuSaving) {
                    return;
                }

                const id = Number(itemId);
                if (this.hiddenMenuItemIds.includes(id)) {
                    this.hiddenMenuItemIds = this.hiddenMenuItemIds.filter((hiddenId) => hiddenId !== id);
                } else {
                    this.hiddenMenuItemIds.push(id);
                }

                this.saveMenuStructure();
            },
            onMenuDragStart(event) {
                if (!this.menuEditMode || this.menuSaving) {
                    event.preventDefault();
                    return;
                }

                const row = event.currentTarget;
                this.draggingItemId = row?.dataset?.itemId ?? null;

                if (!this.draggingItemId) {
                    event.preventDefault();
                    return;
                }

                row.classList.add('opacity-60');
                event.dataTransfer.effectAllowed = 'move';
                event.dataTransfer.setData('text/plain', this.draggingItemId);
            },
            onMenuDragOver(event) {
                if (!this.menuEditMode || this.menuSaving || !this.draggingItemId) {
                    return;
                }

                const list = this.$refs.sidebarMenuItems;
                const target = event.currentTarget;
                const dragged = this.findMenuItemRow(this.draggingItemId);

                if (!list || !target || !dragged || dragged === target) {
                    return;
                }

                const targetRect = target.getBoundingClientRect();
                const shouldInsertAfter = event.clientY > targetRect.top + targetRect.height / 2;

                if (shouldInsertAfter) {
                    list.insertBefore(dragged, target.nextElementSibling);
                } else {
                    list.insertBefore(dragged, target);
                }
            },
            onMenuDragEnd(event) {
                event.currentTarget?.classList?.remove('opacity-60');
                this.draggingItemId = null;

                if (this.menuEditMode) {
                    this.saveMenuStructure();
                }
            }
        }"
        @mouseenter="onSidebarMouseEnter()"
        @mouseleave="onSidebarMouseLeave()"
        :class="isUiCollapsed() ? 'w-20' : 'w-72'"
        class="app-sidebar sticky top-0 flex h-screen shrink-0 flex-col border-r border-slate-700 bg-slate-900 text-slate-100 transition-all duration-200"
    >
        <div
            :class="isUiCollapsed() ? 'justify-center' : 'justify-between'"
            class="flex h-20 items-center border-b border-slate-700 px-4"
        >
            <a
                href="{{ route('dashboard') }}"
                x-show="!isUiCollapsed()"
                style="{{ $user->sidebar_collapsed ? 'display: none;' : '' }}"
                class="inline-flex min-w-0 items-center gap-3 rounded-md text-white transition hover:bg-slate-800/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/70 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-900"
            >
                <span class="inline-flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-slate-800/70 p-1">
                    <img src="{{ $brandLogoUrl }}" alt="{{ $brandName }}" class="h-full w-full object-contain" />
                </span>
                <span class="truncate text-sm font-semibold">{{ $brandName }}</span>
            </a>

            <button
                type="button"
                @click="toggle()"
                class="inline-flex h-8 w-8 items-center justify-center rounded-md text-slate-300 hover:bg-slate-800 hover:text-white"
                title="Collapse/expand menu"
            >
                <svg x-show="!collapsed" x-cloak xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
                </svg>
                <svg x-show="collapsed" x-cloak xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5">
                    <path stroke-linecap="round" stroke-linejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                </svg>
            </button>
        </div>

        <nav class="flex-1 overflow-y-auto px-3 py-4">
            <div x-ref="sidebarMenuItems" class="space-y-1">
                @foreach ($sidebarItems as $item)
                    @php
                        $itemId = (int) $item['id'];
                        $itemInitiallyHidden = in_array($itemId, $hiddenSidebarItemIds, true);
                    @endphp
                    <div
                        data-menu-item
                        data-item-id="{{ $itemId }}"
                        x-show="menuEditMode || !hiddenMenuItemIds.includes({{ $itemId }})"
                        :draggable="menuEditMode && !menuSaving"
                        @dragstart="onMenuDragStart($event)"
                        @dragover.prevent="onMenuDragOver($event)"
                        @dragend="onMenuDragEnd($event)"
                        x-bind:title="isUiCollapsed() ? @js($item['label']) : ''"
                        :class="hiddenMenuItemIds.includes({{ $itemId }}) ? 'opacity-60' : ''"
                        @if ($itemInitiallyHidden)
                            style="display:none;"
                        @endif
                        class="group relative flex items-center gap-2"
                    >
                        <a
                            href="{{ $item['url'] }}"
                            @if (($item['open_in_new_tab'] ?? false))
                                target="_blank"
                                rel="noopener noreferrer"
                            @endif
                            @click="if (menuEditMode || menuSaving) { $event.preventDefault(); }"
                            :class="[
                                isUiCollapsed() ? 'justify-center px-2' : 'justify-start px-3',
                                menuEditMode ? 'cursor-move' : '',
                                hiddenMenuItemIds.includes({{ $itemId }}) ? 'border-dashed border-slate-600 text-slate-400' : '',
                                menuSaving ? 'pointer-events-none opacity-60' : ''
                            ].join(' ')"
                            class="flex flex-1 items-center gap-3 rounded-lg border py-2 text-sm font-medium transition
                                {{ $item['is_active'] ? 'border-sky-400/60 bg-sky-500/20 text-sky-100' : 'border-transparent text-slate-200 hover:border-slate-700 hover:bg-slate-800 hover:text-white' }}"
                        >
                            <span x-show="menuEditMode" x-cloak class="inline-flex h-5 w-5 shrink-0 items-center justify-center text-slate-400">
                                <x-menu-icon name="fa-solid fa-grip-vertical" class="h-4 w-4" />
                            </span>
                            <x-menu-icon :name="$item['icon']" class="h-5 w-5 shrink-0" />
                            <span x-show="!isUiCollapsed()" style="{{ $user->sidebar_collapsed ? 'display: none;' : '' }}" class="truncate">{{ $item['label'] }}</span>
                        </a>

                        @if ($item['is_custom'])
                            <button
                                type="button"
                                x-show="menuEditMode"
                                x-cloak
                                @click.stop.prevent="removeMenuItem({{ $itemId }})"
                                class="ml-auto inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-slate-600 bg-slate-800 text-slate-300 hover:border-red-400 hover:text-red-300"
                                title="Delete menu item"
                            >
                                <x-menu-icon name="fa-solid fa-trash-can" class="h-3.5 w-3.5" />
                            </button>
                        @else
                            <button
                                type="button"
                                x-show="menuEditMode"
                                x-cloak
                                @click.stop.prevent="toggleCoreMenuItem({{ $itemId }})"
                                :class="hiddenMenuItemIds.includes({{ $itemId }}) ? 'border-emerald-400 text-emerald-200 hover:text-emerald-100' : 'border-slate-600 text-slate-300 hover:border-red-400 hover:text-red-300'"
                                class="ml-auto inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-slate-800"
                                :title="hiddenMenuItemIds.includes({{ $itemId }}) ? @js(__('Restore menu item')) : @js(__('Hide menu item'))"
                            >
                                <x-menu-icon name="fa-solid fa-trash-can" class="h-3.5 w-3.5" x-show="!hiddenMenuItemIds.includes({{ $itemId }})" x-cloak />
                                <x-menu-icon name="fa-solid fa-rotate-left" class="h-3.5 w-3.5" x-show="hiddenMenuItemIds.includes({{ $itemId }})" x-cloak />
                            </button>
                        @endif
                    </div>
                @endforeach
            </div>

            <div x-show="menuEditMode && !isUiCollapsed()" x-cloak class="mt-2 rounded-md border border-slate-700/80 bg-slate-800/60 px-3 py-2 text-[11px] text-slate-300">
                {{ __('Drag items by the dot icon. The Recycle Bin hides system items and deletes custom items.') }}
            </div>

            <div x-show="menuSaving && !isUiCollapsed()" x-cloak class="mt-2 rounded-md border border-slate-700/80 bg-slate-800/60 px-3 py-2 text-[11px] text-slate-300">
                {{ __('Saving menu changes...') }}
            </div>

            <div class="mt-2 space-y-1 border-t border-slate-700/70 pt-2">
                <button
                    type="button"
                    @click="toggleMenuEditMode()"
                    x-bind:title="isUiCollapsed() ? (menuEditMode ? @js(__('Finish changing menu')) : @js(__('Edit menu'))) : ''"
                    :class="[
                        isUiCollapsed() ? 'justify-center px-2' : 'justify-start px-3',
                        menuEditMode ? 'bg-sky-500/20 text-sky-100' : 'text-slate-200 hover:border-slate-700 hover:bg-slate-800 hover:text-white'
                    ].join(' ')"
                    class="inline-flex w-full items-center gap-3 rounded-lg border border-transparent py-2 text-sm font-medium transition"
                >
                    <x-menu-icon name="fa-solid fa-pen-to-square" class="h-4 w-4 shrink-0" />
                    <span
                        x-show="!isUiCollapsed()"
                        style="{{ $user->sidebar_collapsed ? 'display: none;' : '' }}"
                        x-text="menuEditMode ? @js(__('Finish changing menu')) : @js(__('Edit menu'))"
                    ></span>
                </button>

                <button
                    type="button"
                    @click="openCreateMenuModal()"
                    x-bind:title="isUiCollapsed() ? @js(__('Create a new menu item')) : ''"
                    :class="isUiCollapsed() ? 'justify-center px-2' : 'justify-start px-3'"
                    class="inline-flex w-full items-center gap-3 rounded-lg border border-transparent py-2 text-sm font-medium text-slate-200 transition hover:border-slate-700 hover:bg-slate-800 hover:text-white"
                >
                    <x-menu-icon name="fa-solid fa-plus" class="h-4 w-4 shrink-0" />
                    <span x-show="!isUiCollapsed()" style="{{ $user->sidebar_collapsed ? 'display: none;' : '' }}">{{ __('Create a new menu item') }}</span>
                </button>
            </div>
        </nav>

        <div
            x-show="createMenuModalOpen"
            x-cloak
                class="fixed inset-0 z-[80] flex items-center justify-center bg-slate-950/60 p-4"
                @keydown.escape.window="closeCreateMenuModal()"
            >
            <div class="w-full max-w-3xl rounded-xl border border-slate-300 bg-white shadow-2xl">
                <div class="flex items-center justify-between border-b border-gray-200 px-5 py-4">
                    <h3 class="text-base font-semibold text-gray-900">{{ __('Create a new menu item') }}</h3>
                    <button type="button" @click="closeCreateMenuModal()" class="text-gray-500 hover:text-gray-800">
                        <x-menu-icon name="fa-solid fa-xmark" class="h-5 w-5" />
                    </button>
                </div>

                <form method="POST" action="{{ route('profile.menu.custom.store') }}" class="space-y-4 p-5">
                    @csrf

                    <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                        <div>
                            <label for="sidebar-custom-label" class="block text-sm font-medium text-gray-700">{{ __('Name') }}</label>
                            <input
                                id="sidebar-custom-label"
                                type="text"
                                name="label"
                                value="{{ old('label') }}"
                                required
                                class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                placeholder="{{ __('Knowledge Base') }}"
                            >
                            <x-input-error class="mt-2" :messages="$errors->get('label')" />
                        </div>

                        <div>
                            <label for="sidebar-custom-url" class="block text-sm font-medium text-gray-700">{{ __('Link') }}</label>
                            <input
                                id="sidebar-custom-url"
                                type="url"
                                name="url"
                                value="{{ old('url') }}"
                                required
                                class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                placeholder="https://..."
                            >
                            <x-input-error class="mt-2" :messages="$errors->get('url')" />
                        </div>
                    </div>

                    <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                        <input
                            type="checkbox"
                            name="open_in_new_tab"
                            value="1"
                            @checked(old('open_in_new_tab'))
                            class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                        >
                        {{ __('Open in new tab') }}
                    </label>

                    <div>
                        <p class="text-sm font-medium text-gray-700">{{ __('Font Awesome Icon') }}</p>
                        <p class="mt-1 text-xs text-gray-500">{{ __('Showing all Font Awesome Free icons.') }}</p>

                        <div class="mt-2">
                            <input
                                type="text"
                                x-model="menuIconSearch"
                                class="w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                placeholder="{{ __('Search for an icon (for example, chart, user, github)') }}"
                            >
                        </div>

                        <div class="mt-2 max-h-72 overflow-auto rounded-lg border border-gray-200 p-2">
                            <div class="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4">
                                @foreach ($menuIcons as $iconName => $iconMeta)
                                    <label
                                        data-icon-search="{{ mb_strtolower($iconMeta['label'].' '.$iconName) }}"
                                        class="cursor-pointer rounded-md border px-2 py-2 text-xs transition"
                                        x-show="menuIconSearch.trim() === '' || $el.dataset.iconSearch.includes(menuIconSearch.trim().toLowerCase())"
                                        :class="selectedMenuIcon === @js($iconName) ? 'border-indigo-400 bg-indigo-50 text-indigo-700' : 'border-gray-200 bg-white text-gray-700 hover:border-gray-300'"
                                    >
                                        <input
                                            type="radio"
                                            name="icon"
                                            value="{{ $iconName }}"
                                            class="sr-only"
                                            x-model="selectedMenuIcon"
                                            @checked(old('icon', $defaultMenuIcon) === $iconName)
                                        >
                                        <span class="inline-flex items-center gap-2">
                                            <x-menu-icon :name="$iconName" mode="font" class="h-4 w-4" />
                                            <span class="truncate">{{ $iconMeta['label'] }}</span>
                                        </span>
                                    </label>
                                @endforeach
                            </div>
                        </div>
                        <x-input-error class="mt-2" :messages="$errors->get('icon')" />
                    </div>

                    <div class="flex items-center justify-end gap-3 border-t border-gray-200 pt-4">
                        <button type="button" @click="closeCreateMenuModal()" class="rounded-md border border-gray-300 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50">
                            {{ __('Cancel') }}
                        </button>
                        <button type="submit" class="rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">
                            {{ __('Create an item') }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="mt-auto border-t border-slate-700 p-4">
            @if (session()->has('impersonator_id'))
                <form method="POST" action="{{ route('profile.access.impersonate.leave') }}" class="mb-3">
                    @csrf
                    <button
                        type="submit"
                        x-bind:title="isUiCollapsed() ? @js(__('Back to administrator')) : ''"
                        :class="isUiCollapsed() ? 'justify-center px-2' : 'justify-start px-3'"
                        class="inline-flex w-full items-center gap-3 rounded-md border border-amber-500/50 bg-amber-500/10 py-2 text-xs font-medium text-amber-200 hover:bg-amber-500/20"
                    >
                        <x-menu-icon name="fa-solid fa-right-from-bracket" class="h-4 w-4 shrink-0" />
                        <span x-show="!isUiCollapsed()" style="{{ $user->sidebar_collapsed ? 'display: none;' : '' }}">{{ __('Back to administrator') }}</span>
                    </button>
                </form>
            @endif

            <div x-show="!isUiCollapsed()" style="{{ $user->sidebar_collapsed ? 'display: none;' : '' }}" class="mb-3">
                <p class="truncate text-sm font-semibold text-white">{{ $user->name }}</p>
                <p class="truncate text-xs text-slate-300">{{ $user->email }}</p>
                <p class="mt-1 text-xs text-slate-400">{{ __('Role') }}: {{ $roleLabel }}</p>
            </div>

            <div class="space-y-2">
                <a
                    href="{{ route('profile.edit') }}"
                    x-bind:title="isUiCollapsed() ? @js(__('Profile')) : ''"
                    :class="isUiCollapsed() ? 'justify-center px-2' : 'justify-start px-3'"
                    class="inline-flex w-full items-center gap-3 rounded-md border border-slate-600 py-2 text-xs font-medium text-slate-100 hover:bg-slate-800"
                >
                    <x-menu-icon name="settings" class="h-4 w-4 shrink-0" />
                    <span x-show="!isUiCollapsed()" style="{{ $user->sidebar_collapsed ? 'display: none;' : '' }}">{{ __('Profile') }}</span>
                </a>
            </div>
        </div>
    </aside>
</div>
