<!doctype html>
<html class="loading dark-layout" lang="{{ str_replace('_', '-', app()->getLocale()) }}" data-layout="dark-layout"
      data-textdirection="ltr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="theme-color" content="#080B12">
    <title>@yield('title') | {{ brand_name() }}</title>
    @include('partials.portal-theme-script')

    <link rel="icon" href="{{ site_setting('favicon_path') ? Storage::url(site_setting('favicon_path')) : asset('app-assets/images/ico/favicon.png') }}" type="image/x-icon">
    <link rel="manifest" href="{{ asset('site.webmanifest') }}">
    <link rel="apple-touch-icon" href="{{ asset('apple-touch-icon.png') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/vendors/css/vendors.min.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/vendors/css/extensions/toastr.min.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/vendors/css/tables/datatable/dataTables.bootstrap5.min.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/fonts/font-awesome/css/font-awesome.min.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/vendors/css/feather-icons/feather-icons.min.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/css/bootstrap.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/css/bootstrap-extended.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/css/colors.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/css/components.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('app-assets/css/themes/dark-layout.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/style.css') }}">
    @livewireStyles
    @include('partials.theme-style')
    @stack('css')
</head>

<body class="admin-sidebar-layout admin-portal-v2">
<a class="admin-skip-link" href="#adminMainContent">Skip to admin content</a>
<div class="admin-shell">
    <aside class="admin-side-nav" id="adminSideNav" aria-label="Admin navigation">
        <button class="admin-side-nav-close" type="button" id="adminSidebarClose" aria-label="Close navigation">
            <i data-feather="x" aria-hidden="true"></i>
        </button>
        <a class="loot-brand mb-2" href="{{ route('admin.home') }}">
            @if(brand_logo())
                <img src="{{ Storage::url(brand_logo()) }}" alt="{{ brand_name() }}" style="max-width: 210px; max-height: 48px;">
            @else
                <span class="loot-brand-mark">{{ brand_mark() }}</span>{{ brand_name() }}
            @endif
        </a>

        @php $staff = auth()->user(); @endphp
        <div class="admin-nav-group">
            @if($staff->canAccessSection('dashboard'))
                <a class="admin-nav-link {{ Route::is('admin.home') ? 'active' : '' }}" href="{{ route('admin.home') }}" @if(Route::is('admin.home')) aria-current="page" @endif>
                    <i data-feather="home"></i><span>Dashboard</span>
                </a>
                <a class="admin-nav-link {{ Route::is('admin.analytics') ? 'active' : '' }}" href="{{ route('admin.analytics') }}">
                    <i data-feather="bar-chart-2"></i><span>Analytics</span>
                </a>
                <a class="admin-nav-link {{ Route::is('admin.activity') ? 'active' : '' }}" href="{{ route('admin.activity') }}">
                    <i data-feather="activity"></i><span>Activity</span>
                </a>
                <a class="admin-nav-link {{ Route::is('admin.referrals') ? 'active' : '' }}" href="{{ route('admin.referrals') }}">
                    <i data-feather="share-2"></i><span>Referrals</span>
                </a>
            @endif
            @if($staff->canAccessSection('leads'))
                <a class="admin-nav-link {{ Route::is('admin.logs') ? 'active' : '' }}" href="{{ route('admin.logs') }}">
                    <i data-feather="archive"></i><span>Logs</span>
                </a>
            @endif
            @if($staff->canAccessSection('tickets'))
                <a class="admin-nav-link {{ Route::is('admin.tickets*') ? 'active' : '' }}" href="{{ route('admin.tickets') }}">
                    <i data-feather="inbox"></i><span>Tickets</span>
                    <span class="badge rounded-pill bg-danger">{{ \App\Models\SupportTicket::whereIn('status', ['open', 'pending'])->count() }}</span>
                </a>
            @endif
            @if($staff->canAccessSection('users'))
                <a class="admin-nav-link {{ Route::is('admin.users*') ? 'active' : '' }}" href="{{ route('admin.users') }}">
                    <i data-feather="users"></i><span>Users</span>
                </a>
            @endif
            @if($staff->canAccessSection('leads'))
                <a class="admin-nav-link {{ Route::is('admin.leads') ? 'active' : '' }}" href="{{ route('admin.leads') }}">
                    <i data-feather="send"></i><span>Leads</span>
                </a>
            @endif
        </div>

        @if($staff->canAccessSection('cashouts') || $staff->canAccessSection('users'))
            <div class="admin-nav-group">
                <span class="admin-nav-title">Cashouts</span>
                @if($staff->canAccessSection('cashouts'))
                    <a class="admin-nav-link {{ Route::is('admin.withdrawals') ? 'active' : '' }}" href="{{ route('admin.withdrawals') }}">
                        <i data-feather="upload"></i><span>Cashouts</span>
                    </a>
                @endif
                @if($staff->canAccessSection('users'))
                    <a class="admin-nav-link {{ Route::is('admin.face-verifications*') ? 'active' : '' }}" href="{{ route('admin.face-verifications') }}">
                        <i data-feather="camera"></i><span>Face checks</span>
                    </a>
                @endif
                @if($staff->canAccessSection('cashouts'))
                    <a class="admin-nav-link {{ Route::is('admin.payments*') ? 'active' : '' }}" href="{{ route('admin.payments') }}">
                        <i data-feather="credit-card"></i><span>Payment providers</span>
                    </a>
                @endif
            </div>
        @endif

        @if($staff->canAccessSection('offers'))
            <div class="admin-nav-group">
                <span class="admin-nav-title">Offers</span>
                <a class="admin-nav-link {{ Route::is('admin.provider-offers*') ? 'active' : '' }}" href="{{ route('admin.provider-offers') }}">
                    <i data-feather="target"></i><span>Offers</span>
                </a>
                <a class="admin-nav-link {{ Route::is('admin.offerwalls') ? 'active' : '' }}" href="{{ route('admin.offerwalls') }}">
                    <i data-feather="star"></i><span>Providers</span>
                </a>
                <a class="admin-nav-link {{ Route::is('admin.campaigns*') ? 'active' : '' }}" href="{{ route('admin.campaigns') }}">
                    <i data-feather="layers"></i><span>Campaigns</span>
                </a>
            </div>
        @endif

        @if($staff->canAccessSection('dashboard') || $staff->canAccessSection('bonuses') || $staff->canAccessSection('settings'))
            <div class="admin-nav-group">
                <span class="admin-nav-title">Rewards</span>
                @if($staff->canAccessSection('dashboard'))
                    <a class="admin-nav-link {{ Route::is('admin.leaderboard') ? 'active' : '' }}" href="{{ route('admin.leaderboard') }}">
                        <i data-feather="bar-chart-2"></i><span>Leaderboard</span>
                    </a>
                @endif
                @if($staff->canAccessSection('bonuses'))
                    <a class="admin-nav-link {{ Route::is('admin.bonus') ? 'active' : '' }}" href="{{ route('admin.bonus') }}">
                        <i data-feather="gift"></i><span>Bonuses</span>
                    </a>
                    <a class="admin-nav-link {{ Route::is('admin.bonus-history') ? 'active' : '' }}" href="{{ route('admin.bonus-history') }}">
                        <i data-feather="award"></i><span>Bonus History</span>
                    </a>
                @endif
                @if($staff->canAccessSection('settings'))
                    <a class="admin-nav-link {{ Route::is('admin.settings') ? 'active' : '' }}" href="{{ route('admin.settings') }}">
                        <i data-feather="settings"></i><span>Settings</span>
                    </a>
                @endif
            </div>
        @endif
    </aside>
    <div class="admin-sidebar-overlay" id="adminSidebarOverlay"></div>

    <header class="admin-topbar">
        <div class="admin-topbar-main">
            <button class="admin-menu-toggle" type="button" id="adminSidebarToggle" aria-label="Open admin navigation" aria-controls="adminSideNav" aria-expanded="false">
                <i data-feather="menu"></i>
            </button>
            <div class="admin-topbar-title">
                <strong>@yield('title', 'Admin')</strong>
                <span>{{ request()->path() }}</span>
            </div>
        </div>
        <div class="admin-topbar-actions">
            @include('partials.portal-theme-toggle')
            <a class="btn btn-loot" href="{{ route('user.home') }}">
                <i data-feather="monitor" class="me-50"></i>User view
            </a>
            @include('partials.notification-bell', ['bellScope' => 'admin'])
            <div class="dropdown">
                <button class="nav-link dropdown-toggle dropdown-user-link border-0 bg-transparent" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Open admin account menu">
                    <img class="rounded-circle" src="{{ auth()->user()->avatar() }}" alt="{{ auth()->user()->username }}"
                         width="42" height="42">
                </button>
                <div class="dropdown-menu dropdown-menu-end">
                    <a class="dropdown-item" href="{{ route('user.history') }}">
                        <i class="me-50" data-feather="settings"></i> Settings
                    </a>
                    <a class="dropdown-item" href="{{ route('logout') }}"
                       onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                        <i class="me-50" data-feather="power"></i> Logout
                    </a>
                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">@csrf</form>
                </div>
            </div>
        </div>
    </header>

    <main class="admin-content" id="adminMainContent" tabindex="-1">
        @yield('content')
    </main>
