<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Minha Loja{% endblock %}</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: sans-serif; }
        .container { max-width: 960px; margin: auto; padding: 20px; }
        .navbar { margin-bottom: 20px; }
        .thumbnail { width: 100%; height: 200px; object-fit: cover; }
        .box-element { box-shadow: hsl(0, 0%, 80%) 0 0 16px; background-color: #fff; border-radius: 4px; padding: 10px; margin-bottom: 15px; }
        .product { border: 1px solid #ddd; padding: 15px; text-align: center; }
        .product img { max-width: 100%; height: auto; margin-bottom: 10px; }
        .product h6 { margin-top: 10px; margin-bottom: 5px; }
        .product .btn { margin-top: 10px; }
        .cart-icon { width: 30px; display: inline-block; margin-left: 10px; }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="{% url 'home' %}">Minha Loja</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item"></li>
                </ul>
                <div class="form-inline my-2 my-lg-0">
                    {% if user.is_authenticated %}
                        {% if user.is_staff %}
                            <a href="{% url 'dashboard:home' %}" class="btn btn-outline-info me-2">
                                <i class="fas fa-tachometer-alt me-1"></i>Dashboard
                            </a>
                        {% endif %}
                        <a href="{% url 'logout' %}" class="btn btn-outline-light me-2">Logout</a>
                    {% else %}
                        <a href="{% url 'login' %}" class="btn btn-outline-light me-2">Login</a>
                        <a href="{% url 'register' %}" class="btn btn-primary">Registrar</a>
                    {% endif %}
                    <a href="{% url 'carrinho' %}" class="btn btn-warning ms-2">
                        Carrinho (<span id="cart-total">{{ carrinho_itens }}</span>)
                        <img id="cart-icon" src="/media/basket.png" class="cart-icon">
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <!-- Mensagens do Django -->
        {% if messages %}
            {% for message in messages %}
                <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                    {{ message }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            {% endfor %}
        {% endif %}
        
        {% block content %}
        {% endblock %}
    </div>

    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript">
        var user = '{{ request.user }}'
        var csrftoken = '{{ csrf_token }}'

        // Função para atualizar o contador do carrinho
        function updateCartCounter() {
            if (user !== "AnonymousUser") {
                fetch('/get_cart_count/', {
                    method: 'GET',
                    headers: {
                        'X-CSRFToken': csrftoken,
                    }
                })
                .then(response => response.json())
                .then(data => {
                    document.getElementById('cart-total').textContent = data.cart_count;
                })
                .catch(error => {
                    console.error('Erro ao atualizar contador do carrinho:', error);
                });
            }
        }

        // Adicionar event listeners quando a página carregar
        document.addEventListener('DOMContentLoaded', function() {
            var updateBtns = document.getElementsByClassName("update-cart")

            for (i = 0; i < updateBtns.length; i++) {
                updateBtns[i].addEventListener("click", function() {
                    var productId = this.dataset.product
                    var action = this.dataset.action
                    console.log("productId:", productId, "action:", action)

                    console.log("USER:", user)
                    if (user == "AnonymousUser") {
                        alert("Por favor, faça login para adicionar produtos ao carrinho.")
                    } else {
                        updateUserOrder(productId, action)
                    }
                })
            }
        });

        function updateUserOrder(productId, action) {
            console.log("User is logged in, sending data...")

                        var url = "/atualizar_item/"

            fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRFToken": csrftoken,
                },
                body: JSON.stringify({"produtoId": productId, "action": action})
            })
            .then((response) => {
                return response.json()
            })
            .then((data) => {
                console.log("data:", data)
                // Atualizar contador do carrinho sem recarregar a página
                updateCartCounter()
                
                // Mostrar feedback visual
                if (action === 'add') {
                    showNotification('Produto adicionado ao carrinho!', 'success')
                } else if (action === 'remove') {
                    showNotification('Produto removido do carrinho!', 'info')
                }
            })
            .catch(error => {
                console.error('Erro:', error)
                showNotification('Erro ao atualizar carrinho', 'error')
            })
        }

        // Função para mostrar notificações
        function showNotification(message, type) {
            // Criar elemento de notificação
            var notification = document.createElement('div');
            notification.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} alert-dismissible fade show position-fixed`;
            notification.style.top = '20px';
            notification.style.right = '20px';
            notification.style.zIndex = '9999';
            notification.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.body.appendChild(notification);
            
            // Remover automaticamente após 3 segundos
            setTimeout(function() {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 3000);
        }
    </script>
</body>
</html>

