<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>@yield('title', 'Dashboard Siswa')</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Poppins', sans-serif; background-color: #f5f9ff; margin: 0; height: 100vh; overflow: hidden; }
        .siswa-wrapper { display: flex; height: 100vh; overflow: hidden; }

        .icon-sm   { width: 16px; height: 16px; object-fit: contain; vertical-align: middle; }
        .icon-md   { width: 24px; height: 24px; object-fit: contain; vertical-align: middle; }
        .icon-rank { width: 28px; height: 28px; object-fit: contain; vertical-align: middle; }
        .icon-mascot { width: 300px; max-width: 100%; height: auto; object-fit: contain; margin-top: 28px; }

        /* ── SIDEBAR ── */
        .sidebar {
            width: 260px; flex-shrink: 0;
            background: #ffffff; border-right: 2px solid #e6f0ff;
            padding: 0;
            display: flex; flex-direction: column;
            height: 100vh;
            height: 100dvh;
            position: fixed; top: 0; left: 0;
            z-index: 1050;
            overflow: hidden;
            /* selalu tersembunyi by default di semua ukuran layar */
            transform: translateX(-260px);
            transition: transform 0.3s ease;
        }
        /* tampil saat .open ditambahkan via JS */
        .sidebar.open {
            transform: translateX(0);
            box-shadow: 4px 0 24px rgba(0,0,0,0.15);
        }

        /* Logo */
        .sidebar-logo {
            text-align: center;
            padding: 30px 20px 16px;
            white-space: nowrap;
            flex-shrink: 0;
        }
        .sidebar-logo img { width: 90px; }
        @media (max-width: 768px) {
            .sidebar-logo { padding: 20px 20px 10px; }
            .sidebar-logo img { width: 72px; }
        }

        /* Nav — flex:1 + scroll */
        .sidebar-menu {
            flex: 1;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
            padding: 0 20px 8px;
            white-space: nowrap;
        }
        .sidebar-menu::-webkit-scrollbar { width: 4px; }
        .sidebar-menu::-webkit-scrollbar-track { background: transparent; }
        .sidebar-menu::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 99px; }

        .sidebar-link {
            display: flex; align-items: center; gap: 12px;
            padding: 11px 18px; margin-bottom: 8px;
            border-radius: 12px; color: #64748b;
            text-decoration: none; font-weight: 500; font-size: 14px;
            transition: all 0.2s ease;
        }
        .sidebar-link:hover { background: #e6f0ff; color: #1d4ed8; }
        .sidebar-link.active { background: #e6f0ff; color: #1d4ed8; }
        .sidebar-icon { width: 20px; height: 20px; flex-shrink: 0; object-fit: contain; }

        /* Logout — selalu di bawah */
        .sidebar-logout {
            flex-shrink: 0;
            padding: 12px 20px 24px;
            border-top: 1px solid #f1f5f9;
            background: #ffffff;
        }
        .sidebar-logout button {
            width: 100%; border: none; background: transparent;
            color: #ef4444; font-weight: 600; font-size: 14px;
            padding: 10px 18px; text-align: left; border-radius: 12px;
            cursor: pointer; display: flex; align-items: center; gap: 12px;
            transition: background 0.2s; font-family: 'Poppins', sans-serif; white-space: nowrap;
        }
        .sidebar-logout button:hover { background: #fef2f2; }
        .sidebar-logout svg { width: 18px; height: 18px; flex-shrink: 0; }

        /* ── OVERLAY ── */
        .sidebar-overlay {
            display: none;
            position: fixed; inset: 0;
            background: rgba(15,31,61,0.4);
            z-index: 1040; backdrop-filter: blur(2px);
        }
        .sidebar-overlay.show { display: block; }

        /* ── TOGGLE ── */
        .sidebar-toggle-btn {
            position: fixed; top: 50%; transform: translateY(-50%);
            left: 0;
            z-index: 1060;
            width: 22px; height: 48px;
            background: #2b8ef3; border: none;
            border-radius: 0 10px 10px 0; cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            transition: left 0.3s ease, background 0.2s;
            box-shadow: 2px 0 8px rgba(43,142,243,0.3);
        }
        .sidebar-toggle-btn:hover { background: #1a7ae0; }
        /* toggle posisi via JS: style.left langsung */

        @media (max-width: 768px) {
            .sidebar-toggle-btn { top: 20px; transform: none; border-radius: 0 8px 8px 0; height: 40px; width: 28px; }
        }

        .toggle-arrow {
            width: 12px; height: 12px;
            fill: none; stroke: white; stroke-width: 2.5;
            stroke-linecap: round; stroke-linejoin: round;
            transition: transform 0.3s ease;
        }
        /* default: panah kanan (sidebar tutup) */
        .toggle-arrow { transform: rotate(180deg); }

        /* ── MAIN ── */
        .main {
            flex: 1; display: flex; flex-direction: column;
            min-width: 0; height: 100vh; overflow: hidden;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }

        /* ── TOPBAR ── */
        .topbar {
            background: #2b8ef3;
            margin: 12px 12px 0; padding: 12px 16px;
            border-radius: 16px; color: white;
            display: flex; justify-content: space-between; align-items: center;
            box-shadow: 0 8px 24px rgba(43,142,243,0.25); flex-shrink: 0;
        }
        @media (min-width: 769px) { .topbar { margin: 20px 20px 0; padding: 16px 24px; } }
        .topbar-left { font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 8px; padding-left: 32px; }
        @media (min-width: 769px) { .topbar-left { font-size: 16px; padding-left: 0; } }
        .topbar-right { display: flex; align-items: center; gap: 10px; }

        /* ── CONTENT ── */
        .content { padding: 14px 14px 20px; flex: 1; overflow-y: auto; }
        @media (min-width: 769px) { .content { padding: 28px 28px 28px; } }

        /* NOTIF */
        .notif-wrap { position: relative; }
        .notif-btn { width: 34px; height: 34px; border-radius: 50%; background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.4); display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background 0.2s; flex-shrink: 0; }
        .notif-btn:hover { background: rgba(255,255,255,0.35); }
        .notif-btn svg { width: 16px; height: 16px; stroke: white; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
        .notif-badge { position: absolute; top: -4px; right: -4px; min-width: 18px; height: 18px; background: #ef4444; border: 2px solid #2b8ef3; border-radius: 99px; font-size: 10px; font-weight: 700; color: white; display: none; align-items: center; justify-content: center; padding: 0 4px; line-height: 1; }

        .notif-dropdown {
            position: fixed;
            top: auto; right: 12px;
            width: calc(100vw - 24px);
            max-width: 340px;
            background: white; border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.15), 0 0 0 1px rgba(0,0,0,0.05);
            z-index: 9998; opacity: 0; pointer-events: none;
            transform: translateY(-8px) scale(0.97);
            transition: all 0.2s cubic-bezier(0.34,1.56,0.64,1);
            overflow: hidden;
        }
        @media (min-width: 769px) {
            .notif-dropdown { position: absolute; top: calc(100% + 12px); right: 0; width: 340px; }
        }
        .notif-dropdown.show { opacity: 1; pointer-events: all; transform: translateY(0) scale(1); }
        .notif-head { padding: 14px 16px 10px; border-bottom: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; }
        .notif-head-title { font-size: 14px; font-weight: 700; color: #0f1f3d; }
        .notif-head-count { font-size: 11px; color: #94a3b8; }
        .notif-list { max-height: 300px; overflow-y: auto; }
        .notif-item { display: flex; align-items: flex-start; gap: 12px; padding: 12px 16px; border-bottom: 1px solid #f8fafc; transition: background 0.15s; cursor: default; }
        .notif-item:hover { background: #f8faff; }
        .notif-item:last-child { border-bottom: none; }
        .notif-icon-wrap { width: 36px; height: 36px; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        .notif-icon-materi   { background: #e8f4ff; }
        .notif-icon-tugas    { background: #fff7e6; }
        .notif-icon-challenge { background: #f3e8ff; }
        .notif-body { flex: 1; min-width: 0; }
        .notif-title   { font-size: 12px; font-weight: 700; color: #0f1f3d; margin-bottom: 2px; }
        .notif-message { font-size: 12px; color: #475569; margin-bottom: 2px; line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .notif-time    { font-size: 10px; color: #94a3b8; white-space: nowrap; margin-top: 2px; }
        .notif-empty { padding: 28px 16px; text-align: center; }
        .notif-empty-icon { margin-bottom: 8px; display: flex; justify-content: center; }
        .notif-empty-text { font-size: 13px; color: #94a3b8; }

        .topbar-avatar { width: 34px; height: 34px; border-radius: 50%; object-fit: cover; border: 2px solid rgba(255,255,255,0.5); cursor: pointer; transition: all 0.2s; display: block; }
        .topbar-avatar:hover { border-color: white; transform: scale(1.05); }
        .topbar-avatar-icon { width: 34px; height: 34px; border-radius: 50%; background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.4); display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background 0.2s; flex-shrink: 0; }
        .topbar-avatar-icon:hover { background: rgba(255,255,255,0.35); }
        .topbar-avatar-icon svg { width: 18px; height: 18px; stroke: white; }

        /* ── PROFILE MODAL ── */
        .profile-modal-overlay { position: fixed; inset: 0; background: rgba(15,31,61,0.45); backdrop-filter: blur(4px); z-index: 9999; display: flex; align-items: flex-end; justify-content: center; opacity: 0; pointer-events: none; transition: opacity 0.25s ease; }
        @media (min-width: 769px) { .profile-modal-overlay { align-items: center; padding: 16px; } }
        .profile-modal-overlay.show { opacity: 1; pointer-events: all; }
        .profile-modal {
            background: white; border-radius: 24px 24px 0 0; width: 100%; max-width: 100%;
            padding: 24px 20px; box-shadow: 0 24px 60px rgba(0,0,0,0.18);
            transform: translateY(40px); transition: transform 0.25s cubic-bezier(0.34,1.56,0.64,1);
            position: relative; max-height: 90vh; overflow-y: auto;
        }
        @media (min-width: 769px) {
            .profile-modal { border-radius: 24px; max-width: 440px; padding: 32px; transform: translateY(20px) scale(0.97); }
            .profile-modal-overlay.show .profile-modal { transform: translateY(0) scale(1); }
        }
        .profile-modal-overlay.show .profile-modal { transform: translateY(0); }
        .modal-close { position: absolute; top: 16px; right: 16px; width: 32px; height: 32px; border-radius: 50%; background: #f1f5f9; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background 0.2s; }
        .modal-close:hover { background: #e2e8f0; }
        .modal-close svg { width: 16px; height: 16px; stroke: #64748b; }
        .modal-title { font-size: 17px; font-weight: 800; color: #0d1b2e; margin-bottom: 4px; }
        .modal-subtitle { font-size: 13px; color: #94a3b8; margin-bottom: 18px; }
        .foto-upload-area { display: flex; align-items: center; gap: 14px; background: #f8fafc; border-radius: 14px; padding: 12px 16px; margin-bottom: 16px; border: 1.5px dashed #e2e8f0; transition: border-color 0.2s; }
        .foto-upload-area:hover { border-color: #2b8ef3; }
        .foto-circle { width: 60px; height: 60px; border-radius: 50%; overflow: hidden; background: #e6f0ff; display: flex; align-items: center; justify-content: center; flex-shrink: 0; border: 3px solid #dbeeff; }
        .foto-circle img { width: 100%; height: 100%; object-fit: cover; }
        .foto-circle svg { width: 30px; height: 30px; stroke: #2b8ef3; }
        .foto-info p { font-size: 12px; color: #94a3b8; margin: 0 0 6px; }
        .btn-pilih-foto { display: inline-block; background: #e6f0ff; color: #2b8ef3; font-size: 12px; font-weight: 700; padding: 6px 14px; border-radius: 8px; cursor: pointer; border: none; transition: background 0.2s; }
        .btn-pilih-foto:hover { background: #dbeeff; }
        .modal-field { margin-bottom: 12px; }
        .modal-label { display: block; font-size: 11px; font-weight: 700; color: #475569; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px; }
        .modal-label span { color: #94a3b8; font-weight: 500; text-transform: none; letter-spacing: 0; font-size: 10px; margin-left: 4px; }
        .modal-input { width: 100%; background: #f8fafc; border: 1.5px solid #e2e8f0; border-radius: 10px; padding: 10px 12px; font-size: 14px; font-family: 'Poppins', sans-serif; color: #1e293b; outline: none; transition: all 0.2s; }
        .modal-input:focus { border-color: #2b8ef3; background: white; box-shadow: 0 0 0 3px rgba(43,142,243,0.1); }
        .modal-input:disabled { background: #f1f5f9; color: #94a3b8; cursor: not-allowed; }
        .modal-divider { border: none; border-top: 1px solid #f1f5f9; margin: 14px 0; }
        .btn-save-modal { width: 100%; background: linear-gradient(135deg,#2b8ef3,#1a7ae0); color: white; border: none; border-radius: 12px; padding: 13px; font-size: 14px; font-weight: 700; font-family: 'Poppins', sans-serif; cursor: pointer; transition: all 0.2s; box-shadow: 0 6px 18px rgba(43,142,243,0.3); }
        .btn-save-modal:hover { transform: translateY(-1px); box-shadow: 0 10px 24px rgba(43,142,243,0.35); }
        .btn-save-modal:disabled { opacity: 0.7; cursor: not-allowed; transform: none; }
        .modal-toast { border-radius: 10px; padding: 10px 14px; font-size: 13px; font-weight: 500; margin-bottom: 12px; display: none; }
        .modal-toast.success { background: #f0fdf4; border: 1.5px solid #86efac; color: #166534; display: block; }
        .modal-toast.error   { background: #fef2f2; border: 1.5px solid #fca5a5; color: #991b1b; display: block; }

        /* ── Badge Koleksi ── */
        .modal-badge-section { margin-top: 20px; }
        .modal-badge-title { font-size: 13px; font-weight: 700; color: #475569; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 12px; display: flex; align-items: center; gap: 6px; }
        .modal-badge-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
        .modal-badge-item { background: #f8fafc; border: 2px solid #e2e8f0; border-radius: 14px; padding: 12px 8px; text-align: center; position: relative; transition: all 0.2s; }
        .modal-badge-item.dimiliki { background: #faf5ff; border-color: #c4b5fd; }
        .modal-badge-item.belum { opacity: 0.45; filter: grayscale(100%); }
        .modal-badge-icon { width: 40px; height: 40px; object-fit: contain; display: block; margin: 0 auto 7px; }
        .modal-badge-nama { font-size: 11px; font-weight: 700; color: #1e293b; line-height: 1.3; margin-bottom: 3px; }
        .modal-badge-desc { font-size: 10px; color: #94a3b8; line-height: 1.3; }
        .modal-badge-lock { position: absolute; top: 7px; right: 7px; width: 13px; height: 13px; color: #94a3b8; }
        .modal-badge-tag { display: inline-block; background: #ede9fe; color: #7c3aed; font-size: 9px; font-weight: 700; padding: 2px 6px; border-radius: 99px; margin-top: 4px; }
        .medal-icon { width: 40px; height: 40px; }

        /* ── Modal Badge Leaderboard ── */
        .lb-badge-modal-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.55); z-index: 99999; align-items: center; justify-content: center; backdrop-filter: blur(3px); padding: 16px; box-sizing: border-box; }
        .lb-badge-modal-overlay.active { display: flex; }
        .lb-badge-modal { background: white; border-radius: 24px; padding: 28px 20px 20px; max-width: 360px; width: 100%; text-align: center; animation: lbPopIn 0.35s cubic-bezier(0.34,1.56,0.64,1); max-height: 90vh; overflow-y: auto; }
        @keyframes lbPopIn { from { transform: scale(0.7); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .lb-badge-modal-label { font-size: 12px; font-weight: 700; color: #7c3aed; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 20px; }
        .lb-badge-modal-list { display: flex; flex-direction: column; gap: 20px; margin-bottom: 24px; }
        .lb-badge-modal-item { display: flex; flex-direction: column; align-items: center; text-align: center; }
        .lb-badge-modal-icon { width: 100%; max-width: 180px; height: auto; object-fit: contain; margin-bottom: 14px; }
        .lb-badge-modal-nama { font-size: 16px; font-weight: 800; color: #1e293b; margin-bottom: 4px; }
        .lb-badge-modal-desc { font-size: 13px; color: #64748b; }
        .lb-badge-modal-btn { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; border-radius: 12px; padding: 12px 32px; font-size: 14px; font-weight: 700; font-family: 'Poppins', sans-serif; cursor: pointer; width: 100%; transition: opacity 0.2s; }
        .lb-badge-modal-btn:hover { opacity: 0.9; }
    </style>
    @stack('styles')
</head>
<body>

<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebarMobile()"></div>

<div class="siswa-wrapper">
    <aside class="sidebar" id="mainSidebar">

        {{-- Logo --}}
        <div class="sidebar-logo">
            <img src="{{ asset('images/logo/logosmk.png') }}" alt="Logo SMK">
        </div>

        {{-- Nav scrollable --}}
        <nav class="sidebar-menu">
            <a href="{{ route('siswa.dashboard') }}" class="sidebar-link {{ request()->routeIs('siswa.dashboard') ? 'active' : '' }}">
                <img src="{{ asset('images/icon/sidebar/home.png') }}" class="sidebar-icon" alt="Dashboard">
                <span>Dashboard</span>
            </a>
            <a href="{{ route('siswa.materi.index') }}" class="sidebar-link {{ request()->routeIs('siswa.materi*') ? 'active' : '' }}">
                <img src="{{ asset('images/icon/sidebar/mapel.png') }}" class="sidebar-icon" alt="Materi">
                <span>Materi</span>
            </a>
            <a href="{{ route('siswa.tugas.index') }}" class="sidebar-link {{ request()->routeIs('siswa.tugas*') ? 'active' : '' }}">
                <img src="{{ asset('images/icon/sidebar/siswa.png') }}" class="sidebar-icon" alt="Tugas">
                <span>Tugas</span>
            </a>
            <a href="{{ route('siswa.challenge.index') }}" class="sidebar-link {{ request()->routeIs('siswa.challenge*') ? 'active' : '' }}">
                <img src="{{ asset('images/icon/sidebar/challenge.png') }}" class="sidebar-icon" alt="Challenge">
                <span>Challenge</span>
            </a>
            <a href="{{ route('siswa.leaderboard.index') }}" class="sidebar-link {{ request()->routeIs('siswa.leaderboard*') ? 'active' : '' }}">
                <img src="{{ asset('images/icon/sidebar/lb.png') }}" class="sidebar-icon" alt="Leaderboard">
                <span>Leaderboard</span>
            </a>
        </nav>

        {{-- Logout — selalu di bawah --}}
        <div class="sidebar-logout">
            <form action="{{ route('siswa.logout') }}" method="POST">
                @csrf
                <button type="submit">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                        <polyline points="16 17 21 12 16 7"/>
                        <line x1="21" y1="12" x2="9" y2="12"/>
                    </svg>
                    Logout
                </button>
            </form>
        </div>

    </aside>

    <button class="sidebar-toggle-btn" id="sidebarToggleBtn" onclick="toggleSidebar()">
        <svg class="toggle-arrow" viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></svg>
    </button>

    <div class="main" id="mainContent">
        <header class="topbar">
            <div class="topbar-left">
                <img src="{{ asset('images/icon/siswadb/wavinghand.png') }}" alt="Hai" class="icon-sm">
                Hai, {{ Auth::guard('siswa')->user()->nama ?? 'Siswa' }}
            </div>
            <div class="topbar-right">
                <div class="notif-wrap" id="notifWrap">
                    <button class="notif-btn" id="notifBtn" onclick="toggleNotif(event)">
                        <svg viewBox="0 0 24 24"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
                    </button>
                    <div class="notif-badge" id="notifBadge"></div>
                    <div class="notif-dropdown" id="notifDropdown">
                        <div class="notif-head">
                            <span class="notif-head-title">Notifikasi</span>
                            <span class="notif-head-count" id="notifCount">7 hari terakhir</span>
                        </div>
                        <div class="notif-list" id="notifList">
                            <div class="notif-empty">
                                <div class="notif-empty-icon">
                                    <img src="{{ asset('images/icon/siswadb/notif.png') }}" alt="Notifikasi" class="icon-md">
                                </div>
                                <div class="notif-empty-text">Memuat notifikasi...</div>
                            </div>
                        </div>
                    </div>
                </div>

                @php $siswa = Auth::guard('siswa')->user(); @endphp
                @if($siswa->foto_profil)
                    <img src="/E31230356/storage/app/public/{{ $siswa->foto_profil }}" 
                    class="topbar-avatar" 
                        id="topbar-foto" 
                        onclick="openProfileModal()" 
                        alt="Foto profil {{ $siswa->nama }}">
                @else
                    <div class="topbar-avatar-icon" id="topbar-foto-icon" onclick="openProfileModal()">
                        <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
                    </div>
                @endif
            </div>
        </header>
        <main class="content">@yield('content')</main>
    </div>
</div>

{{-- PROFILE MODAL --}}
@php
    use App\Models\Badge;
    use App\Models\SiswaBadge;
    $semuaBadgeLayout = Badge::all();
    $idBadgeDimiliki  = SiswaBadge::where('id_siswa', $siswa->id_siswa)->pluck('id_badge')->toArray();
@endphp

<div class="profile-modal-overlay" id="profileModalOverlay" onclick="closeOnOverlay(event)">
    <div class="profile-modal">
        <button class="modal-close" onclick="closeProfileModal()">
            <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
        <div class="modal-title">Edit Profil</div>
        <div class="modal-subtitle">Perbarui foto profil dan password</div>
        <div id="modal-toast" class="modal-toast"></div>
        <form id="profile-form" enctype="multipart/form-data">
            @csrf
            <div class="foto-upload-area">
                <div class="foto-circle">
                    @if($siswa->foto_profil)
    			<img src="/E31230356/storage/app/public/{{ $siswa->foto_profil }}" 
     			    id="modal-foto-preview" 
       			    alt="Foto profil saat ini">
		    @else
                        <svg id="modal-foto-icon" viewBox="0 0 24 24" fill="none" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
                        <img src="" id="modal-foto-preview" alt="Preview foto profil" style="display:none">
                    @endif
                </div>
                <div class="foto-info">
                    <p>JPG, PNG, WEBP · Maks. 2MB</p>
                    <label for="modal-foto-input" class="btn-pilih-foto">Pilih Foto</label>
                    <input type="file" name="foto_profil" id="modal-foto-input" accept="image/*" style="display:none">
                </div>
            </div>
            <div class="modal-field">
                <label class="modal-label">NISN <span>(tidak dapat diubah)</span></label>
                <input type="text" class="modal-input" value="{{ $siswa->nisn }}" disabled>
            </div>
            <div class="modal-field">
                <label class="modal-label">Nama Lengkap <span>(tidak dapat diubah)</span></label>
                <input type="text" class="modal-input" value="{{ $siswa->nama }}" disabled>
            </div>
            <hr class="modal-divider">
            <div class="modal-field">
                <label class="modal-label">Password Baru <span>(kosongkan jika tidak ingin mengubah)</span></label>
                <input type="password" name="password" class="modal-input" placeholder="Password baru" autocomplete="new-password">
            </div>
            <div class="modal-field">
                <label class="modal-label">Konfirmasi Password</label>
                <input type="password" name="password_confirmation" class="modal-input" placeholder="Ulangi password baru" autocomplete="new-password">
            </div>
            <button type="submit" class="btn-save-modal" id="btn-save">Simpan Perubahan</button>
        </form>

        @if($semuaBadgeLayout->isNotEmpty())
        <div class="modal-badge-section">
            <hr class="modal-divider">
            <div class="modal-badge-title">
                <img src="{{ asset('images/icon/gurud/medal-pita.png') }}" class="medal-icon" alt="Medal">
                Badge Koleksiku
            </div>
            <div class="modal-badge-grid">
                @foreach($semuaBadgeLayout as $b)
                @php $dimiliki = in_array($b->id_badge, $idBadgeDimiliki); @endphp
                <div class="modal-badge-item {{ $dimiliki ? 'dimiliki' : 'belum' }}">
                    @if(!$dimiliki)
                        <svg class="modal-badge-lock" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                        </svg>
                    @endif
                    <img src="{{ asset($b->icon_badge) }}" alt="{{ $b->nama_badge }}" class="modal-badge-icon">
                    <div class="modal-badge-nama">{{ $b->nama_badge }}</div>
                    <div class="modal-badge-desc">{{ $b->deskripsi }}</div>
                    @if($dimiliki)
                        <span class="modal-badge-tag">✓ Diraih</span>
                    @endif
                </div>
                @endforeach
            </div>
        </div>
        @endif
    </div>
</div>

{{-- Modal Badge Leaderboard --}}
<div class="lb-badge-modal-overlay" id="lbBadgeModal">
    <div class="lb-badge-modal">
        <div class="lb-badge-modal-label">Badge Baru Diraih! 🎉</div>
        <div id="lbBadgeCounter" style="font-size:12px;color:#94a3b8;margin-bottom:16px"></div>
        <div class="lb-badge-modal-list" id="lbBadgeList"></div>
        <div style="display:flex;gap:10px;margin-top:4px">
            <button class="lb-badge-modal-btn" id="lbBadgePrev" onclick="lbBadgeNav(-1)" style="background:#e2e8f0;color:#475569;display:none">← Sebelumnya</button>
            <button class="lb-badge-modal-btn" id="lbBadgeNext" onclick="lbBadgeNav(1)">Selanjutnya →</button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
@php
    $iconMateri = asset('images/icon/siswadb/buku.png');
    $iconTugas  = asset('images/icon/siswadb/buku.png');
    $iconNotif  = asset('images/icon/siswadb/notif.png');
@endphp
<script>
// ── Sidebar ──
const sidebar    = document.getElementById('mainSidebar');
const toggleBtn  = document.getElementById('sidebarToggleBtn');
const mainContent= document.getElementById('mainContent');
const overlay    = document.getElementById('sidebarOverlay');
const arrow      = toggleBtn.querySelector('.toggle-arrow');
const isMobile   = () => window.innerWidth <= 768;

let sidebarOpen = false;

function setSidebarState(open) {
    sidebarOpen = open;
    if (open) {
        sidebar.classList.add('open');
        toggleBtn.style.left = '260px';
        arrow.style.transform = 'rotate(0deg)';
        if (isMobile()) {
            overlay.classList.add('show');
            document.body.style.overflow = 'hidden';
            mainContent.style.marginLeft = '0';
        } else {
            overlay.classList.remove('show');
            document.body.style.overflow = '';
            mainContent.style.marginLeft = '260px';
        }
    } else {
        sidebar.classList.remove('open');
        toggleBtn.style.left = '0px';
        arrow.style.transform = 'rotate(180deg)';
        overlay.classList.remove('show');
        document.body.style.overflow = '';
        mainContent.style.marginLeft = '0';
    }
}

function toggleSidebar() { setSidebarState(!sidebarOpen); }
function closeSidebarMobile() { setSidebarState(false); }

// Auto close saat klik link menu (navigasi)
document.querySelectorAll('.sidebar-link').forEach(link => {
    link.addEventListener('click', () => { if (sidebarOpen) setSidebarState(false); });
});

// Saat resize, sesuaikan ulang state
window.addEventListener('resize', () => {
    if (sidebarOpen) setSidebarState(true); // re-apply margin sesuai breakpoint
});

// ── Notif ──
const NOTIF_URL        = '{{ route("siswa.notifikasi") }}';
const LB_JSON_URL      = '{{ route("siswa.leaderboard.json") }}';
const LB_BADGE_STORAGE_KEY = 'lb_badge_ids_{{ Auth::guard("siswa")->id() }}';
const LB_BADGE_PENDING_KEY = LB_BADGE_STORAGE_KEY + '_pending';

const notifIcons = {
    materi:    '<img src="{{ $iconMateri }}" alt="Materi" class="icon-md">',
    tugas:     '<img src="{{ $iconTugas }}" alt="Tugas" class="icon-md">',
    challenge: '<img src="{{ asset("images/icon/siswac/piala.png") }}" alt="Challenge" class="icon-md">'
};

async function fetchNotif() {
    try {
        const res  = await fetch(NOTIF_URL, { headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } });
        const data = await res.json();
        const badge = document.getElementById('notifBadge');
        const list  = document.getElementById('notifList');
        const count = document.getElementById('notifCount');
        badge.style.display = data.count > 0 ? 'flex' : 'none';
        if (data.count > 0) badge.textContent = data.count > 99 ? '99+' : data.count;
        count.textContent = `${data.count} notifikasi`;
        list.innerHTML = data.notifications.length === 0
            ? `<div class="notif-empty"><div class="notif-empty-icon"><img src="{{ $iconNotif }}" alt="Kosong" class="icon-md"></div><div class="notif-empty-text">Tidak ada notifikasi baru</div></div>`
            : data.notifications.map(n => `
                <div class="notif-item">
                    <div class="notif-icon-wrap notif-icon-${n.type}">${notifIcons[n.type] ?? '🔔'}</div>
                    <div class="notif-body">
                        <div class="notif-title">${n.title}</div>
                        <div class="notif-message">${n.message}</div>
                        <div class="notif-time">${n.time}</div>
                    </div>
                </div>`).join('');
    } catch(e) {}
}

function toggleNotif(e) {
    e.stopPropagation();
    document.getElementById('notifDropdown').classList.toggle('show');
}
document.addEventListener('click', e => {
    if (!document.getElementById('notifWrap').contains(e.target))
        document.getElementById('notifDropdown').classList.remove('show');
});
fetchNotif();
setInterval(fetchNotif, 30000);

// ── Badge Leaderboard Polling ──
function getSavedBadgeIds() { try { return JSON.parse(localStorage.getItem(LB_BADGE_STORAGE_KEY) || '[]'); } catch(e) { return []; } }
function saveBadgeIds(ids)  { try { localStorage.setItem(LB_BADGE_STORAGE_KEY, JSON.stringify(ids)); } catch(e) {} }
function getPendingBadges() { try { return JSON.parse(localStorage.getItem(LB_BADGE_PENDING_KEY) || '[]'); } catch(e) { return []; } }
function savePendingBadges(b) { try { localStorage.setItem(LB_BADGE_PENDING_KEY, JSON.stringify(b)); } catch(e) {} }
function clearPendingBadges() { try { localStorage.removeItem(LB_BADGE_PENDING_KEY); } catch(e) {} }

let lbBadgeQueue = [], lbBadgeCurrent = 0;

function showLbBadgeModal(badges) {
    lbBadgeQueue = badges; lbBadgeCurrent = 0;
    renderLbBadgeSlide();
    document.getElementById('lbBadgeModal').classList.add('active');
}

function renderLbBadgeSlide() {
    const b = lbBadgeQueue[lbBadgeCurrent];
    const total = lbBadgeQueue.length;
    document.getElementById('lbBadgeCounter').textContent = total > 1 ? `${lbBadgeCurrent + 1} / ${total}` : '';
    document.getElementById('lbBadgeList').innerHTML = `
        <div class="lb-badge-modal-item">
            <img src="${b.icon_url}" alt="${b.nama_badge}" class="lb-badge-modal-icon">
            <div class="lb-badge-modal-nama">${b.nama_badge}</div>
            <div class="lb-badge-modal-desc">${b.deskripsi}</div>
        </div>`;
    document.getElementById('lbBadgePrev').style.display = lbBadgeCurrent === 0 ? 'none' : '';
    document.getElementById('lbBadgeNext').textContent = lbBadgeCurrent === total - 1 ? 'Sip, lanjut! 🚀' : 'Selanjutnya →';
}

function lbBadgeNav(dir) {
    if (dir === 1 && lbBadgeCurrent === lbBadgeQueue.length - 1) {
        document.getElementById('lbBadgeModal').classList.remove('active');
        const pending = getPendingBadges();
        if (pending.length > 0) { saveBadgeIds(pending[0]._confirmedIds); clearPendingBadges(); }
        return;
    }
    lbBadgeCurrent = Math.max(0, Math.min(lbBadgeQueue.length - 1, lbBadgeCurrent + dir));
    renderLbBadgeSlide();
}

async function pollLbBadge() {
    try {
        const res  = await fetch(LB_JSON_URL);
        const data = await res.json();
        const currentBadges = data.badgeSiswa || [];
        const currentIds    = currentBadges.map(b => b.id_badge);
        const savedIds      = getSavedBadgeIds();
        const newBadges     = currentBadges.filter(b => !savedIds.includes(b.id_badge));
        if (newBadges.length > 0) {
            savePendingBadges([{ _confirmedIds: currentIds }]);
            showLbBadgeModal(newBadges);
        } else {
            saveBadgeIds(currentIds);
        }
    } catch(e) {}
}
pollLbBadge();
setInterval(pollLbBadge, 10000);

// ── Profile Modal ──
function openProfileModal()  { document.getElementById('profileModalOverlay').classList.add('show'); document.body.style.overflow = 'hidden'; }
function closeProfileModal() {
    document.getElementById('profileModalOverlay').classList.remove('show');
    document.body.style.overflow = '';
    const t = document.getElementById('modal-toast'); t.className = 'modal-toast'; t.textContent = '';
}
function closeOnOverlay(e)   { if (e.target === document.getElementById('profileModalOverlay')) closeProfileModal(); }
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeProfileModal(); });

document.getElementById('modal-foto-input').addEventListener('change', function() {
    const f = this.files[0]; if (!f) return;
    const p = document.getElementById('modal-foto-preview');
    const i = document.getElementById('modal-foto-icon');
    p.src = URL.createObjectURL(f); p.style.display = 'block';
    if (i) i.style.display = 'none';
});

document.getElementById('profile-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    const btn = document.getElementById('btn-save'), toast = document.getElementById('modal-toast');
    btn.disabled = true; btn.textContent = 'Menyimpan...';
    try {
        const res  = await fetch('{{ route("siswa.profile.update") }}', { method: 'POST', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }, body: new FormData(this) });
        const data = await res.json();
        if (data.success) {
            if (data.foto_url) {
                const tf = document.getElementById('topbar-foto'), ti = document.getElementById('topbar-foto-icon');
                if (tf) { tf.src = data.foto_url + '?t=' + Date.now(); }
                else if (ti) { const img = document.createElement('img'); img.src = data.foto_url + '?t=' + Date.now(); img.className = 'topbar-avatar'; img.id = 'topbar-foto'; img.onclick = openProfileModal; img.alt = 'Foto profil {{ $siswa->nama }}'; ti.replaceWith(img); }
                const mp = document.getElementById('modal-foto-preview'), mi = document.getElementById('modal-foto-icon');
                if (mp) { mp.src = data.foto_url; mp.style.display = 'block'; } if (mi) mi.style.display = 'none';
            }
            toast.className = 'modal-toast success'; toast.textContent = '✓ ' + data.message;
            this.querySelector('[name="password"]').value = '';
            this.querySelector('[name="password_confirmation"]').value = '';
        } else {
            toast.className = 'modal-toast error'; toast.textContent = data.errors ? Object.values(data.errors).flat().join(' · ') : 'Terjadi kesalahan.';
        }
    } catch(err) { toast.className = 'modal-toast error'; toast.textContent = 'Gagal terhubung ke server.'; }
    finally { btn.disabled = false; btn.textContent = 'Simpan Perubahan'; }
});
</script>
@stack('scripts')
</body>
</html>