</div>

@if(site_bool('ai_assistant_enabled', false))
    @include('admin.partials.ai-assistant')
@endif

<script src="{{ asset('app-assets/vendors/js/vendors.min.js') }}"></script>
<script src="{{ asset('app-assets/vendors/js/extensions/toastr.min.js') }}"></script>
<script src="{{ asset('app-assets/vendors/js/tables/datatable/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('app-assets/vendors/js/tables/datatable/datatables.buttons.min.js') }}"></script>
<script src="{{ asset('app-assets/vendors/js/feather-icons/feather-icons.min.js') }}"></script>
<script src="{{ asset('assets/js/basketloot-icons.js') }}"></script>
<script src="{{ asset('assets/js/basketloot-reactive.js') }}" data-turbo-eval="false" data-turbolinks-eval="false"></script>
<script data-turbo-eval="false" data-turbolinks-eval="false">
    window.livewire = new Livewire();
    window.Livewire = window.livewire;
    window.livewire_app_url = '';
    window.livewire_token = @json(csrf_token());
    window.deferLoadingAlpine = function (callback) {
        window.addEventListener('livewire:load', callback);
    };

    let basketLootLivewireStarted = false;
    function startBasketLootLivewire() {
        if (!basketLootLivewireStarted) {
            window.livewire.start();
            basketLootLivewireStarted = true;
        }
    }

    window.addEventListener('alpine:initializing', startBasketLootLivewire);
    document.addEventListener('DOMContentLoaded', startBasketLootLivewire);
