<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ config('app.name', 'ApprovalDesk') }}</title>

    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">

    <style>
        body { font-family: 'Figtree', sans-serif; background-color: #f8f9fa; }
        #sidebar { width: 250px; min-height: 100vh; transition: width 0.3s ease; overflow: hidden; flex-shrink: 0; }
        #sidebar.collapsed { width: 60px; }
        #sidebar.collapsed .sidebar-label { display: none !important; }
        #sidebar .nav-link { border-radius: 8px; padding: 9px 14px; color: rgba(255,255,255,.75); white-space: nowrap; }
        #sidebar .nav-link:hover { color: #fff; background: rgba(255,255,255,.1); }
        #sidebar .nav-link.active { color: #fff; background: #0d6efd; }
        #sidebar .nav-link i { width: 20px; text-align: center; flex-shrink: 0; }
        .sidebar-section-label { font-size: .7rem; letter-spacing: .08em; }
        #pageContent { min-width: 0; }
    </style>

    @stack('styles')
</head>
<body>
<div class="d-flex" id="wrapper" style="min-height:100vh">

    <!-- ═══════════ SIDEBAR ═══════════ -->
    <div id="sidebar" class="bg-dark text-white d-flex flex-column">

        <div class="p-3 border-bottom border-secondary d-flex align-items-center justify-content-between">
            <a href="{{ route('dashboard') }}" class="text-decoration-none d-flex align-items-center gap-2">
                <i class="bi bi-check2-square text-primary fs-5 flex-shrink-0"></i>
                <span class="sidebar-label fw-bold fs-6 text-white">ApprovalDesk</span>
            </a>
            <button id="sidebarToggle" class="btn btn-sm btn-outline-light border-0 p-1 flex-shrink-0" title="Toggle sidebar">
                <i class="bi bi-list fs-5"></i>
            </button>
        </div>

        <nav class="nav flex-column p-2 flex-grow-1 gap-1">
            <a href="{{ route('dashboard') }}"
               class="nav-link d-flex align-items-center gap-2 {{ request()->routeIs('dashboard') ? 'active' : '' }}">
                <i class="bi bi-speedometer2"></i>
                <span class="sidebar-label">Dashboard</span>
            </a>

            <a href="{{ route('tokens.index') }}"
               class="nav-link d-flex align-items-center gap-2 {{ request()->routeIs('tokens.*') ? 'active' : '' }}">
                <i class="bi bi-ticket-detailed"></i>
                <span class="sidebar-label">My Tokens</span>
            </a>

            @auth
                @if (!auth()->user()->isAdmin())
                    <a href="{{ route('tokens.index', ['filter' => 'pending-approval']) }}"
                       class="nav-link d-flex align-items-center gap-2">
                        <i class="bi bi-clock-history"></i>
                        <span class="sidebar-label">Pending Approval</span>
                    </a>
                @endif

                @if (auth()->user()->isAdmin())
                    <hr class="border-secondary my-1">
                    <div class="px-2 mb-1">
                        <span class="sidebar-label sidebar-section-label text-secondary text-uppercase fw-semibold">Admin</span>
                    </div>
                    <a href="{{ route('admin.departments.index') }}"
                       class="nav-link d-flex align-items-center gap-2 {{ request()->routeIs('admin.departments.*') ? 'active' : '' }}">
                        <i class="bi bi-building"></i>
                        <span class="sidebar-label">Departments</span>
                    </a>
                    <a href="{{ route('admin.categories.index') }}"
                       class="nav-link d-flex align-items-center gap-2 {{ request()->routeIs('admin.categories.*') ? 'active' : '' }}">
                        <i class="bi bi-tags"></i>
                        <span class="sidebar-label">Categories</span>
                    </a>
                    <a href="{{ route('admin.users.index') }}"
                       class="nav-link d-flex align-items-center gap-2 {{ request()->routeIs('admin.users.*') ? 'active' : '' }}">
                        <i class="bi bi-people"></i>
                        <span class="sidebar-label">Users</span>
                    </a>
                @endif
            @endauth

            <a href="{{ route('notifications.index') }}"
               class="nav-link d-flex align-items-center gap-2 {{ request()->routeIs('notifications.*') ? 'active' : '' }}">
                <i class="bi bi-bell"></i>
                <span class="sidebar-label">Notifications</span>
            </a>
        </nav>

        <!-- User Dropup -->
        <div class="p-2 border-top border-secondary">
            <div class="dropup">
                <button type="button"
                        class="btn btn-dark w-100 d-flex align-items-center gap-2 text-start border-0 rounded-2 p-2"
                        data-bs-toggle="dropdown" aria-expanded="false">
                    <div class="rounded-circle bg-primary d-flex align-items-center justify-content-center text-white fw-bold flex-shrink-0"
                         style="width:32px;height:32px;font-size:13px">
                        {{ strtoupper(substr(auth()->user()->name ?? 'U', 0, 1)) }}
                    </div>
                    <div class="sidebar-label flex-grow-1 overflow-hidden">
                        <div class="text-white fw-medium text-truncate" style="font-size:.875rem;line-height:1.3">
                            {{ auth()->user()->name ?? 'User' }}
                        </div>
                        <div class="text-secondary text-truncate" style="font-size:.75rem">
                            {{ auth()->user()->designation ?? 'Staff' }}
                        </div>
                    </div>
                    <i class="bi bi-three-dots-vertical sidebar-label text-secondary flex-shrink-0"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-dark w-100 mb-1">
                    <li>
                        <div class="dropdown-header">
                            <div class="fw-semibold">{{ auth()->user()->name ?? 'User' }}</div>
                            <small class="text-muted">{{ auth()->user()->email ?? '' }}</small>
                        </div>
                    </li>
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <button type="button" class="dropdown-item d-flex align-items-center gap-2"
                                data-bs-toggle="modal" data-bs-target="#editProfileModal">
                            <i class="bi bi-person-gear"></i> Edit Profile
                        </button>
                    </li>
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <form method="POST" action="{{ route('logout') }}">
                            @csrf
                            <button type="submit" class="dropdown-item d-flex align-items-center gap-2 text-danger">
                                <i class="bi bi-box-arrow-right"></i> Logout
                            </button>
                        </form>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- ════════════════════════════════ -->

    <!-- Page Content -->
    <div class="d-flex flex-column flex-grow-1" id="pageContent" style="min-width:0">

        <!-- Topbar -->
        <nav class="navbar navbar-light bg-white border-bottom px-3 sticky-top" style="z-index:100">
            <button class="btn btn-sm btn-outline-secondary d-md-none me-2" id="mobileSidebarToggle">
                <i class="bi bi-list"></i>
            </button>
            <span class="navbar-brand fw-semibold mb-0 h6 me-auto">{{ config('app.name', 'ApprovalDesk') }}</span>

            <div class="d-flex align-items-center gap-2">
                @php $unreadCount = auth()->user()->notifications()->whereNull('read_at')->count(); @endphp
                <a href="{{ route('notifications.index') }}" class="btn btn-outline-secondary btn-sm position-relative">
                    <i class="bi bi-bell"></i>
                    @if ($unreadCount > 0)
                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"
                              style="font-size:.6rem">
                            {{ $unreadCount > 9 ? '9+' : $unreadCount }}
                        </span>
                    @endif
                </a>

                <div class="dropdown">
                    <button class="btn btn-outline-secondary btn-sm dropdown-toggle d-flex align-items-center gap-2"
                            data-bs-toggle="dropdown" aria-expanded="false">
                        <div class="rounded-circle bg-primary d-flex align-items-center justify-content-center text-white fw-bold"
                             style="width:26px;height:26px;font-size:11px">
                            {{ strtoupper(substr(auth()->user()->name ?? 'U', 0, 1)) }}
                        </div>
                        <span class="d-none d-sm-inline" style="font-size:.875rem">{{ auth()->user()->name ?? 'User' }}</span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                        <li>
                            <div class="dropdown-header">
                                <div class="fw-semibold">{{ auth()->user()->name }}</div>
                                <small class="text-muted">{{ auth()->user()->email }}</small>
                            </div>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <button type="button" class="dropdown-item d-flex align-items-center gap-2"
                                    data-bs-toggle="modal" data-bs-target="#editProfileModal">
                                <i class="bi bi-person-gear text-muted"></i> Edit Profile
                            </button>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <form method="POST" action="{{ route('logout') }}">
                                @csrf
                                <button type="submit" class="dropdown-item d-flex align-items-center gap-2 text-danger">
                                    <i class="bi bi-box-arrow-right"></i> Logout
                                </button>
                            </form>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <!-- Toast Container -->
        <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index:9999">
            @foreach(['success' => 'success', 'error' => 'danger', 'warning' => 'warning', 'info' => 'info'] as $type => $bg)
                @if(session($type))
                    <div class="toast align-items-center text-white bg-{{ $bg }} border-0" role="alert" aria-live="assertive">
                        <div class="d-flex">
                            <div class="toast-body fw-medium">
                                <i class="bi bi-{{ $type === 'success' ? 'check-circle' : ($type === 'error' ? 'x-circle' : ($type === 'warning' ? 'exclamation-triangle' : 'info-circle')) }} me-2"></i>
                                {{ session($type) }}
                            </div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                        </div>
                    </div>
                @endif
            @endforeach
        </div>

        <!-- Main Content -->
        <main class="flex-grow-1 p-4">
            {{ $slot }}
        </main>
    </div>
</div>

<!-- ═══════════ Edit Profile Modal ═══════════ -->
<div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content shadow">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-semibold" id="editProfileModalLabel">
                    <i class="bi bi-person-gear me-2 text-primary"></i>Edit Profile
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body px-4 pb-4">
                <form method="POST" action="{{ route('profile.update') }}">
                    @csrf
                    @method('PATCH')
                    <div class="mb-3">
                        <label for="profile_name" class="form-label fw-medium">Full Name</label>
                        <input type="text" id="profile_name" name="name"
                               value="{{ old('name', auth()->user()->name) }}"
                               class="form-control @error('name') is-invalid @enderror" required>
                        @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="mb-3">
                        <label for="profile_email" class="form-label fw-medium">Email Address</label>
                        <input type="email" id="profile_email" name="email"
                               value="{{ old('email', auth()->user()->email) }}"
                               class="form-control @error('email') is-invalid @enderror" required>
                        @error('email')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="d-flex justify-content-end">
                        <button type="submit" class="btn btn-primary btn-sm px-4">
                            <i class="bi bi-check-lg me-1"></i>Save Changes
                        </button>
                    </div>
                </form>

                <hr class="my-4">
                <p class="fw-semibold mb-3" style="font-size:.875rem">Change Password</p>

                <form method="POST" action="{{ route('password.update') }}">
                    @csrf
                    @method('PUT')
                    <div class="mb-3">
                        <label for="current_password" class="form-label" style="font-size:.8125rem">Current Password</label>
                        <input type="password" id="current_password" name="current_password"
                               class="form-control form-control-sm @error('current_password', 'updatePassword') is-invalid @enderror"
                               autocomplete="current-password">
                        @error('current_password', 'updatePassword')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="row gx-3 mb-3">
                        <div class="col">
                            <label class="form-label" style="font-size:.8125rem">New Password</label>
                            <input type="password" name="password"
                                   class="form-control form-control-sm @error('password', 'updatePassword') is-invalid @enderror"
                                   autocomplete="new-password">
                            @error('password', 'updatePassword')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col">
                            <label class="form-label" style="font-size:.8125rem">Confirm</label>
                            <input type="password" name="password_confirmation" class="form-control form-control-sm" autocomplete="new-password">
                        </div>
                    </div>
                    <div class="d-flex justify-content-end">
                        <button type="submit" class="btn btn-outline-secondary btn-sm px-4">
                            <i class="bi bi-shield-lock me-1"></i>Update Password
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    // ── Sidebar toggle ───────────────────────────────────
    const sidebar = document.getElementById('sidebar');

    function setSidebar(collapsed) {
        sidebar.classList.toggle('collapsed', collapsed);
        localStorage.setItem('sidebarCollapsed', collapsed ? '1' : '0');
    }

    document.getElementById('sidebarToggle')?.addEventListener('click', () => {
        setSidebar(!sidebar.classList.contains('collapsed'));
    });
    document.getElementById('mobileSidebarToggle')?.addEventListener('click', () => {
        setSidebar(!sidebar.classList.contains('collapsed'));
    });

    // Restore on load
    if (localStorage.getItem('sidebarCollapsed') === '1') {
        sidebar.classList.add('collapsed');
    }

    // ── Toast auto-dismiss ───────────────────────────────
    document.querySelectorAll('.toast').forEach(el => {
        bootstrap.Toast.getOrCreateInstance(el, { autohide: true, delay: 4000 }).show();
    });

    // ── Re-open profile modal on validation error ────────
    @if ($errors->has('name') || $errors->has('email') || $errors->updatePassword->isNotEmpty())
        document.addEventListener('DOMContentLoaded', () => {
            bootstrap.Modal.getOrCreateInstance(document.getElementById('editProfileModal')).show();
        });
    @endif
</script>

@stack('scripts')
</body>
</html>