{% load i18n %}
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}RaktaPulse Dashboard{% endblock %}</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
    
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    
    <style>
        :root {
            --dark-bg: #f8f9fa;
            --sidebar-bg: #ffffff;
            --card-bg: #ffffff;
            --pulse-red: #E63946;
            --pulse-red-light: #fff5f5;
            --pulse-red-glow: rgba(230, 57, 70, 0.1);
            --text-primary: #2b2d42;
            --text-secondary: #6c757d;
            --border-color: rgba(0, 0, 0, 0.08);
            --sidebar-width: 260px;
        }

        body {
            background-color: var(--dark-bg);
            color: var(--text-primary);
            font-family: 'Inter', sans-serif;
            margin: 0;
            overflow-x: hidden;
        }

        /* Remove blue underline from links */
        a {
            text-decoration: none !important;
            color: inherit;
        }
        
        a:hover {
            color: var(--pulse-red);
        }

        @keyframes blink {
            0% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.6; transform: scale(1.1); }
            100% { opacity: 1; transform: scale(1); }
        }
        .blinking-logo {
            animation: blink 1.5s infinite ease-in-out;
            display: inline-block;
        }

        h1, h2, h3, .brand-font {
            font-family: 'Outfit', sans-serif;
        }

        /* F-Shape Layout */
        .wrapper {
            display: flex;
            width: 100%;
            align-items: stretch;
        }

        /* Sidebar (Vertical stroke of F) */
        #sidebar {
            width: var(--sidebar-width);
            background: var(--sidebar-bg);
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
            border-right: 1px solid var(--border-color);
            transition: all 0.3s;
            overflow-y: auto;
        }

        #sidebar.collapsed {
            margin-left: calc(-1 * var(--sidebar-width));
        }

        .sidebar-header {
            padding: 30px 25px;
            display: flex;
            align-items: center;
        }

        .sidebar-menu {
            padding: 0;
            list-style: none;
        }

        .sidebar-menu li a {
            padding: 15px 25px;
            display: flex;
            align-items: center;
            color: var(--text-secondary);
            text-decoration: none;
            transition: all 0.3s;
            font-weight: 500;
            border-left: 4px solid transparent;
        }

        .sidebar-menu li a:hover, .sidebar-menu li.active a {
            color: var(--pulse-red);
            background: var(--pulse-red-light);
            border-left-color: var(--pulse-red);
        }

        .sidebar-menu li a i {
            margin-right: 15px;
            font-size: 1.2rem;
        }

        /* Content Area */
        #content {
            width: calc(100% - var(--sidebar-width));
            margin-left: var(--sidebar-width);
            min-height: 100vh;
            transition: all 0.3s;
        }

        #content.expanded {
            width: 100%;
            margin-left: 0;
        }

        /* Top Bar (Horizontal stroke 1 of F) */
        .top-bar {
            height: 70px;
            background: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            padding: 0 30px;
            border-bottom: 1px solid var(--border-color);
            position: sticky;
            top: 0;
            z-index: 999;
        }

        .search-box {
            background: #f1f3f5;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 6px 15px;
            display: flex;
            align-items: center;
            width: 300px;
        }

        .search-box input {
            background: transparent;
            border: none;
            color: var(--text-primary);
            padding-left: 10px;
            width: 100%;
        }

        .search-box input:focus {
            outline: none;
        }

        /* Glass Cards */
        .glass-card {
            background: var(--card-bg);
            border-radius: 16px;
            border: 1px solid var(--border-color);
            padding: 24px;
            transition: transform 0.3s ease;
        }

        .glass-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        }

        /* Responsive */
        @media (max-width: 992px) {
            #sidebar { margin-left: calc(-1 * var(--sidebar-width)); }
            #content { width: 100%; margin-left: 0; }
            #sidebar.active { margin-left: 0; }
        }

        /* SOS Floating Button */
        .sos-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 65px;
            height: 65px;
            background-color: var(--pulse-red);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
            z-index: 9999;
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            font-weight: 800;
            font-size: 1.1rem;
            border: 3px solid white;
        }

        .sos-btn:hover {
            transform: scale(1.1);
            color: white;
            box-shadow: 0 6px 20px rgba(230, 57, 70, 0.6);
        }

        .sos-btn .pulse-ring {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background-color: var(--pulse-red);
            opacity: 0.6;
            animation: sos-pulse 2s infinite;
            z-index: -1;
        }

        .dropdown-toggle.no-caret::after {
            display: none;
        }

        .sos-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            line-height: 1;
        }

        .sos-text {
            font-size: 1.1rem;
            font-weight: 800;
        }

        .sos-number {
            font-size: 0.7rem;
            font-weight: 600;
            margin-top: 2px;
        }

        @keyframes sos-pulse {
            0% { transform: scale(1); opacity: 0.6; }
            100% { transform: scale(1.8); opacity: 0; }
        }

        @media (max-width: 576px) {
            .sos-btn {
                bottom: 20px;
                right: 20px;
                width: 55px;
                height: 55px;
                font-size: 0.9rem;
            }
        }

        {% block head %}{% endblock %}
    </style>
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <a href="/" class="text-decoration-none d-flex align-items-center">
                    <div class="bg-danger rounded-circle d-flex align-items-center justify-content-center me-2 blinking-logo" style="width: 35px; height: 35px;">
                        <i class="bi bi-droplet-fill text-white"></i>
                    </div>
                    <span class="fs-4 fw-bold text-danger brand-font">RaktaPulse</span>
                </a>
            </div>
            
            <ul class="sidebar-menu mt-4">
                <li class="{% if request.resolver_match.url_name == 'home' %}active{% endif %}"><a href="{% url 'home' %}"><i class="bi bi-grid-1x2-fill"></i> {% trans "Dashboard" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'donor_list' %}active{% endif %}"><a href="{% url 'donor_list' %}"><i class="bi bi-people-fill"></i> {% trans "Donors" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'blood_request_list' %}active{% endif %}"><a href="{% url 'blood_request_list' %}"><i class="bi bi-megaphone-fill"></i> {% trans "Blood Requests" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'donation_history' %}active{% endif %}"><a href="{% url 'donation_history' %}"><i class="bi bi-clock-history"></i> {% trans "Donation History" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'lives_saved' %}active{% endif %}"><a href="{% url 'lives_saved' %}"><i class="bi bi-heart-pulse"></i> {% trans "Lives Saved" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'blood_bank_list' %}active{% endif %}"><a href="{% url 'blood_bank_list' %}"><i class="bi bi-droplet-half"></i> {% trans "Blood Banks" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'hospital_list' %}active{% endif %}"><a href="{% url 'hospital_list' %}"><i class="bi bi-hospital-fill"></i> {% trans "Hospitals" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'live_map' %}active{% endif %}"><a href="{% url 'live_map' %}"><i class="bi bi-map text-danger"></i> {% trans "Live Alerts" %}</a></li>
                <li class="{% if request.resolver_match.url_name == 'vaccination_info' %}active{% endif %}"><a href="{% url 'vaccination_info' %}"><i class="bi bi-shield-check"></i> {% trans "Vaccination" %}</a></li>
                {% if user.is_authenticated %}
                <li class="{% if 'vaccination_dashboard' in request.resolver_match.url_name or 'add_vaccination' in request.resolver_match.url_name %}active{% endif %}"><a href="{% url 'vaccination_dashboard' %}"><i class="bi bi-journal-check"></i> {% trans "My Records" %}</a></li>
                {% endif %}
                {% if user.is_superuser %}
                <li><a href="/admin/"><i class="bi bi-gear-fill"></i> {% trans "Settings" %}</a></li>
                {% endif %}
            </ul>
        </nav>

        <!-- Page Content -->
        <div id="content">
            <!-- Top Bar -->
            <div class="top-bar justify-content-between flex-wrap">
                <div class="d-flex align-items-center">
                    <button type="button" id="sidebarCollapse" class="btn btn-link text-danger me-3 p-0">
                        <i class="bi bi-list fs-3"></i>
                    </button>
                    <form action="{% url 'donor_list' %}" method="GET" class="search-box d-none d-lg-flex">
                        <button type="submit" class="btn btn-link p-0 text-secondary border-0">
                            <i class="bi bi-search"></i>
                        </button>
                        <input type="text" name="q" placeholder="Search anything..." value="{{ request.GET.q }}">
                    </form>
                </div>
                
                <div class="d-flex align-items-center gap-2 gap-md-4">
                    <!-- Language Switcher -->
                    <div class="dropdown">
                        <button class="btn btn-link text-secondary dropdown-toggle d-flex align-items-center gap-1 p-0 text-decoration-none small" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-translate"></i>
                            <span class="d-none d-sm-inline">{{ LANGUAGE_CODE|upper }}</span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0">
                            {% get_current_language as LANGUAGE_CODE %}
                            {% get_available_languages as LANGUAGES %}
                            {% get_language_info_list for LANGUAGES as languages %}
                            {% for language in languages %}
                            <li>
                                <form action="{% url 'set_language' %}" method="post">
                                    {% csrf_token %}
                                    <input name="next" type="hidden" value="{{ request.get_full_path }}">
                                    <input name="language" type="hidden" value="{{ language.code }}">
                                    <button type="submit" class="dropdown-item {% if language.code == LANGUAGE_CODE %}active{% endif %}">
                                        {{ language.name_local }} ({{ language.code|upper }})
                                    </button>
                                </form>
                            </li>
                            {% endfor %}
                        </ul>
                    </div>

                    <div id="location-status" class="d-none d-xl-flex align-items-center text-secondary small cursor-pointer" style="cursor: pointer;" onclick="detectLocation()">
                        <i class="bi bi-geo-alt me-1"></i>
                        <span id="location-text">Detect Location</span>
                    </div>
                    <div class="d-none d-md-flex align-items-center text-secondary small">
                        <i class="bi bi-calendar3 me-1"></i>
                        {{ current_time|date:"M d" }}
                    </div>
                    {% if user.is_authenticated %}
                    <div class="d-flex align-items-center gap-2">
                        <!-- Notification Bell -->
                        <a href="{% url 'notifications' %}" class="text-decoration-none me-2 position-relative">
                            <i class="bi bi-bell-fill fs-5 text-secondary"></i>
                            {% if unread_notifications_count > 0 %}
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="font-size: 0.6rem;">
                                {{ unread_notifications_count }}
                            </span>
                            {% endif %}
                        </a>

                        <!-- Messages Inbox -->
                        <a href="{% url 'inbox' %}" class="text-decoration-none me-2 position-relative">
                            <i class="bi bi-chat-dots-fill fs-5 text-secondary"></i>
                            {% if unread_messages_count > 0 %}
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="font-size: 0.6rem;">
                                {{ unread_messages_count }}
                            </span>
                            {% endif %}
                        </a>
                        
                        <!-- Profile Dropdown -->
                        <div class="dropdown">
                            <a href="#" class="text-decoration-none d-flex align-items-center gap-2 dropdown-toggle no-caret" id="profileDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                <div class="rounded-circle overflow-hidden border border-danger-subtle d-flex align-items-center justify-content-center" style="width: 35px; height: 35px;">
                                    {% if user.profile.profile_pic %}
                                        <img src="{{ user.profile.profile_pic.url }}" alt="{{ user.username }}" class="w-100 h-100 object-fit-cover">
                                    {% else %}
                                        <div class="bg-danger bg-opacity-10 w-100 h-100 d-flex align-items-center justify-content-center">
                                            <i class="bi bi-person-fill text-danger"></i>
                                        </div>
                                    {% endif %}
                                </div>
                                <span class="d-none d-sm-inline fw-bold text-dark">{{ user.username }}</span>
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="profileDropdown">
                                <li>
                                    <a class="dropdown-item d-flex align-items-center gap-2 py-2" href="{% url 'profile' %}">
                                        <i class="bi bi-person-circle text-danger"></i>
                                        <span>{% trans "My Profile" %}</span>
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center gap-2 py-2" href="{% url 'profile' %}">
                                        <i class="bi bi-pencil-square text-danger"></i>
                                        <span>{% trans "Change Name" %}</span>
                                    </a>
                                </li>
                                <li><hr class="dropdown-divider opacity-50"></li>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center gap-2 py-2 text-danger" href="{% url 'logout' %}">
                                        <i class="bi bi-box-arrow-right"></i>
                                        <span>{% trans "Logout" %}</span>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                    {% else %}
                    <div class="d-flex align-items-center gap-2">
                        <a href="{% url 'login' %}" class="btn btn-danger btn-sm px-2 px-sm-3">Login</a>
                        <a href="{% url 'register' %}" class="btn btn-outline-danger btn-sm px-2 px-sm-3">Register</a>
                    </div>
                    {% endif %}
                </div>
            </div>

            <div class="p-4 p-md-5">
                {% if messages %}
                    {% for message in messages %}
                        <div class="alert alert-{{ message.tags }} alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
                            {% if message.tags == 'success' %}<i class="bi bi-check-circle-fill me-2"></i>{% endif %}
                            {% if message.tags == 'error' %}<i class="bi bi-exclamation-triangle-fill me-2"></i>{% endif %}
                            {{ message }}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    {% endfor %}
                {% endif %}
                {% block content %}{% endblock %}
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 Bundle JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Leaflet JS -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        document.getElementById('sidebarCollapse').addEventListener('click', function() {
            document.getElementById('sidebar').classList.toggle('collapsed');
            document.getElementById('content').classList.toggle('expanded');
            
            // For mobile view, handle the 'active' class as well if needed
            if (window.innerWidth <= 992) {
                document.getElementById('sidebar').classList.toggle('active');
            }
        });

        function detectLocation() {
            const text = document.getElementById('location-text');
            const originalText = text.innerText;
            text.innerText = "Locating...";

            if ("geolocation" in navigator) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    const lat = position.coords.latitude;
                    const lng = position.coords.longitude;
                    text.innerText = lat.toFixed(4) + ", " + lng.toFixed(4);
                    
                    // Save to cookies for 1 day
                    document.cookie = `user_lat=${lat}; path=/; max-age=86400`;
                    document.cookie = `user_lng=${lng}; path=/; max-age=86400`;
                    
                    // If we are on a list page without lat/lng, reload with them
                    const urlParams = new URLSearchParams(window.location.search);
                    if (!urlParams.has('lat')) {
                        urlParams.set('lat', lat);
                        urlParams.set('lng', lng);
                        window.location.search = urlParams.toString();
                    }
                }, function(error) {
                    text.innerText = "Error";
                    console.error(error);
                });
            } else {
                text.innerText = "Not supported";
            }
        }

        // Check if location is already in cookies
        function checkLocationCookie() {
            const cookies = document.cookie.split(';');
            let lat = null, lng = null;
            for (let cookie of cookies) {
                const [name, value] = cookie.trim().split('=');
                if (name === 'user_lat') lat = value;
                if (name === 'user_lng') lng = value;
            }
            if (lat && lng) {
                document.getElementById('location-text').innerText = parseFloat(lat).toFixed(4) + ", " + parseFloat(lng).toFixed(4);
            }
        }
        checkLocationCookie();
    </script>
    <a href="javascript:void(0);" class="sos-btn" id="sosButton" title="Single click: Request Form | Double click: Call 1115">
        <div class="pulse-ring"></div>
        <div class="sos-content">
            <span class="sos-text">SOS</span>
            <span class="sos-number">1115</span>
        </div>
    </a>

    <script>
        (function() {
            const sosBtn = document.getElementById('sosButton');
            let clickTimer = null;
            
            sosBtn.addEventListener('click', function(e) {
                e.preventDefault();
                
                if (clickTimer === null) {
                    // First click: start a timer
                    clickTimer = setTimeout(function() {
                        clickTimer = null;
                        // Single click action: Go to request form
                        window.location.href = "{% url 'request_blood' %}";
                    }, 300); // 300ms window for double click
                } else {
                    // Second click within 300ms: clear timer and trigger call
                    clearTimeout(clickTimer);
                    clickTimer = null;
                    window.location.href = "tel:1115";
                }
            });
        })();
    </script>

    {% block scripts %}{% endblock %}

    {% if user.is_authenticated %}
    <script>
        (function() {
            function sendLocation(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                
                // Update local display if it exists
                const locText = document.getElementById('location-text');
                if (locText && locText.innerText === "Detect Location") {
                    locText.innerText = lat.toFixed(4) + ", " + lng.toFixed(4);
                }

                fetch("{% url 'update_location' %}", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRFToken": "{{ csrf_token }}"
                    },
                    body: JSON.stringify({
                        latitude: lat,
                        longitude: lng
                    })
                }).catch(err => console.debug("Location update deferred"));
            }

            if ("geolocation" in navigator) {
                // Live tracking
                navigator.geolocation.watchPosition(sendLocation, 
                    (err) => console.debug("Position update skipped"),
                    {
                        enableHighAccuracy: true,
                        maximumAge: 60000, // 1 minute
                        timeout: 30000
                    }
                );
            }
        })();
    </script>
    {% endif %}
</body>
</html>