</script>
@stack('scripts')
<script>
    $(window).on('load', function () {
        if (window.BasketLootIcons) {
            window.BasketLootIcons.refresh();
        }
    });

    $.ajaxSetup({
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
    });

    // Explicitly initialize the two shell dropdowns. This keeps them working
    // after Livewire updates and avoids relying only on Bootstrap's data scan.
    if (window.bootstrap && window.bootstrap.Dropdown) {
        document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(function (toggle) {
            window.bootstrap.Dropdown.getOrCreateInstance(toggle);
        });
    }

    (function () {
        var body = document.body;
        var toggle = document.getElementById('adminSidebarToggle');
        var close = document.getElementById('adminSidebarClose');
        var overlay = document.getElementById('adminSidebarOverlay');
        var collapsedKey = 'basketloot_admin_sidebar_collapsed';

        if (window.innerWidth >= 992 && localStorage.getItem(collapsedKey) === '1') {
            body.classList.add('admin-sidebar-collapsed');
        }

        function closeMobileMenu() {
            body.classList.remove('admin-sidebar-open');
            if (toggle) {
                toggle.setAttribute('aria-expanded', 'false');
                toggle.setAttribute('aria-label', 'Open admin navigation');
            }
        }

        if (toggle) {
            toggle.addEventListener('click', function () {
                if (window.innerWidth < 992) {
                    var open = body.classList.toggle('admin-sidebar-open');
                    toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
                    toggle.setAttribute('aria-label', open ? 'Close admin navigation' : 'Open admin navigation');
                    return;
                }

                body.classList.toggle('admin-sidebar-collapsed');
                localStorage.setItem(collapsedKey, body.classList.contains('admin-sidebar-collapsed') ? '1' : '0');
            });
        }

        if (overlay) {
            overlay.addEventListener('click', closeMobileMenu);
        }

        if (close) {
            close.addEventListener('click', function () {
                closeMobileMenu();
                if (toggle) toggle.focus();
            });
        }

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape' && body.classList.contains('admin-sidebar-open')) {
                closeMobileMenu();
                if (toggle) toggle.focus();
            }
        });

        window.addEventListener('resize', function () {
            if (window.innerWidth >= 992) {
                closeMobileMenu();
            }
        });
    })();

    (function () {
        function items(group) {
            return Array.from(document.querySelectorAll('[data-bulk-item="' + group + '"]'));
        }

        function refresh(group) {
            var checkboxes = items(group);
            var selected = checkboxes.filter(function (checkbox) { return checkbox.checked; }).length;
            document.querySelectorAll('[data-bulk-count="' + group + '"]').forEach(function (node) {
                node.textContent = selected + ' selected';
            });
            document.querySelectorAll('[data-bulk-submit="' + group + '"]').forEach(function (button) {
                button.disabled = selected === 0;
            });
            document.querySelectorAll('[data-bulk-select-all="' + group + '"]').forEach(function (toggle) {
                toggle.checked = checkboxes.length > 0 && selected === checkboxes.length;
                toggle.indeterminate = selected > 0 && selected < checkboxes.length;
            });
        }

        document.addEventListener('change', function (event) {
            var selectGroup = event.target.getAttribute('data-bulk-select-all');
            var itemGroup = event.target.getAttribute('data-bulk-item');
            if (selectGroup) {
                items(selectGroup).forEach(function (checkbox) { checkbox.checked = event.target.checked; });
                refresh(selectGroup);
            } else if (itemGroup) {
                refresh(itemGroup);
            }
        });

        document.querySelectorAll('[data-bulk-form]').forEach(function (form) {
            var group = form.getAttribute('data-bulk-form');
            form.addEventListener('submit', function (event) {
                var selected = items(group).filter(function (checkbox) { return checkbox.checked; }).length;
                if (!selected) {
                    event.preventDefault();
                    return;
                }

                var action = form.querySelector('[name="action"]');
                if (action && ['delete', 'reject', 'end'].includes(action.value) && !window.confirm('Apply this action to ' + selected + ' selected record(s)?')) {
                    event.preventDefault();
                }
            });
            refresh(group);
        });

        // CSV export: exports the selected rows, or the current filtered view
        // when nothing is selected. The button carries data-bulk-export="group"
        // and data-export-url="/admin/.../export" (with any filter query string).
        document.querySelectorAll('[data-bulk-export]').forEach(function (button) {
            button.addEventListener('click', function () {
                var group = button.getAttribute('data-bulk-export');
                var url = button.getAttribute('data-export-url');
                var ids = items(group).filter(function (c) { return c.checked; }).map(function (c) { return c.value; });
                var target = new URL(url, window.location.origin);
                if (ids.length) {
                    target.searchParams.set('ids', ids.join(','));
                }
                window.location.href = target.toString();
            });
        });
    })();
</script>
</body>
</html>
