<?php
/**
 * Cart Sidebar Component - MontaLoja
 * Carrinho lateral com todas as funcionalidades
 */

$storeSlug = $store['slug'] ?? '';
$checkoutUrl = (isset($baseUrl) ? $baseUrl : (function_exists('storeUrl') ? storeUrl() : '')) . '/checkout';
?>

<!-- Cart Overlay -->
<div class="cart-overlay" id="cartOverlay" onclick="closeCart()"></div>

<!-- Cart Sidebar -->
<div class="cart-sidebar" id="cartSidebar">
    <div class="cart-header">
        <h3><iconify-icon icon="solar:cart-3-bold" style="font-size: 1.3rem; margin-right: 8px;"></iconify-icon> Seu Carrinho</h3>
        <button class="cart-close" onclick="closeCart()">
            <iconify-icon icon="solar:close-circle-bold" style="font-size: 1.5rem;"></iconify-icon>
        </button>
    </div>
    
    <div class="cart-items" id="cartItems">
        <!-- Itens do carrinho serão inseridos aqui via JavaScript -->
    </div>
    
    <div class="cart-empty" id="cartEmpty" style="display: none;">
        <iconify-icon icon="solar:cart-large-minimalistic-outline" style="font-size: 4rem; opacity: 0.3;"></iconify-icon>
        <p>Seu carrinho está vazio</p>
        <a href="<?php echo isset($baseUrl) ? $baseUrl : (function_exists('storeUrl') ? storeUrl() : ''); ?>/produtos" class="btn-continue-shopping">Continuar Comprando</a>
    </div>
    
    <div class="cart-footer" id="cartFooter">
        <div class="cart-subtotal">
            <span>Subtotal:</span>
            <span id="cartSubtotal">R$ 0,00</span>
        </div>
        <a href="<?php echo htmlspecialchars($checkoutUrl); ?>" class="btn-checkout" id="btnCheckout">
            Finalizar Compra
        </a>
        <button class="btn-continue" onclick="closeCart()">Continuar Comprando</button>
    </div>
</div>

<style>
/* Cart Overlay */
.cart-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.cart-overlay.active {
    opacity: 1;
    visibility: visible;
}

