{% extends 'main/header.html' %}
{% load static %}

{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <title>Најблиски продавници</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
          integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
          crossorigin=""/>
    <style>
        :root {
            --primary-color: #2e652e;
            --primary-dark: #1f3f1f;
            --light-bg: #f5f5f5;
            --white: #ffffff;
            --text-dark: #333333;
            --text-light: #666666;
            --border-color: #e0e0e0;
        }

        /* Base Styles */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: var(--light-bg);
            color: var(--text-dark);
            line-height: 1.6;
        }

        /* Stores Page Container */
        .stores-wrapper {
            padding: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }

        /* Main Container */
        .stores-container {
            background-color: var(--white);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            margin-bottom: 30px;
            animation: fadeIn 0.4s ease-out;
        }

        /* Header Section */
        .stores-header {
            background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),
                url('{% static "images/baner1.jpg" %}') center center / cover no-repeat;
            color: white;
            padding: 40px 20px;
            text-align: center;
        }

        .stores-main-title {
            font-size: 28px;
            font-weight: 700;
            margin: 0;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

        /* Navigation */
        .back-button {
            margin: 20px;
        }

        .back-button a {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            background-color: var(--white);
            color: var(--primary-color);
            border-radius: 30px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(46, 101, 46, 0.2);
        }

        .back-button a:hover {
            background-color: #f0f7f0;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* Form Styles */
        .store-search-form {
            padding: 0 20px 20px;
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            flex: 1;
            min-width: 0;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--primary-color);
            font-size: 14px;
        }

        .form-input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 15px;
            background-color: var(--white);
            transition: all 0.2s ease;
        }

        .form-input:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(46, 101, 46, 0.1);
        }

        .form-actions {
            text-align: center;
            margin-top: 30px;
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .action-button {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 14px 30px;
            border-radius: 30px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
            border: 2px solid transparent;
        }

        .primary-button {
            background-color: var(--primary-color);
            color: var(--white);
            border-color: var(--primary-color);
        }

        .primary-button:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .secondary-button {
            background-color: #e8f5e9;
            color: var(--primary-color);
            border-color: #c8e6c9;
        }

        .secondary-button:hover {
            background-color: #d0f0d0;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* Stores Grid */
        .stores-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin: 30px 20px;
        }

        .store-card {
            background-color: var(--white);
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            border-left: 4px solid #81c784;
        }

        .store-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .store-title {
            color: var(--primary-color);
            margin: 0 0 15px 0;
            font-size: 18px;
            font-weight: 600;
        }

        .store-meta {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            color: var(--text-light);
        }

        .meta-item i {
            color: var(--primary-color);
            width: 20px;
            text-align: center;
        }

        /* Map Styles */
        #map-container {
            height: 500px;
            margin: 20px;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid var(--border-color);
        }

        #map {
            height: 100%;
            width: 100%;
        }

        /* Empty State */
        .no-stores {
            text-align: center;
            padding: 40px;
            margin: 20px;
            background-color: #fff3e0;
            border-radius: 8px;
            color: #e65100;
            border-left: 4px solid #e65100;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.02); }
            100% { transform: scale(1); }
        }

        .no-stores i {
            font-size: 40px;
            margin-bottom: 15px;
            color: #e65100;
        }

        .no-stores p {
            margin: 5px 0;
            font-size: 16px;
        }

        /* Section Titles */
        .section-title {
            color: var(--primary-color);
            font-size: 20px;
            font-weight: 600;
            margin: 30px 20px 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        /* Responsive Adjustments */
        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
                gap: 15px;
            }

            .form-actions {
                flex-direction: column;
                gap: 10px;
            }

            .action-button {
                width: 100%;
                justify-content: center;
            }

            #map-container {
                height: 300px;
            }

            .stores-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 480px) {
            .stores-wrapper {
                padding: 10px;
            }

            .stores-header {
                padding: 30px 15px;
            }

            .stores-main-title {
                font-size: 24px;
            }

            .back-button {
                margin: 15px;
            }

            .store-search-form {
                padding: 0 15px 15px;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>

<div class="stores-wrapper">
    <div class="stores-container">
        <!-- Header Section -->
        <div class="stores-header">
            <h1 class="stores-main-title">Најблиски продавници</h1>
        </div>

        <div class="back-button">
            <a href="{% url 'home' %}">
                <i class="fas fa-arrow-left"></i> Назад кон почетна
            </a>
        </div>

        <!-- Search Form -->
        <form method="get" action="{% url 'nearby_stores' %}" class="store-search-form">
            <div class="form-row">
                <div class="form-group">
                    <label for="latitude"><i class="fas fa-map-marker-alt"></i> Latitude:</label>
                    <input type="text" id="latitude" name="latitude" required class="form-input">
                </div>
                <div class="form-group">
                    <label for="longitude"><i class="fas fa-map-marker-alt"></i> Longitude:</label>
                    <input type="text" id="longitude" name="longitude" required class="form-input">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="fuel_consumption"><i class="fas fa-gas-pump"></i> Потрошувачка на гориво (L/100km):</label>
                    <input type="number" step="0.1" id="fuel_consumption" name="fuel_consumption" required
                           class="form-input">
                </div>
                <div class="form-group">
                    <label for="store_chain"><i class="fas fa-store"></i> Продавничка мрежа:</label>
                    <select name="store_chain" id="store_chain" required class="form-input">
                        <option value="Reptil">Reptil</option>
                        <option value="Vero">Vero</option>
                        <option value="Ramstore">Ramstore</option>
                    </select>
                </div>
            </div>

            <div class="form-actions">
                <button type="button" onclick="getLocation()" class="action-button secondary-button">
                    <i class="fas fa-location-arrow"></i> Користи моја локација
                </button>
                <button type="submit" class="action-button primary-button">
                    <i class="fas fa-search"></i> Пронајди продавници
                </button>
            </div>
        </form>

        {% if nearest_stores %}
            <h2 class="section-title"><i class="fas fa-store"></i> Најблиски продавници</h2>
            <div class="stores-grid">
                {% for store in nearest_stores|slice:":5" %}
                    <div class="store-card">
                        <h3 class="store-title">{{ store.store }}</h3>
                        <div class="store-meta">
                            <span class="meta-item"><i class="fas fa-route"></i> Растојание: {{ store.distance_km }} km</span>
                            <span class="meta-item"><i class="fas fa-clock"></i> Време: {{ store.duration }}</span>
                            <span class="meta-item"><i class="fas fa-gas-pump"></i> Гориво: {{ store.gas_used }} L</span>
                        </div>
                    </div>
                {% endfor %}
            </div>

            <!-- Map Container -->
            <div id="map-container">
                <div id="map"></div>
            </div>

{#            <!-- Center Map Button -->#}
{#            <div class="form-actions" style="margin-top: 15px;">#}
{#                <button onclick="centerMapOnUser()" class="action-button secondary-button">#}
{#                    <i class="fas fa-location-arrow"></i> Центрирај на мојата локација#}
{#                </button>#}
{#            </div>#}
        {% else %}
            <div class="no-stores">
                <i class="fas fa-exclamation-circle"></i>
                <p>Нема пронајдени продавници.</p>
                <p>Внесете ги вашите координати за да ги видите најблиските продавници.</p>
            </div>
        {% endif %}

        {% if least_gas_stores %}
            <h2 class="section-title"><i class="fas fa-gas-pump"></i> Продавници со најмало користење на гориво</h2>
            <div class="stores-grid">
                {% for store in least_gas_stores|slice:":5" %}
                    <div class="store-card">
                        <h3 class="store-title">{{ store.store }}</h3>
                        <div class="store-meta">
                            <span class="meta-item"><i class="fas fa-route"></i> Растојание: {{ store.distance_km }} km</span>
                            <span class="meta-item"><i class="fas fa-clock"></i> Време: {{ store.duration }}</span>
                            <span class="meta-item"><i class="fas fa-gas-pump"></i> Гориво: {{ store.gas_used }} L</span>
                        </div>
                    </div>
                {% endfor %}
            </div>
        {% endif %}
    </div>
</div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
        crossorigin=""></script>

<script>
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                document.getElementById("latitude").value = position.coords.latitude.toFixed(6);
                document.getElementById("longitude").value = position.coords.longitude.toFixed(6);

                if (typeof map !== 'undefined') {
                    updateMap(position.coords.latitude, position.coords.longitude);
                }
            }, function (error) {
                {#alert("Грешка при геолокација: " + error.message);#}
            });
        } else {
            alert("Геолокацијата не е поддржана од овој пребарувач.");
        }
    }

    let map;
    let userMarker;
    let storeMarkers = [];
    let routeLines = [];

    document.addEventListener('DOMContentLoaded', function () {
        {% if nearest_stores %}
            initMap();
        {% endif %}
    });

    function initMap() {
        try {
            const userLat = parseFloat(document.getElementById('latitude').value) || {{ nearest_stores.0.latitude|default:41.9981 }};
            const userLng = parseFloat(document.getElementById('longitude').value) || {{ nearest_stores.0.longitude|default:21.4254 }};

            map = L.map('map', {
                center: [userLat, userLng],
                zoom: 13
            });

            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                maxZoom: 18
            }).addTo(map);

            userMarker = L.marker([userLat, userLng], {
                icon: L.icon({
                    iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
                    iconSize: [25, 41],
                    iconAnchor: [12, 41],
                    popupAnchor: [1, -34]
                })
            }).addTo(map);
            userMarker.bindPopup("<b>Вашата локација</b>").openPopup();

            storeMarkers.forEach(marker => map.removeLayer(marker));
            routeLines.forEach(line => map.removeLayer(line));
            storeMarkers = [];
            routeLines = [];

            const stores = [
                {% for store in nearest_stores %}
                    {
                        name: "{{ store.store|escapejs }}",
                        latitude: {{ store.latitude }},
                        longitude: {{ store.longitude }},
                        distance: {{ store.distance_km }},
                        duration: "{{ store.duration|escapejs }}",
                        gasUsed: {{ store.gas_used }}
                    },
                {% endfor %}
            ];

            stores.forEach(store => {
                const storeMarker = L.marker([store.latitude, store.longitude], {
                    icon: L.icon({
                        iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
                        iconSize: [25, 41],
                        iconAnchor: [12, 41],
                        popupAnchor: [1, -34]
                    })
                }).addTo(map);
                storeMarker.bindPopup(
                    `<b>${store.name}</b><br>` +
                    `Растојание: ${store.distance} km<br>` +
                    `Време: ${store.duration}<br>` +
                    `Гориво: ${store.gasUsed} L`
                );
                storeMarkers.push(storeMarker);

                const line = L.polyline(
                    [[userLat, userLng], [store.latitude, store.longitude]],
                    {color: '#2e652e', weight: 2, dashArray: '5, 5'}
                ).addTo(map);
                routeLines.push(line);
            });

            console.log("Map initialized successfully with center:", [userLat, userLng]);
        } catch (error) {
            console.error("Error initializing map:", error);
            alert("Грешка при иницијализација на мапата. Проверете ги координатите или податоците.");
        }
    }

    function updateMap(lat, lng) {
        if (!map) return;

        userMarker.setLatLng([lat, lng]);
        userMarker.bindPopup("<b>Вашата локација</b>").openPopup();

        routeLines.forEach((line, index) => {
            const storeMarker = storeMarkers[index];
            if (storeMarker) {
                const storeLatLng = storeMarker.getLatLng();
                line.setLatLngs([[lat, lng], [storeLatLng.lat, storeLatLng.lng]]);
            }
        });

        map.setView([lat, lng], 13);
    }

    function centerMapOnUser() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                const userLat = position.coords.latitude;
                const userLng = position.coords.longitude;

                document.getElementById('latitude').value = userLat.toFixed(6);
                document.getElementById('longitude').value = userLng.toFixed(6);

                if (map) {
                    updateMap(userLat, userLng);
                } else {
                    initMap();
                }
            }, function (error) {
                alert("Грешка при геолокација: " + error.message);
            });
        } else {
            alert("Геолокацијата не е поддржана од овој пребарувач.");
        }
    }

    document.querySelector('.store-search-form').addEventListener('submit', function () {
        if (map) {
            setTimeout(initMap, 100);
        }
    });
</script>
</body>
{% endblock %}
</html>