<?php
/**
 * Header Component - MontaLoja Modern Theme
 * Requer variáveis: $store, $storeName, $logo, $menuItems, $logoType, $logoImage, $logoText, $baseUrl
 */

// Montar URL base da loja se não definida
if (!isset($baseUrl) || empty($baseUrl)) {
    if (function_exists('get_store_url') && !empty($store)) {
        // Usa a função centralizada que respeita domínio personalizado, subdomínio ou path
        $baseUrl = get_store_url($store);
    } else {
        // Fallback: detecta o domínio atual da requisição dinamicamente
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
        $currentHost = $_SERVER['HTTP_HOST'] ?? '';
        // Verifica se já estamos no domínio da loja (custom domain ou subdomínio)
        $storeSlugFallback = $store['slug'] ?? $store['subdomain'] ?? '';
        $baseUrl = $protocol . $currentHost;
        // Se não estamos em custom domain nem subdomínio, usa path /loja/slug
        $subdomain = $store['subdomain'] ?? '';
        $customDomain = $store['custom_domain'] ?? '';
        $domainType = $store['domain_type'] ?? 'subdomain';
        if ($domainType !== 'custom' && strpos($currentHost, $subdomain . '.') !== 0) {
            $baseUrl = $protocol . $currentHost . '/loja/' . $storeSlugFallback;
        }
    }
}

// Valores padrão se não definidos
$menuItems = $menuItems ?? [
    ['name' => 'Início', 'link' => $baseUrl, 'icon' => 'solar:home-2-bold'],
    ['name' => 'Produtos', 'link' => $baseUrl . '#produtos', 'icon' => 'solar:bag-3-bold'],
    ['name' => 'Ofertas', 'link' => $baseUrl . '#ofertas', 'icon' => 'solar:tag-price-bold'],
    ['name' => 'Contato', 'link' => $baseUrl . '#contato', 'icon' => 'solar:phone-bold']
];

$logoType = $logoType ?? 'text';
$logoImage = $logoImage ?? ($logo ?? '');
$logoText = $logoText ?? ($storeName ?? 'Loja');

// Verificar se cliente está logado
$isCustomerLoggedIn = isset($_SESSION['customer_id']) && isset($_SESSION['customer_store_id']) && $_SESSION['customer_store_id'] == ($currentStoreId ?? null);
$customerName = $_SESSION['customer_name'] ?? '';
$customerFirstName = explode(' ', $customerName)[0] ?? 'Cliente';
?>