/* Cart Sidebar */
.cart-sidebar {
    position: fixed;
    top: 0;
    right: -400px;
    width: 100%;
    max-width: 400px;
    height: 100%;
    background: var(--bg-primary, #fff);
    box-shadow: -4px 0 20px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    display: flex;
    flex-direction: column;
    transition: right 0.3s ease;
}

.cart-sidebar.active {
    right: 0;
}

.cart-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid var(--border-color, #eee);
    background: var(--bg-secondary, #f9f9f9);
}

.cart-header h3 {
    margin: 0;
    font-size: 1.1rem;
    display: flex;
    align-items: center;
    color: var(--text-primary, #333);
}

.cart-close {
    background: none;
    border: none;
    cursor: pointer;
    color: var(--text-secondary, #666);
    padding: 0.25rem;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: color 0.2s;
}

.cart-close:hover {
    color: var(--danger, #dc3545);
}

/* Cart Items */
.cart-items {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
}

.cart-item {
    display: flex;
    gap: 1rem;
    padding: 1rem 0;
    border-bottom: 1px solid var(--border-color, #eee);
}

.cart-item:last-child {
    border-bottom: none;
}

.cart-item-image {
    width: 70px;
    height: 70px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;
    background: var(--bg-secondary, #f5f5f5);
}

.cart-item-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.cart-item-details {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.cart-item-name {
    font-weight: 500;
    color: var(--text-primary, #333);
    font-size: 0.9rem;
    line-height: 1.3;
}

.cart-item-price {
    color: var(--primary, #007bff);
    font-weight: 600;
    font-size: 0.95rem;
}

.cart-item-quantity {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-top: 0.5rem;
}

.cart-item-quantity button {
    width: 28px;
    height: 28px;
    border: 1px solid var(--border-color, #ddd);
    background: var(--bg-secondary, #f9f9f9);
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.cart-item-quantity button:hover {
    background: var(--primary, #007bff);
    color: white;
    border-color: var(--primary, #007bff);
}

.cart-item-quantity span {
    min-width: 30px;
    text-align: center;
    font-weight: 500;
}

.cart-item-remove {
    background: none;
    border: none;
    cursor: pointer;
    color: var(--text-secondary, #999);
    padding: 0.25rem;
    align-self: flex-start;
    transition: color 0.2s;
}

.cart-item-remove:hover {
    color: var(--danger, #dc3545);
}

/* Cart Empty State */
.cart-empty {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 2rem;
    text-align: center;
    color: var(--text-secondary, #666);
}

.cart-empty p {
    margin: 1rem 0;
    font-size: 1.1rem;
}

.btn-continue-shopping {
    background: var(--primary, #007bff);
    color: white;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 500;
    transition: background 0.2s;
}

.btn-continue-shopping:hover {
    background: var(--primary-dark, #0056b3);
}

/* Cart Footer */
.cart-footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--border-color, #eee);
    background: var(--bg-secondary, #f9f9f9);
}

.cart-subtotal {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    font-size: 1.1rem;
}

.cart-subtotal span:last-child {
    font-weight: 700;
    color: var(--primary, #007bff);
    font-size: 1.25rem;
}

.btn-checkout {
    display: block;
    width: 100%;
    background: var(--primary, #007bff);
    color: white;
    padding: 0.875rem;
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 600;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
    transition: background 0.2s;
}

.btn-checkout:hover {
    background: var(--primary-dark, #0056b3);
    color: white;
}

.btn-continue {
    display: block;
    width: 100%;
    background: transparent;
    color: var(--text-secondary, #666);
    padding: 0.75rem;
    border: 1px solid var(--border-color, #ddd);
    border-radius: 8px;
    font-size: 0.9rem;
    margin-top: 0.5rem;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-continue:hover {
    background: var(--bg-secondary, #f5f5f5);
    color: var(--text-primary, #333);
}

/* Mobile Responsive */
@media (max-width: 480px) {
    .cart-sidebar {
        max-width: 100%;
    }
}
</style>

<script>
// ============================================
// SISTEMA DE CARRINHO - MontaLoja
// ============================================

const CART_STORAGE_KEY = 'montaloja_cart_<?php echo htmlspecialchars($storeSlug); ?>';
let cart = [];

// Carregar carrinho do localStorage
function loadCart() {
    try {
        const stored = localStorage.getItem(CART_STORAGE_KEY);
        cart = stored ? JSON.parse(stored) : [];
    } catch (e) {
        cart = [];
    }
    updateCartUI();
}

// Salvar carrinho no localStorage
function saveCart() {
    try {
        localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(cart));
    } catch (e) {
        console.error('Erro ao salvar carrinho:', e);
    }
    updateCartUI();
}

// Adicionar item ao carrinho
function addToCart(productId, name, price, image, quantity = 1) {
    const cartItemId = productId.toString();
    const existingIndex = cart.findIndex(item => item.id === cartItemId);
    
    if (existingIndex >= 0) {
        cart[existingIndex].quantity += quantity;
    } else {
        cart.push({
            id: cartItemId,
            cartItemId: cartItemId,
            name: name,
            originalName: name,
            price: parseFloat(price) || 0,
            image: image || '',
            quantity: quantity,
            variations: {},
            variationsText: ''
        });
    }
    
    saveCart();
    
    if (typeof updateCartCount === 'function') {
        updateCartCount();
    }
    
    showCartToast('Produto adicionado ao carrinho!');
    
    // Abrir carrinho após adicionar
    setTimeout(() => openCart(), 300);
}

// Adicionar item com variações ao carrinho
function addToCartWithVariations(cartItemId, productId, name, price, image, quantity, variationsText, variationsData) {
    let displayName = name;
    if (variationsText) {
        displayName = name + ' (' + variationsText + ')';
    }
    
    const existingIndex = cart.findIndex(item => item.id === cartItemId);
    
    if (existingIndex >= 0) {
        cart[existingIndex].quantity += quantity;
    } else {
        cart.push({
            cartItemId: cartItemId,
            id: cartItemId,
            name: displayName,
            originalName: name,
            price: parseFloat(price) || 0,
            image: image || '',
            quantity: quantity,
            variations: variationsData,
            variationsText: variationsText
        });
    }
    
    saveCart();
    
    if (typeof updateCartCount === 'function') {
        updateCartCount();
    }
    
    showCartToast('Produto adicionado ao carrinho!');
    
    // Abrir carrinho após adicionar
    setTimeout(() => openCart(), 300);
}

// Remover item do carrinho
function removeFromCart(cartItemId) {
    cart = cart.filter(item => item.id !== cartItemId && item.cartItemId !== cartItemId);
    saveCart();
}

// Atualizar quantidade de um item
function updateCartItemQuantity(cartItemId, newQuantity) {
    const item = cart.find(item => item.id === cartItemId && item.cartItemId === cartItemId);
    if (item) {
        if (newQuantity <= 0) {
            removeFromCart(cartItemId);
        } else {
            item.quantity = newQuantity;
            saveCart();
        }
    }
}

// Incrementar quantidade
function incrementCartItem(cartItemId) {
    const item = cart.find(item => item.id === cartItemId && item.cartItemId === cartItemId);
    if (item) {
        item.quantity++;
        saveCart();
    }
}

// Decrementar quantidade
function decrementCartItem(cartItemId) {
    const item = cart.find(item => item.id === cartItemId && item.cartItemId === cartItemId);
    if (item) {
        if (item.quantity > 1) {
            item.quantity--;
            saveCart();
        } else {
            removeFromCart(cartItemId);
        }
    }
}

// Calcular subtotal do carrinho
function getCartSubtotal() {
    return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
}

// Obter quantidade total de itens
function getCartItemCount() {
    return cart.reduce((total, item) => total + item.quantity, 0);
}

// Atualizar UI do carrinho
function updateCartUI() {
    const cartItems = document.getElementById('cartItems');
    const cartEmpty = document.getElementById('cartEmpty');
    const cartFooter = document.getElementById('cartFooter');
    const cartSubtotal = document.getElementById('cartSubtotal');
    
    if (!cartItems) return;
    
    if (cart.length === 0) {
        cartItems.style.display = 'none';
        if (cartEmpty) cartEmpty.style.display = 'flex';
        if (cartFooter) cartFooter.style.display = 'none';
    } else {
        cartItems.style.display = 'block';
        if (cartEmpty) cartEmpty.style.display = 'none';
        if (cartFooter) cartFooter.style.display = 'block';
        
        cartItems.innerHTML = cart.map(item => `
            <div class="cart-item">
                <div class="cart-item-image">
                    <img src="${item.image || '/assets/images/no-image.png'}" alt="${escapeHtml(item.name)}" onerror="this.src='/assets/images/no-image.png'">
                </div>
                <div class="cart-item-details">
                    <div class="cart-item-name">${escapeHtml(item.name)}</div>
                    <div class="cart-item-price">R$ ${formatPrice(item.price)}</div>
                    <div class="cart-item-quantity">
                        <button onclick="decrementCartItem('${item.id}')">
                            <iconify-icon icon="solar:minus-bold"></iconify-icon>
                        </button>
                        <span>${item.quantity}</span>
                        <button onclick="incrementCartItem('${item.id}')">
                            <iconify-icon icon="solar:add-bold"></iconify-icon>
                        </button>
                    </div>
                </div>
                <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Remover">
                    <iconify-icon icon="solar:trash-bin-minimalistic-bold" style="font-size: 1.2rem;"></iconify-icon>
                </button>
            </div>
        `).join('');
        
        if (cartSubtotal) {
            cartSubtotal.textContent = 'R$ ' + formatPrice(getCartSubtotal());
        }
    }
    
    updateCartCount();
}

// Atualizar contador do carrinho no header
function updateCartCount() {
    const count = getCartItemCount();
    const badges = document.querySelectorAll('.cart-count, .cart-btn .badge');
    
    badges.forEach(badge => {
        if (count > 0) {
            badge.textContent = count > 99 ? '99+' : count;
            badge.style.display = 'flex';
        } else {
            badge.style.display = 'none';
        }
    });
}

// Abrir carrinho sidebar
function openCart() {
    const overlay = document.getElementById('cartOverlay');
    const sidebar = document.getElementById('cartSidebar');
    
    if (overlay) overlay.classList.add('active');
    if (sidebar) sidebar.classList.add('active');
    
    document.body.style.overflow = 'hidden';
}

// Fechar carrinho sidebar
function closeCart() {
    const overlay = document.getElementById('cartOverlay');
    const sidebar = document.getElementById('cartSidebar');
    
    if (overlay) overlay.classList.remove('active');
    if (sidebar) sidebar.classList.remove('active');
    
    document.body.style.overflow = '';
}

// Limpar carrinho
function clearCart() {
    cart = [];
    saveCart();
}

// Helpers
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatPrice(value) {
    return parseFloat(value).toLocaleString('pt-BR', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

function showCartToast(message) {
    // Usar toast existente se disponível
    if (typeof showToast === 'function') {
        showToast(message, 'success');
    } else {
        const toast = document.getElementById('toast');
        if (toast) {
            toast.textContent = message;
            toast.className = 'toast show success';
            setTimeout(() => toast.classList.remove('show'), 3000);
        }
    }
}

// Fechar carrinho ao clicar fora
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeCart();
    }
});

// Carregar carrinho ao iniciar
document.addEventListener('DOMContentLoaded', function() {
    loadCart();
});

// Carregar imediatamente se DOM já estiver pronto
if (document.readyState !== 'loading') {
    loadCart();
}
</script>
