{% load static i18n %}
{% get_current_language as LANGUAGE_CODE %}

<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}" dir="{% if LANGUAGE_CODE == 'ar' %}rtl{% else %}ltr{% endif %}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="{% trans 'King Abdullah Academic University Hospital - Applicant Tracking System' %}">
    <title>{% block title %}{% trans 'University ATS' %}{% endblock %}</title>

    {% comment %} Load correct Bootstrap CSS file for RTL/LTR {% endcomment %}
    {% if LANGUAGE_CODE == 'ar' %}
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    {% else %}
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    {% endif %}


    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <link rel="stylesheet" href="{% static 'css/main.css' %}">


    {% block customCSS %}{% endblock %}
</head>
<body class="d-flex flex-column min-vh-100" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>

    <div class="top-bar d-none d-md-block">
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center gap-2 max-width-1600">
                <div class="logo-container d-flex gap-2">
                </div>
                <div class="clogo-container d-flex gap-2">
                </div>
                <div class="logo-container d-flex gap-2 align-items-center">
                    <img src="{% static 'image/vision.svg' %}" alt="{% trans 'Saudi Vision 2030' %}" loading="lazy" style="height: 35px; object-fit: contain;">

                    <div class="kaauh-logo-container d-flex flex-column flex-md-row align-items-center gap-2 me-0">
                        <div class="hospital-text text-center text-md-start me-0">
                            <div class="ar text-xs">جامعة الأميرة نورة بنت عبدالرحمن الأكاديمية</div>
                            <div class="ar text-xs">ومستشفى الملك عبدالله بن عبدالرحمن التخصصي</div>
                            <div class="en text-xs">Princess Nourah bint Abdulrahman University</div>
                            <div class="en text-xs">King Abdullah bin Abdulaziz University Hospital</div>
                        </div>
                    </div>
                     <img src="{% static 'image/kaauh.png' %}" alt="KAAUH Logo" style="max-height: 40px; max-width: 40px;">
                </div>
            </div>
        </div>
    </div>

    <nav class="navbar navbar-expand-lg navbar-dark sticky-top">
        <div class="container-fluid max-width-1600">

            {# --- MOBILE BRAND LOGIC: Show small logo on mobile, large on desktop (lg) --- #}
            <a class="navbar-brand text-white d-block d-lg-none" href="{% url 'dashboard' %}" aria-label="Home">
                <img src="{% static 'image/kaauh_green1.png' %}"  alt="{% trans 'kaauh logo green bg' %}" class="navbar-brand-mobile">
            </a>

            <a class="navbar-brand text-white d-none d-lg-block me-4 pe-4" href="{% url 'dashboard' %}" aria-label="Home">
                <img src="{% static 'image/kaauh_green1.png' %}"  alt="{% trans 'kaauh logo green bg' %}" style="width: 60px; height: 60px;">
            </a>

            {# Toggler: order-lg-0 ensures it's before navigation links on desktop, but it stays where it is on mobile #}
            <button class="navbar-toggler order-lg-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="{% trans 'Toggle navigation' %}">
                <span class="navbar-toggler-icon"></span>
            </button>

            {# Language and Profile Controls (Keep outside collapse for mobile access) #}
            <div class="d-flex align-items-center order-lg-3">
                <ul class="navbar-nav flex-row">
                    <li class="nav-item dropdown">
                        <a class="language-toggle-btn dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"
                        data-bs-offset="0, 8" aria-expanded="false" aria-label="{% trans 'Toggle language menu' %}">
                            <i class="fas fa-globe"></i>
                            <span class="d-none d-lg-inline">{{ LANGUAGE_CODE|upper }}</span>
                        </a>
                        <ul class="dropdown-menu {% if LANGUAGE_CODE == 'ar' %}dropdown-menu-start{% else %}dropdown-menu-end{% endif %}" data-bs-popper="static">
                            <li>
                                <form action="{% url 'set_language' %}" method="post" class="d-inline">{% csrf_token %}
                                    <input name="next" type="hidden" value="{{ request.get_full_path }}">
                                    <button name="language" value="en" class="dropdown-item {% if LANGUAGE_CODE == 'en' %}active bg-light-subtle{% endif %}" type="submit">
                                        <span class="me-2">🇺🇸</span> English
                                    </button>
                                </form>
                            </li>
                            <li>
                                <form action="{% url 'set_language' %}" method="post" class="d-inline">{% csrf_token %}
                                    <input name="next" type="hidden" value="{{ request.get_full_path }}">
                                    <button name="language" value="ar" class="dropdown-item {% if LANGUAGE_CODE == 'ar' %}active bg-light-subtle{% endif %}" type="submit">
                                        <span class="me-2">🇸🇦</span> العربية (Arabic)
                                    </button>
                                </form>
                            </li>
                        </ul>
                    </li>
                </ul>

                <ul class="navbar-nav ms-2 ms-lg-4">
                    <!-- Notification Bell for Admin Users -->
                    {% comment %} {% if request.user.is_authenticated and request.user.is_staff %}
                    <li class="nav-item dropdown me-2">
                        <a class="nav-link position-relative" href="#" role="button" id="notificationDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-bell"></i>
                            <span id="admin-notification-badge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="display: none; font-size: 0.6em; min-width: 18px; height: 18px; line-height: 18px;">
                                0
                            </span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" style="min-width: 300px;" aria-labelledby="notificationDropdown">
                            <li class="dropdown-header d-flex justify-content-between align-items-center">
                                <span>{% trans "Messages" %}</span>
                                <a href="#" class="text-decoration-none">{% trans "View All" %}</a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <div id="admin-notification-list" class="px-3 py-2 text-muted text-center">
                                    <small>{% trans "Loading messages..." %}</small>
                                </div>
                            </li>
                        </ul>
                    </li>
                    {% endif %} {% endcomment %}
                    <li class="nav-item me-2">
                        <a class="nav-link" href="{% url 'message_list' %}">
                            <i class="fas fa-envelope"></i>
                        </a>
                    </li>

                    <li class="nav-item dropdown">
                        <button
                            class="nav-link p-0 border-0 bg-transparent dropdown-toggle"
                            type="button"
                            data-bs-toggle="dropdown"
                            aria-expanded="false"
                            aria-label="{% trans 'Toggle user menu' %}"
                            data-bs-auto-close="outside"
                            data-bs-offset="0, 16" {# Vertical offset remains 16px to prevent clipping #}
                        >
                            {% if user.profile_image %}
                                <img src="{{ user.profile_image.url }}" alt="{{ user.username }}" class="profile-avatar"
                                    style="width: 36px; height: 36px; object-fit: cover; background-color: var(--kaauh-teal); display: inline-block; vertical-align: middle;"
                                    title="{% trans 'Your account' %}">
                            {% else %}
                                <div class="profile-avatar" title="{% trans 'Your account' %}">
                                    {{ user.username|first|upper }}
                                </div>
                            {% endif %}
                        </button>
                        <ul

                            class="dropdown-menu dropdown-menu-end py-0 shadow border-0 rounded-3"
                            style="min-width: 240px;"
                        >
                            <li class="px-4 py-3 ">
                                <div class="d-flex align-items-center">
                                    <div class="me-3 d-flex align-items-center justify-content-center" style="min-width: 48px;">
                                        {% if user.profile_image %}
                                            <img src="{{ user.profile_image.url }}" alt="{{ user.username }}" class="profile-avatar shadow-sm border"
                                                style="width: 44px; height: 44px; object-fit: cover; background-color: var(--kaauh-teal); display: block;"
                                                title="{% trans 'Your account' %}">
                                        {% else %}
                                            <div class="profile-avatar shadow-sm border d-flex align-items-center justify-content-center"
                                                style="width: 44px; height: 44px; background-color: var(--kaauh-teal); font-size: 1.2rem;">
                                                {{ user.username|first|upper }}
                                            </div>
                                        {% endif %}
                                    </div>
                                    <div>
                                        <div class="fw-semibold text-dark">{{ user.get_full_name|default:user.username }}</div>
                                        <div class="text-muted small">{{ user.email|truncatechars:24 }}</div>
                                    </div>
                                </div>
                            </li>
                            <li><hr class="dropdown-divider my-1"></li>
                            {% if request.user.is_authenticated %}
                            <li><a class="dropdown-item py-2 px-4 d-flex align-items-center text-decoration-none text-teal" href="{% url 'user_detail' request.user.pk %}"><i class="fas fa-user-circle me-3  fs-5"></i> <span>{% trans "My Profile" %}</span></a></li>


                                {% if request.user.is_superuser %}
                                    <li><a class="dropdown-item py-2 px-4 d-flex align-items-center text-decoration-none text-teal" href="{% url 'admin_settings' %}"><i class="fas fa-cog me-3  fs-5"></i> <span>{% trans "Settings" %}</span></a></li>
                                    <li><a class="dropdown-item py-2 px-4 d-flex align-items-center text-decoration-none text-teal" href="{% url 'source_list' %}"><i class="fas fa-cog me-3  fs-5"></i> <span>{% trans "Integration" %}</span></a></li>
                                    <li><a class="dropdown-item py-2 px-4 d-flex align-items-center text-decoration-none text-teal" href="{% url 'easy_logs' %}"><i class="fas fa-history me-3 fs-5"></i> <span>{% trans "Activity Log" %}</span></a></li>
                                {% comment %} <li><a class="dropdown-item py-2 px-4 d-flex align-items-center text-decoration-none" href="#"><i class="fas fa-question-circle me-3 text-primary fs-5"></i> <span>{% trans "Help & Support" %}</span></a></li> {% endcomment %}
                                {% endif %}
                            {% endif %}

                            {% comment %} CORRECTED LINKEDIN BLOCK {% endcomment %}
                            {% if not request.session.linkedin_authenticated %}
                                <li>
                                    <a class="dropdown-item py-2 px-4 d-flex align-items-center text-decoration-none text-teal" href="{% url 'linkedin_login' %}">
                                        <i class="fab fa-linkedin me-3 text-primary fs-5"></i>
                                        <span>{% trans "Connect LinkedIn" %}</span>
                                    </a>
                                </li>
                            {% else %}
                                <li class="px-4 py-2 text-muted small">
                                    <i class="fab fa-linkedin text-primary me-2"></i>
                                    {% trans "LinkedIn Connected" %}
                                </li>
                            {% endif %}

                            <li><hr class="dropdown-divider my-1"></li>
                            {% if request.user.is_authenticated %}
                            <li>
                                <form method="post" action="{% url 'account_logout'%}" class="d-inline">
                                    {% csrf_token %}
                                    <button
                                        type="submit"
                                        class="dropdown-item py-2 px-4 d-flex align-items-center border-0 bg-transparent text-start"
                                        aria-label="{% trans 'Sign out' %}"
                                    >
                                        <i class="fas fa-sign-out-alt me-3 fs-5 " style="color:red;"></i>
                                        <span style="color:red;">{% trans "Sign Out" %}</span>
                                    </button>
                                </form>
                                {% comment %} <a class="d-inline text-decoration-none px-4 d-flex align-items-center border-0 bg-transparent text-start text-center" href={% url "account_logout" %}>
                                     <i class="fas fa-sign-out-alt me-3 fs-5 " style="color:red;"></i>
                                    <span style="color:red;">{% trans "Sign Out" %}</span>
                                </a> {% endcomment %}
                            </li>
                            {% endif %}
                        </ul>
                    </li>
                </ul>
            </div>
            {# End Language and Profile Controls #}

            {# Main Navigation Links (This collapses on mobile) - order-lg-1 ensures it is centered on desktop #}
            <div class="collapse navbar-collapse order-lg-1" id="navbarNav">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    {# Changed me-4 to me-lg-4 so they stack tightly on mobile #}
                    <li class="nav-item me-lg-4">
                        <a class="nav-link {% if request.resolver_match.url_name == 'job_list' %}active{% endif %}" href="{% url 'job_list' %}">
                            <span class="d-flex align-items-center gap-2">
                                {% include "icons/jobs.html" %}
                                {% trans "Jobs" %}
                            </span>
                        </a>
                    </li>
                    <li class="nav-item me-lg-4">
                        <a class="nav-link {% if request.resolver_match.url_name == 'candidate_list' %}active{% endif %}" href="{% url 'candidate_list' %}">
                            <span class="d-flex align-items-center gap-2">
                                {% include "icons/users.html" %}
                                {% trans "Applications" %}
                            </span>
                        </a>
                    </li>
                    <li class="nav-item me-lg-4">
                        <a class="nav-link {% if request.resolver_match.url_name == 'person_list' %}active{% endif %}" href="{% url 'person_list' %}">
                            <span class="d-flex align-items-center gap-2">
                                {% include "icons/users.html" %}
                                {% trans "Applicant" %}
                            </span>
                        </a>
                    </li>
                    <li class="nav-item me-lg-4">
                        <a class="nav-link {% if request.resolver_match.url_name == 'agency_list' %}active{% endif %}" href="{% url 'agency_list' %}">
                            <span class="d-flex align-items-center gap-2">
                                <i class="fas fa-building"></i>
                                {% trans "Agencies" %}
                            </span>
                        </a>
                    </li>
                    <li class="nav-item me-lg-4">
                        <a class="nav-link {% if request.resolver_match.url_name == 'list_meetings' %}active{% endif %}" href="{% url 'list_meetings' %}">
                            <span class="d-flex align-items-center gap-2">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                            <path stroke-linecap="round" stroke-linejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" />
                            </svg>
                                {% trans "Meetings" %}
                            </span>
                        </a>
                    </li>
                    {% comment %} <li class="nav-item me-lg-4">
                        <a class="nav-link {% if request.resolver_match.url_name == 'interview_list' %}active{% endif %}" href="{% url 'interview_list' %}">
                            <span class="d-flex align-items-center gap-2">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                            <path stroke-linecap="round" stroke-linejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" />
                            </svg>
                                {% trans "Onsite Interviews" %}
                            </span>
                        </a>
                    </li> {% endcomment %}
                    <li class="nav-item me-lg-4">
                        <a class="nav-link {% if request.resolver_match.url_name == 'participants_list' %}active{% endif %}" href="{% url 'participants_list' %}">
                            <span class="d-flex align-items-center gap-2">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z" />
                                </svg>


                                {% trans "Participants" %}
                            </span>
                        </a>
                    </li>
                    {% comment %} <li class="nav-item dropdown ms-lg-2">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"
                        data-bs-offset="0, 8" data-bs-auto-close="outside">
                            {% trans "More" %}
                        </a>
                        <ul class="dropdown-menu" data-bs-popper="static">
                            <li><a class="dropdown-item" href="#"><i class="fas fa-calendar me-2"></i> {% trans "Meetings" %}</a></li>
                            <li><a class="dropdown-item" href="#"><i class="fas fa-clock me-2"></i> {% trans "Schedule" %}</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#"><i class="fas fa-briefcase me-2"></i> {% trans "Active Jobs" %}</a></li>
                            <li><a class="dropdown-item" href="#"><i class="fas fa-file-alt me-2"></i> {% trans "Draft Jobs" %}</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#"><i class="fas fa-users me-2"></i> {% trans "All Candidates" %}</a></li>
                            <li><a class="dropdown-item" href="#"><i class="fas fa-user-plus me-2"></i> {% trans "New Candidates" %}</a></li>
                        </ul>
                    </li> {% endcomment %}
                </ul>
            </div>
        </div>
    </nav>


    <main id="messageContent" class="container-fluid flex-grow-1" style="max-width: 1600px; margin: 0 auto;">
             {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-{{ message.tags }} alert-dismissible fade show mt-2" role="alert">
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="{% trans 'Close' %}"></button>
                    </div>
                {% endfor %}
            {% endif %}

            {% block content %}
            {% endblock %}
        </main>

<footer class="mt-auto">
    <div class="footer-bottom py-3 small text-muted" style="background-color: #00363a;">
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center flex-wrap max-width-1600">
                <p class="mb-0 text-white-50">
                    &copy; {% now "Y" %} {% trans "King Abdullah Academic University Hospital (KAAUH)." %}
                    {% trans "All rights reserved." %}
                </p>
                <a class="text-decoration-none" href="https://tenhal.sa/" target='_blank'>
                <p class="mb-0 text-white-50">
                    {% trans "Powered by" %} <strong class="text-white">Tenhal</strong>
                </p>
                </a>
            </div>
        </div>
    </div>
</footer>

    {% include 'includes/delete_modal.html' %}

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.7/dist/htmx.min.js"></script>
    <script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar@1.0.0-RC.6/bundles/datastar.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // Navbar collapse auto-close on link click (Standard Mobile UX)
            const navbarCollapse = document.getElementById('navbarNav');
            if (navbarCollapse) {
                // Select all links, including those inside "More" dropdown
                const navLinks = navbarCollapse.querySelectorAll('.nav-link:not(.dropdown-toggle), .dropdown-item');
                const bsCollapse = bootstrap.Collapse.getInstance(navbarCollapse) || new bootstrap.Collapse(navbarCollapse, { toggle: false });

                navLinks.forEach(link => {
                    link.addEventListener('click', () => {
                        // Only collapse if nav is actually shown (i.e., on mobile)
                        if (navbarCollapse.classList.contains('show')) {
                            // Check if click was on a non-dropdown-toggle or a dropdown item (which navigate away)
                            if (!link.classList.contains('dropdown-toggle')) {
                                bsCollapse.hide();
                            }
                        }
                    });
                });
            }

            // Mobile logout confirmation (Good UX for small screens)
            const logoutButton = document.querySelector('form[action$="/logout/"] button');
            if (logoutButton) {
                logoutButton.addEventListener('click', (e) => {
                    // Check if screen is small (Bootstrap 'lg' breakpoint is 992px)
                    if (window.innerWidth < 992) {
                        const confirmed = confirm('{% trans "Are you sure you want to sign out?" %}');
                        if (!confirmed) e.preventDefault();
                    }
                });
            }
        });


    function form_loader(){
        const forms = document.querySelectorAll('form');
        forms.forEach(form => {
        form.addEventListener('submit', function(e) {
        const submitButton = form.querySelector('button[type="submit"], input[type="submit"]');

        if (submitButton) {
            submitButton.disabled = true;
            submitButton.classList.add('loading');
            window.addEventListener('unload', function() {
            submitButton.disabled = false;
            submitButton.classList.remove('loading');
            });
        }
        });
  });
  }

  //form_loader();

  try{
      document.addEventListener('htmx:afterSwap', form_loader);
    }catch(e){
        console.error(e)
    }

function closeOpenBootstrapModal() {
    const openModalElement = document.querySelector('.modal.show');
    if (openModalElement) {
        const modal = bootstrap.Modal.getInstance(openModalElement);
        if (modal) {
            modal.hide();
        } else {
            console.warn("Found an open modal element, but could not get the Bootstrap Modal instance.");
        }
    } else {
        console.log("No open Bootstrap Modal found to close.");
    }
}
    </script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Update unread message count on page load
        fetch('/api/unread-count/')
            .then(response => response.json())
            .then(data => {
                const badge = document.getElementById('unread-messages-badge');
                if (badge && data.unread_count > 0) {
                    badge.textContent = data.unread_count;
                    badge.style.display = 'inline-block';
                }
            })
            .catch(error => console.error('Error fetching unread count:', error));
    });
    </script>

    <!-- Notification JavaScript for Admin Users -->
    {% comment %} {% if request.user.is_authenticated and request.user.is_staff %}
    <script>
        // SSE Notification System
        let eventSource = null;
        let reconnectAttempts = 0;
        let maxReconnectAttempts = 5;
        let reconnectDelay = 1000; // Start with 1 second

        function connectSSE() {
            // Close existing connection if any
            if (eventSource) {
                eventSource.close();
            }

            // Create new EventSource connection
            eventSource = new EventSource('');

            eventSource.onopen = function(event) {
                console.log('SSE connection opened');
                reconnectAttempts = 0;
                reconnectDelay = 1000; // Reset delay on successful connection

                // Update connection status indicator if exists
                const statusIndicator = document.getElementById('sse-status');
                if (statusIndicator) {
                    statusIndicator.className = 'text-success';
                    statusIndicator.title = 'Connected';
                }
            };

            eventSource.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);

                    if (event.type === 'new_notification') {
                        handleNewNotification(data);
                    } else if (event.type === 'count_update') {
                        updateNotificationCount(data.count);
                    } else if (event.type === 'heartbeat') {
                        console.log('SSE heartbeat received');
                    }
                } catch (error) {
                    console.error('Error parsing SSE message:', error);
                }
            };

            eventSource.addEventListener('new_notification', function(event) {
                try {
                    const notification = JSON.parse(event.data);
                    handleNewNotification(notification);
                } catch (error) {
                    console.error('Error parsing new notification:', error);
                }
            });

            eventSource.addEventListener('count_update', function(event) {
                try {
                    const data = JSON.parse(event.data);
                    updateNotificationCount(data.count);
                } catch (error) {
                    console.error('Error parsing count update:', error);
                }
            });

            eventSource.addEventListener('heartbeat', function(event) {
                try {
                    const data = JSON.parse(event.data);
                    console.log('SSE heartbeat:', new Date(data.timestamp * 1000));
                } catch (error) {
                    console.error('Error parsing heartbeat:', error);
                }
            });

            eventSource.addEventListener('error', function(event) {
                console.error('SSE error:', event);
                handleSSEError();
            });

            eventSource.onerror = function(event) {
                console.error('SSE connection error:', event);
                handleSSEError();
            };
        }

        function handleNewNotification(notification) {
            console.log('New notification received:', notification);

            // Update badge
            updateNotificationCount();

            // Show toast notification
            showToast(notification);

            // Update dropdown list
            addNotificationToList(notification);

            // Play sound (optional)
            playNotificationSound();
        }

        function updateNotificationCount(count) {
            const badge = document.getElementById('admin-notification-badge');

            if (count !== undefined) {
                // Use provided count
                if (count > 0) {
                    badge.style.display = 'inline-block';
                    badge.textContent = count;
                } else {
                    badge.style.display = 'none';
                }
            } else {
                // Fetch current count
                fetch('{% url "admin_notification_count" %}')
                    .then(response => response.json())
                    .then(data => {
                        if (data.count > 0) {
                            badge.style.display = 'inline-block';
                            badge.textContent = data.count;
                        } else {
                            badge.style.display = 'none';
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching notification count:', error);
                    });
            }
        }

        function addNotificationToList(notification) {
            const list = document.getElementById('admin-notification-list');
            if (!list) return;

            // Create new notification element
            const notificationElement = document.createElement('div');
            notificationElement.className = 'notification-item px-3 py-2 border-bottom';
            notificationElement.innerHTML = `
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <div class="fw-semibold small">${notification.message}</div>
                        <div class="text-muted small">${notification.type}</div>
                    </div>
                    <span class="badge bg-info ms-2">${notification.status}</span>
                </div>
                <div class="text-muted small mt-1">${notification.time_ago}</div>
            `;

            // Add click handler to navigate to notification detail
            notificationElement.style.cursor = 'pointer';
            notificationElement.addEventListener('click', function() {
                window.location.href = notification.url;
            });

            // Insert at the top of the list
            list.insertBefore(notificationElement, list.firstChild);

            // Remove "No new messages" placeholder if exists
            const placeholder = list.querySelector('.text-muted.text-center');
            if (placeholder) {
                placeholder.remove();
            }
        }

        function showToast(notification) {
            // Create toast container if it doesn't exist
            let toastContainer = document.getElementById('toast-container');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.id = 'toast-container';
                toastContainer.className = 'position-fixed top-0 end-0 p-3';
                toastContainer.style.zIndex = '1050';
                document.body.appendChild(toastContainer);
            }

            // Create toast element
            const toast = document.createElement('div');
            toast.className = 'toast show align-items-center text-white bg-primary border-0 mb-2';
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <strong>New Notification</strong><br>
                        <small>${notification.message}</small>
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;

            // Add click handler to close toast
            const closeButton = toast.querySelector('.btn-close');
            closeButton.addEventListener('click', function() {
                toast.remove();
            });

            // Add to container
            toastContainer.appendChild(toast);

            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.remove();
                }
            }, 5000);
        }

        function playNotificationSound() {
            // Create and play a simple notification sound
            try {
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = audioContext.createOscillator();
                const gainNode = audioContext.createGain();

                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);

                oscillator.frequency.value = 800; // 800 Hz tone
                oscillator.type = 'sine';

                gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1);

                oscillator.start(audioContext.currentTime);
                oscillator.stop(audioContext.currentTime + 0.1);
            } catch (error) {
                console.log('Could not play notification sound:', error);
            }
        }

        function handleSSEError() {
            // Update connection status indicator if exists
            const statusIndicator = document.getElementById('sse-status');
            if (statusIndicator) {
                statusIndicator.className = 'text-danger';
                statusIndicator.title = 'Disconnected';
            }

            // Attempt to reconnect with exponential backoff
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                console.log(`Attempting to reconnect (${reconnectAttempts}/${maxReconnectAttempts}) in ${reconnectDelay}ms...`);

                setTimeout(() => {
                    connectSSE();
                    reconnectDelay = Math.min(reconnectDelay * 2, 30000); // Max 30 seconds
                }, reconnectDelay);
            } else {
                console.error('Max reconnection attempts reached. Falling back to polling.');
                // Fallback to polling
                setInterval(updateNotificationBadge, 30000);
            }
        }

        // Initialize SSE connection on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Only connect SSE for authenticated staff users
            /*if ('{{ request.user.is_authenticated|yesno:"true,false" }}' === 'true' && '{{ request.user.is_staff|yesno:"true,false" }}' === 'true') {
                connectSSE();

                // Initial notification count update
                updateNotificationCount();
            }
                */
        });

        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            if (eventSource) {
                eventSource.close();
            }
        });

        // Fallback function for manual refresh
        function updateNotificationBadge() {
            fetch('{% url "admin_notification_count" %}')
                .then(response => response.json())
                .then(data => {
                    const badge = document.getElementById('admin-notification-badge');
                    const list = document.getElementById('admin-notification-list');

                    if (data.count > 0) {
                        badge.style.display = 'inline-block';
                        badge.textContent = data.count;
                    } else {
                        badge.style.display = 'none';
                    }

                    // Update notification list
                    if (data.recent_notifications && data.recent_notifications.length > 0) {
                        list.innerHTML = data.recent_notifications.map(msg => `
                            <div class="notification-item px-3 py-2 border-bottom">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <div class="fw-semibold small">${msg.message}</div>
                                        <div class="text-muted small">${msg.type}</div>
                                    </div>
                                    <span class="badge bg-info ms-2">${msg.status}</span>
                                </div>
                                <div class="text-muted small mt-1">${msg.time_ago}</div>
                            </div>
                        `).join('');
                    } else {
                        list.innerHTML = '<div class="px-3 py-2 text-muted text-center"><small>{% trans "No new messages" %}</small></div>';
                    }
                })
                .catch(error => {
                    console.error('Error fetching notifications:', error);
                    const list = document.getElementById('admin-notification-list');
                    list.innerHTML = '<div class="px-3 py-2 text-muted text-center"><small>{% trans "Error loading messages" %}</small></div>';
                });
        }
    </script> {% endcomment %}
    {% comment %} {% endif %} {% endcomment %}

    {% block customJS %}{% endblock %}
</body>
</html>