<!-- HEADER SUPERIOR -->
<header class="top-header sticky-header">
    <div class="header-inner">
        <a href="<?php echo htmlspecialchars($baseUrl); ?>" class="brand">
            <?php if ($logoType === 'image' || $logoType === 'both'): ?>
                <?php if (!empty($logoImage)): ?>
                    <div class="brand-logo has-image">
                        <img src="<?php echo htmlspecialchars($logoImage); ?>" alt="<?php echo htmlspecialchars($logoText); ?>">
                    </div>
                <?php else: ?>
                    <div class="brand-logo">
                        <?php echo strtoupper(substr($logoText, 0, 1)); ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>

            <?php if ($logoType === 'text'): ?>
                <div class="brand-logo">
                    <?php echo strtoupper(substr($logoText, 0, 1)); ?>
                </div>
            <?php endif; ?>

            <?php if ($logoType === 'text' || $logoType === 'both'): ?>
                <span class="brand-name"><?php echo htmlspecialchars($logoText); ?></span>
            <?php endif; ?>
        </a>

        <nav class="nav-menu">
            <?php foreach ($menuItems as $index => $item): 
                $menuLink = $item['link'] ?? '#';
                // Se o link começa com # (âncora), prefixar com baseUrl para funcionar em todas as páginas
                if ($menuLink === '#') {
                    $menuLink = $baseUrl;
                } elseif (strpos($menuLink, '#') === 0) {
                    $menuLink = rtrim($baseUrl, '/') . '/' . $menuLink;
                }
            ?>
            <a href="<?php echo htmlspecialchars($menuLink); ?>" class="nav-link<?php echo $index === 0 ? ' active' : ''; ?>">
                <iconify-icon icon="<?php echo htmlspecialchars($item['icon'] ?? 'solar:home-2-bold'); ?>"></iconify-icon>
                <?php echo htmlspecialchars($item['name'] ?? 'Item'); ?>
            </a>
            <?php endforeach; ?>
        </nav>

        <div class="search-bar">
            <iconify-icon icon="solar:magnifer-bold" class="search-icon"></iconify-icon>
            <input type="text" placeholder="Buscar produtos..." aria-label="Buscar produtos">
        </div>

        <button class="mobile-menu-toggle" onclick="openMobileNav()" aria-label="Abrir menu">
            <iconify-icon icon="solar:hamburger-menu-bold"></iconify-icon>
        </button>

        <div class="header-actions">
            <a href="<?php echo htmlspecialchars($baseUrl); ?>/favoritos" class="action-btn wishlist-btn" title="Favoritos">
                <iconify-icon icon="solar:heart-outline" style="font-size: 1.3rem;"></iconify-icon>
                <span class="badge wishlist-count" style="display: none;">0</span>
            </a>
            <button class="action-btn cart-btn" onclick="openCart()" title="Carrinho">
                <iconify-icon icon="solar:bag-3-outline" style="font-size: 1.3rem;"></iconify-icon>
                <span class="badge cart-count" style="display: none;">0</span>
            </button>

            <?php if ($isCustomerLoggedIn): ?>
            <!-- Menu do Cliente Logado -->
            <div class="user-dropdown-container">
                <button class="user-btn logged-in" onclick="toggleUserDropdown()">
                    <div class="user-avatar">
                        <iconify-icon icon="solar:user-check-bold"></iconify-icon>
                    </div>
                    <span><?php echo htmlspecialchars($customerFirstName); ?></span>
                    <iconify-icon icon="solar:alt-arrow-down-bold" class="dropdown-arrow"></iconify-icon>
                </button>
                <div class="user-dropdown" id="userDropdown">
                    <div class="dropdown-header">
                        <div class="dropdown-avatar">
                            <iconify-icon icon="solar:user-bold"></iconify-icon>
                        </div>
                        <div class="dropdown-info">
                            <strong><?php echo htmlspecialchars($customerName); ?></strong>
                            <span><?php echo htmlspecialchars($_SESSION['customer_email'] ?? ''); ?></span>
                        </div>
                    </div>
                    <div class="dropdown-menu">
                        <a href="<?php echo htmlspecialchars($baseUrl); ?>/minha-conta" class="dropdown-item">
                            <iconify-icon icon="solar:user-circle-bold"></iconify-icon>
                            Minha Conta
                        </a>
                        <a href="<?php echo htmlspecialchars($baseUrl); ?>/meus-pedidos" class="dropdown-item">
                            <iconify-icon icon="solar:bag-4-bold"></iconify-icon>
                            Meus Pedidos
                        </a>
                        <a href="<?php echo htmlspecialchars($baseUrl); ?>/meus-enderecos" class="dropdown-item">
                            <iconify-icon icon="solar:map-point-bold"></iconify-icon>
                            Meus Endereços
                        </a>
                        <a href="<?php echo htmlspecialchars($baseUrl); ?>/favoritos" class="dropdown-item">
                            <iconify-icon icon="solar:heart-bold"></iconify-icon>
                            Favoritos
                        </a>
                        <div class="dropdown-divider"></div>
                        <a href="<?php echo htmlspecialchars($baseUrl); ?>/meus-dados" class="dropdown-item">
                            <iconify-icon icon="solar:settings-bold"></iconify-icon>
                            Configurações
                        </a>
                        <a href="<?php echo htmlspecialchars($baseUrl); ?>/sair" class="dropdown-item logout">
                            <iconify-icon icon="solar:logout-2-bold"></iconify-icon>
                            Sair
                        </a>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <!-- Botão de Login -->
            <a href="<?php echo htmlspecialchars($baseUrl); ?>/entrar" class="user-btn">
                <div class="user-avatar">
                    <iconify-icon icon="solar:user-bold"></iconify-icon>
                </div>
                <span>Entrar</span>
            </a>
            <?php endif; ?>
        </div>
    </div>
</header>

<!-- Barra de Busca Mobile -->
<div class="mobile-search-bar">
    <iconify-icon icon="solar:magnifer-bold" class="search-icon"></iconify-icon>
    <input type="text" placeholder="Buscar produtos..." aria-label="Buscar produtos">
</div>

<!-- Mobile Navigation Overlay -->
<div class="mobile-nav-overlay" id="mobileNavOverlay" onclick="closeMobileNav()"></div>

<!-- Mobile Navigation Drawer -->
<nav class="mobile-nav" id="mobileNav">
    <div class="mobile-nav-header">
        <a href="<?php echo htmlspecialchars($baseUrl); ?>" class="brand">
            <?php if (!empty($logoImage)): ?>
                <div class="brand-logo has-image">
                    <img src="<?php echo htmlspecialchars($logoImage); ?>" alt="<?php echo htmlspecialchars($logoText); ?>">
                </div>
            <?php else: ?>
                <div class="brand-logo">
                    <?php echo strtoupper(substr($logoText, 0, 1)); ?>
                </div>
            <?php endif; ?>
        </a>
        <button class="mobile-nav-close" onclick="closeMobileNav()">
            <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
        </button>
    </div>

    <?php if ($isCustomerLoggedIn): ?>
    <!-- Mobile User Info -->
    <div class="mobile-user-info">
        <div class="mobile-user-avatar">
            <iconify-icon icon="solar:user-bold"></iconify-icon>
        </div>
        <div class="mobile-user-details">
            <strong><?php echo htmlspecialchars($customerFirstName); ?></strong>
            <a href="<?php echo htmlspecialchars($baseUrl); ?>/minha-conta">Ver minha conta</a>
        </div>
    </div>
    <?php endif; ?>

    <div class="mobile-nav-menu">
        <?php foreach ($menuItems as $index => $item): 
            $mobileMenuLink = $item['link'] ?? '#';
            // Se o link começa com # (âncora), prefixar com baseUrl
            if ($mobileMenuLink === '#') {
                $mobileMenuLink = $baseUrl;
            } elseif (strpos($mobileMenuLink, '#') === 0) {
                $mobileMenuLink = rtrim($baseUrl, '/') . '/' . $mobileMenuLink;
            }
        ?>
        <a href="<?php echo htmlspecialchars($mobileMenuLink); ?>" class="mobile-nav-link<?php echo $index === 0 ? ' active' : ''; ?>">
            <iconify-icon icon="<?php echo htmlspecialchars($item['icon'] ?? 'solar:home-2-bold'); ?>"></iconify-icon>
            <?php echo htmlspecialchars($item['name'] ?? 'Item'); ?>
        </a>
        <?php endforeach; ?>

        <div class="mobile-nav-divider"></div>

        <?php if ($isCustomerLoggedIn): ?>
        <a href="<?php echo htmlspecialchars($baseUrl); ?>/minha-conta" class="mobile-nav-link">
            <iconify-icon icon="solar:user-circle-bold"></iconify-icon>
            Minha Conta
        </a>
        <a href="<?php echo htmlspecialchars($baseUrl); ?>/meus-pedidos" class="mobile-nav-link">
            <iconify-icon icon="solar:bag-4-bold"></iconify-icon>
            Meus Pedidos
        </a>
        <a href="<?php echo htmlspecialchars($baseUrl); ?>/favoritos" class="mobile-nav-link">
            <iconify-icon icon="solar:heart-bold"></iconify-icon>
            Favoritos
        </a>
        <a href="<?php echo htmlspecialchars($baseUrl); ?>/sair" class="mobile-nav-link logout">
            <iconify-icon icon="solar:logout-2-bold"></iconify-icon>
            Sair
        </a>
        <?php else: ?>
        <a href="<?php echo htmlspecialchars($baseUrl); ?>/entrar" class="mobile-nav-link">
            <iconify-icon icon="solar:login-2-bold"></iconify-icon>
            Entrar
        </a>
        <a href="<?php echo htmlspecialchars($baseUrl); ?>/registrar" class="mobile-nav-link">
            <iconify-icon icon="solar:user-plus-bold"></iconify-icon>
            Criar Conta
        </a>
        <?php endif; ?>
    </div>
</nav>

<style>
/* User Dropdown Styles */
.user-dropdown-container {
    position: relative;
}

.user-btn.logged-in {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    background: var(--primary-soft);
    color: var(--primary);
    border: none;
    border-radius: 50px;
    cursor: pointer;
    font-weight: 600;
    font-size: 0.9rem;
    transition: all 0.2s;
}

.user-btn.logged-in:hover {
    background: var(--primary-soft);
}

.user-btn.logged-in .user-avatar {
    width: 28px;
    height: 28px;
    background: var(--primary);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.user-btn.logged-in .user-avatar iconify-icon {
    color: white;
}

.dropdown-arrow {
    font-size: 14px;
    transition: transform 0.2s;
}

.user-dropdown-container.active .dropdown-arrow {
    transform: rotate(180deg);
}

.user-dropdown {
    position: absolute;
    top: calc(100% + 12px);
    right: 0;
    width: 280px;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    opacity: 0;
    visibility: hidden;
    transform: translateY(-10px);
    transition: all 0.2s;
    z-index: 1000;
}

.user-dropdown-container.active .user-dropdown {
    opacity: 1;
    visibility: visible;
    transform: translateY(0);
}

.dropdown-header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px;
    border-bottom: 1px solid var(--border);
}

.dropdown-avatar {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: var(--primary);
    display: flex;
    align-items: center;
    justify-content: center;
}

.dropdown-avatar iconify-icon {
    font-size: 22px;
    color: white;
}

.dropdown-info {
    flex: 1;
    min-width: 0;
}

.dropdown-info strong {
    display: block;
    font-size: 0.95rem;
    color: var(--text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.dropdown-info span {
    display: block;
    font-size: 0.8rem;
    color: var(--text-muted);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.dropdown-menu {
    padding: 8px;
}

.dropdown-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    color: var(--text);
    text-decoration: none;
    border-radius: var(--radius);
    font-weight: 500;
    transition: all 0.2s;
}

.dropdown-item:hover {
    background: var(--surface-hover);
    color: var(--primary);
}

.dropdown-item iconify-icon {
    font-size: 20px;
    color: var(--text-muted);
}

.dropdown-item:hover iconify-icon {
    color: var(--primary);
}

.dropdown-item.logout {
    color: #EF4444;
}

.dropdown-item.logout iconify-icon {
    color: #EF4444;
}

.dropdown-item.logout:hover {
    background: rgba(239, 68, 68, 0.1);
}

.dropdown-divider {
    height: 1px;
    background: var(--border);
    margin: 8px 0;
}

/* Mobile User Info */
.mobile-user-info {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 20px;
    background: var(--surface-hover);
    margin: 0 12px 12px;
    border-radius: var(--radius);
}

.mobile-user-avatar {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: var(--primary);
    display: flex;
    align-items: center;
    justify-content: center;
}

.mobile-user-avatar iconify-icon {
    font-size: 22px;
    color: white;
}

.mobile-user-details strong {
    display: block;
    font-size: 1rem;
    color: var(--text);
}

.mobile-user-details a {
    font-size: 0.85rem;
    color: var(--primary);
    text-decoration: none;
}

.mobile-nav-divider {
    height: 1px;
    background: var(--border);
    margin: 12px 20px;
}

.mobile-nav-link.logout {
    color: #EF4444;
}

.mobile-nav-link.logout iconify-icon {
    color: #EF4444;
}

@media (max-width: 768px) {
    .user-btn.logged-in span {
        display: none;
    }

    .dropdown-arrow {
        display: none;
    }

    .user-btn.logged-in {
        padding: 8px;
        border-radius: 50%;
    }
}
</style>

<script>
function toggleUserDropdown() {
    const container = document.querySelector('.user-dropdown-container');
    container.classList.toggle('active');
}

// Fechar dropdown ao clicar fora
document.addEventListener('click', function(e) {
    const container = document.querySelector('.user-dropdown-container');
    if (container && !container.contains(e.target)) {
        container.classList.remove('active');
    }
});
</script>

<!-- Script para atualizar badge de favoritos -->
<script>
(function() {
    const storeSlug = '<?php echo htmlspecialchars($storeSlug ?? $store["slug"] ?? ""); ?>';
    const favoritesKey = `montaloja_favorites_${storeSlug}`;
    
    function updateWishlistBadge() {
        try {
            const saved = localStorage.getItem(favoritesKey);
            const favorites = saved ? JSON.parse(saved) : [];
            const count = favorites.length;
            const badges = document.querySelectorAll('.wishlist-count');
            
            badges.forEach(badge => {
                if (count > 0) {
                    badge.textContent = count > 99 ? '99+' : count;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }
            });
        } catch (e) {
            console.error('Erro ao atualizar badge de favoritos:', e);
        }
    }
    
    // Atualizar ao carregar
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', updateWishlistBadge);
    } else {
        updateWishlistBadge();
    }
    
    // Atualizar quando localStorage mudar (em outras abas)
    window.addEventListener('storage', function(e) {
        if (e.key === favoritesKey) {
            updateWishlistBadge();
        }
    });
    
    // Expor função globalmente
    window.updateWishlistBadge = updateWishlistBadge;
})();
</script>

<!-- Script para Menu Mobile -->
<script>
function openMobileNav() {
    document.getElementById('mobileNav').classList.add('active');
    document.getElementById('mobileNavOverlay').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function closeMobileNav() {
    document.getElementById('mobileNav').classList.remove('active');
    document.getElementById('mobileNavOverlay').classList.remove('active');
    document.body.style.overflow = '';
}
</script>
