<?php
/**
 * Página de Favoritos - MontaLoja
 * Lista os produtos salvos como favoritos (localStorage + banco de dados)
 */

require_once __DIR__ . '/includes/store-config.php';

$isLoggedIn = isCustomerLoggedIn();
$customer = $isLoggedIn ? getLoggedCustomer() : null;
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Favoritos - <?php echo htmlspecialchars($storeName); ?></title>
<meta name="description" content="Meus produtos favoritos em <?php echo htmlspecialchars($storeName); ?>">
<meta name="theme-color" content="<?php echo $primaryColor; ?>">
<?php if (!empty($faviconUrl)): ?>
<link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($faviconUrl); ?>">
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<style>
/* Dynamic Color Variables from Store Settings */
:root {
    --primary: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>;
    --primary-soft: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>14;
    --primary-hover: <?php echo htmlspecialchars($customSettings['colors']['secondary'] ?? $primaryColor ?? '#1D4ED8'); ?>;
    --accent: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>;
    --accent-soft: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>1A;
    --bg: <?php echo htmlspecialchars($bgColor ?? '#FAFBFC'); ?>;
    --bg-white: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --surface: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --text: <?php echo htmlspecialchars($textColor ?? '#111827'); ?>;
    --text-secondary: <?php echo htmlspecialchars($textSecondary ?? '#6B7280'); ?>;
}

:root {
    --primary: <?php echo $primaryColor; ?>;
    --primary-hover: <?php echo $primaryColor; ?>dd;
    --primary-soft: <?php echo $primaryColor; ?>15;
    --primary-rgb: <?php 
        $hex = ltrim($primaryColor, '#');
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
        echo "$r, $g, $b";
    ?>;
    --danger: #EF4444;
}

/* Hero Section */
.favorites-hero {
    background: linear-gradient(135deg, var(--primary-soft) 0%, rgba(var(--primary-rgb), 0.15) 50%, rgba(var(--primary-rgb), 0.1) 100%);
    padding: 48px 24px;
    margin: -24px -24px 32px -24px;
    text-align: center;
    position: relative;
    overflow: hidden;
}

.favorites-hero::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.3) 0%, transparent 60%);
    animation: shimmer 15s infinite linear;
}

@keyframes shimmer {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.hero-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, var(--primary), var(--primary-hover));
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
    box-shadow: 0 10px 40px rgba(var(--primary-rgb), 0.3);
    position: relative;
    z-index: 1;
}

.hero-icon iconify-icon {
    font-size: 40px;
    color: white;
}

.hero-title {
    font-size: 2.5rem;
    font-weight: 800;
    color: var(--text);
    margin-bottom: 8px;
    position: relative;
    z-index: 1;
}

.hero-subtitle {
    color: var(--text-secondary);
    font-size: 1.1rem;
    position: relative;
    z-index: 1;
}

.hero-count {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: white;
    padding: 10px 20px;
    border-radius: 50px;
    margin-top: 16px;
    font-weight: 600;
    color: var(--primary);
    box-shadow: 0 4px 15px rgba(0,0,0,0.08);
    position: relative;
    z-index: 1;
}

/* Login Banner */
.login-banner {
    display: flex;
    align-items: center;
    gap: 16px;
    background: linear-gradient(135deg, var(--primary-soft), rgba(var(--primary-rgb), 0.08));
    border: 1px solid rgba(var(--primary-rgb), 0.2);
    border-radius: var(--radius-lg);
    padding: 16px 20px;
    margin-bottom: 24px;
}

.login-banner iconify-icon {
    font-size: 24px;
    color: var(--primary);
    flex-shrink: 0;
}

.login-banner-content {
    flex: 1;
}

.login-banner-content strong {
    display: block;
    color: var(--text);
    margin-bottom: 2px;
}

.login-banner-content span {
    font-size: 0.9rem;
    color: var(--text-secondary);
}

.login-banner .btn-login {
    padding: 10px 20px;
    background: var(--primary);
    color: white;
    border-radius: var(--radius);
    text-decoration: none;
    font-weight: 600;
    font-size: 0.9rem;
    white-space: nowrap;
    transition: all 0.2s;
}

.login-banner .btn-login:hover {
    background: var(--primary-hover);
    transform: translateY(-2px);
}

/* Synced Badge */
.synced-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: rgba(16, 185, 129, 0.1);
    color: #10B981;
    padding: 6px 12px;
    border-radius: 50px;
    font-size: 0.8rem;
    font-weight: 600;
    margin-left: 12px;
}

/* Floating hearts */
.floating-hearts {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
    overflow: hidden;
}

.floating-heart {
    position: absolute;
    color: rgba(var(--primary-rgb), 0.15);
    animation: float 20s infinite;
}

.floating-heart:nth-child(1) { left: 5%; animation-delay: 0s; font-size: 24px; }
.floating-heart:nth-child(2) { left: 15%; animation-delay: 3s; font-size: 32px; }
.floating-heart:nth-child(3) { left: 30%; animation-delay: 6s; font-size: 20px; }
.floating-heart:nth-child(4) { left: 50%; animation-delay: 9s; font-size: 28px; }
.floating-heart:nth-child(5) { left: 70%; animation-delay: 12s; font-size: 22px; }
.floating-heart:nth-child(6) { left: 85%; animation-delay: 15s; font-size: 30px; }
.floating-heart:nth-child(7) { left: 95%; animation-delay: 18s; font-size: 26px; }

@keyframes float {
    0% { transform: translateY(100%) rotate(0deg); opacity: 0; }
    10% { opacity: 1; }
    90% { opacity: 1; }
    100% { transform: translateY(-100vh) rotate(360deg); opacity: 0; }
}

/* Toolbar */
.favorites-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 16px;
}

.toolbar-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.view-toggle {
    display: flex;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    overflow: hidden;
}

.view-btn {
    padding: 10px 14px;
    background: transparent;
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.2s;
}

.view-btn.active {
    background: var(--primary);
    color: white;
}

.view-btn:hover:not(.active) {
    background: var(--surface-hover);
}

.btn-clear-all {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 10px 16px;
    background: transparent;
    border: 1px solid var(--danger);
    color: var(--danger);
    border-radius: var(--radius);
    font-weight: 500;
    font-size: 0.9rem;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-clear-all:hover {
    background: var(--danger);
    color: white;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: linear-gradient(135deg, #fafafa 0%, #f5f5f5 100%);
    border-radius: 24px;
    border: 2px dashed var(--border);
}

.empty-illustration {
    width: 200px;
    height: 200px;
    margin: 0 auto 24px;
    position: relative;
}

.empty-circle {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: linear-gradient(135deg, var(--primary-soft) 0%, rgba(var(--primary-rgb), 0.1) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

.empty-circle::after {
    content: '';
    position: absolute;
    width: 110%;
    height: 110%;
    border-radius: 50%;
    border: 2px dashed rgba(var(--primary-rgb), 0.2);
    animation: spin 20s linear infinite;
}

@keyframes spin {
    100% { transform: rotate(360deg); }
}

.empty-circle iconify-icon {
    font-size: 80px;
    color: var(--primary);
    opacity: 0.8;
}

.empty-title {
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--text);
    margin-bottom: 12px;
}

.empty-text {
    color: var(--text-secondary);
    margin-bottom: 32px;
    font-size: 1.05rem;
    max-width: 400px;
    margin-left: auto;
    margin-right: auto;
}

.btn-explore {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 16px 32px;
    background: linear-gradient(135deg, var(--primary), var(--primary-hover));
    color: white;
    font-weight: 700;
    font-size: 1rem;
    border-radius: 50px;
    text-decoration: none;
    transition: all 0.3s;
    box-shadow: 0 8px 25px rgba(var(--primary-rgb), 0.3);
}

.btn-explore:hover {
    transform: translateY(-3px);
    box-shadow: 0 12px 35px rgba(var(--primary-rgb), 0.4);
}

/* Products Grid */
.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 24px;
}

.products-grid.list-view {
    grid-template-columns: 1fr;
    gap: 16px;
}

/* Product Card */
.product-card {
    background: var(--surface);
    border-radius: 20px;
    border: 1px solid var(--border);
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
}

.product-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 20px 50px rgba(0,0,0,0.12);
    border-color: transparent;
}

.product-image-wrapper {
    position: relative;
    overflow: hidden;
}

.product-image {
    aspect-ratio: 1;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    position: relative;
    overflow: hidden;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.product-card:hover .product-image img {
    transform: scale(1.1);
}

.product-image .placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ccc;
    font-size: 64px;
}

.image-overlay {
    position: absolute;
    inset: 0;
    background: linear-gradient(to top, rgba(0,0,0,0.4) 0%, transparent 50%);
    opacity: 0;
    transition: opacity 0.3s;
}

.product-card:hover .image-overlay {
    opacity: 1;
}

.favorite-badge {
    position: absolute;
    top: 12px;
    left: 12px;
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    background: rgba(var(--primary-rgb), 0.9);
    backdrop-filter: blur(10px);
    border-radius: 50px;
    color: white;
    font-size: 0.75rem;
    font-weight: 600;
}

.remove-btn {
    position: absolute;
    top: 12px;
    right: 12px;
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: white;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    color: var(--danger);
    opacity: 0;
    transform: scale(0.8);
}

.product-card:hover .remove-btn {
    opacity: 1;
    transform: scale(1);
}

.remove-btn:hover {
    background: var(--danger);
    color: white;
    transform: scale(1.15) !important;
}

.quick-actions {
    position: absolute;
    bottom: 12px;
    left: 12px;
    right: 12px;
    display: flex;
    gap: 8px;
    opacity: 0;
    transform: translateY(10px);
    transition: all 0.3s;
}

.product-card:hover .quick-actions {
    opacity: 1;
    transform: translateY(0);
}

.quick-btn {
    flex: 1;
    padding: 12px;
    background: white;
    border: none;
    border-radius: 12px;
    font-weight: 600;
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    color: var(--text);
    text-decoration: none;
}

.quick-btn:hover {
    background: var(--primary);
    color: white;
}

.quick-btn.view-btn-action {
    flex: 0 0 48px;
}

.product-info {
    padding: 20px;
}

.product-name {
    font-weight: 700;
    font-size: 1.05rem;
    color: var(--text);
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.4;
}

.product-meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}

.product-price {
    font-size: 1.5rem;
    font-weight: 800;
    color: var(--primary);
}

.product-date {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 0.8rem;
    color: var(--text-secondary);
}

/* List View */
.products-grid.list-view .product-card {
    display: flex;
    flex-direction: row;
    border-radius: 16px;
}

.products-grid.list-view .product-image-wrapper {
    flex: 0 0 180px;
}

.products-grid.list-view .product-image {
    aspect-ratio: 1;
    height: 100%;
}

.products-grid.list-view .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 24px;
}

.products-grid.list-view .product-name {
    font-size: 1.2rem;
}

.products-grid.list-view .product-meta {
    margin-top: auto;
    padding-top: 16px;
}

.products-grid.list-view .product-actions-list {
    display: flex;
    gap: 12px;
    margin-top: 16px;
}

.products-grid.list-view .btn-action {
    padding: 12px 20px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 0.9rem;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
}

.products-grid.list-view .btn-cart {
    background: var(--primary);
    color: white;
    border: none;
}

.products-grid.list-view .btn-cart:hover {
    background: var(--primary-hover);
}

.products-grid.list-view .btn-view-product {
    background: var(--surface-hover);
    color: var(--text);
    border: 1px solid var(--border);
}

.products-grid.list-view .btn-view-product:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.products-grid.list-view .btn-remove {
    background: transparent;
    color: var(--danger);
    border: 1px solid var(--danger);
    margin-left: auto;
}

.products-grid.list-view .btn-remove:hover {
    background: var(--danger);
    color: white;
}

.products-grid.list-view .quick-actions,
.products-grid.list-view .image-overlay,
.products-grid.list-view .remove-btn {
    display: none;
}

/* Modal */
.confirm-modal {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s;
    backdrop-filter: blur(4px);
    padding: 20px;
}

.confirm-modal.show {
    opacity: 1;
    visibility: visible;
}

.confirm-content {
    background: white;
    padding: 32px;
    border-radius: 20px;
    text-align: center;
    max-width: 400px;
    width: 100%;
    transform: scale(0.9);
    transition: transform 0.3s;
}

.confirm-modal.show .confirm-content {
    transform: scale(1);
}

.confirm-icon {
    width: 70px;
    height: 70px;
    background: rgba(239, 68, 68, 0.1);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
}

.confirm-icon iconify-icon {
    font-size: 36px;
    color: var(--danger);
}

.confirm-title {
    font-size: 1.4rem;
    font-weight: 700;
    color: var(--text);
    margin-bottom: 8px;
}

.confirm-text {
    color: var(--text-secondary);
    margin-bottom: 24px;
}

.confirm-buttons {
    display: flex;
    gap: 12px;
}

.confirm-btn {
    flex: 1;
    padding: 14px 20px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 0.95rem;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}

.confirm-btn.cancel {
    background: var(--surface-hover);
    color: var(--text);
}

.confirm-btn.cancel:hover {
    background: var(--bg);
}

.confirm-btn.danger {
    background: var(--danger);
    color: white;
}

.confirm-btn.danger:hover {
    background: #DC2626;
}

/* Toast */
.toast {
    position: fixed;
    bottom: 100px;
    left: 50%;
    transform: translateX(-50%) translateY(20px);
    background: var(--text);
    color: white;
    padding: 14px 24px;
    border-radius: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 10px;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s;
    z-index: 10000;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}

.toast.show {
    opacity: 1;
    visibility: visible;
    transform: translateX(-50%) translateY(0);
}

.toast.success { background: #10B981; }
.toast.info { background: var(--primary); }

/* Responsive - Tablets */
@media (max-width: 992px) {
    .favorites-hero { padding: 40px 20px; margin: -20px -20px 28px -20px; }
    .hero-title { font-size: 2rem; }
    .products-grid { grid-template-columns: repeat(3, 1fr); gap: 20px; }
}

/* Responsive - Mobile */
@media (max-width: 768px) {
    .favorites-hero { padding: 32px 16px; margin: -16px -16px 24px -16px; }
    .hero-title { font-size: 1.75rem; }
    .hero-subtitle { font-size: 1rem; }
    .hero-icon { width: 64px; height: 64px; }
    .hero-icon iconify-icon { font-size: 32px; }
    .hero-count { padding: 8px 16px; font-size: 0.9rem; }
    .login-banner { flex-direction: column; text-align: center; padding: 16px; gap: 12px; }
    .login-banner .btn-login { width: 100%; text-align: center; }
    .favorites-toolbar { flex-direction: column; align-items: stretch; gap: 12px; }
    .toolbar-left { justify-content: center; }
    .btn-clear-all { justify-content: center; }
    .products-grid { grid-template-columns: repeat(2, 1fr); gap: 12px; }
    .product-info { padding: 14px; }
    .product-name { font-size: 0.9rem; }
    .product-price { font-size: 1.2rem; }
    .product-meta { flex-direction: column; align-items: flex-start; gap: 6px; }
    .product-date { display: none; }
    .remove-btn { opacity: 1; transform: scale(1); width: 36px; height: 36px; }
    .quick-actions { display: none; }
    .products-grid.list-view { grid-template-columns: 1fr; }
    .products-grid.list-view .product-card { flex-direction: column; }
    .products-grid.list-view .product-image-wrapper { flex: none; }
    .products-grid.list-view .product-info { padding: 16px; }
    .products-grid.list-view .product-actions-list { flex-wrap: wrap; gap: 8px; }
    .products-grid.list-view .btn-action { padding: 10px 16px; font-size: 0.85rem; }
    .products-grid.list-view .btn-remove { margin-left: 0; flex: 1 1 100%; justify-content: center; }
    .empty-state { padding: 40px 16px; border-radius: 16px; }
    .empty-illustration { width: 150px; height: 150px; }
    .empty-circle iconify-icon { font-size: 60px; }
    .empty-title { font-size: 1.4rem; }
    .empty-text { font-size: 0.95rem; }
    .btn-explore { padding: 14px 28px; font-size: 0.95rem; }
    .confirm-content { padding: 24px; margin: 16px; }
    .confirm-icon { width: 60px; height: 60px; }
    .confirm-icon iconify-icon { font-size: 30px; }
    .confirm-title { font-size: 1.2rem; }
    .confirm-buttons { flex-direction: column-reverse; }
    .toast { left: 16px; right: 16px; transform: translateX(0) translateY(20px); bottom: 80px; }
    .toast.show { transform: translateX(0) translateY(0); }
}

/* Responsive - Mobile pequeno */
@media (max-width: 400px) {
    .favorites-hero { padding: 24px 12px; margin: -12px -12px 20px -12px; }
    .hero-title { font-size: 1.5rem; }
    .hero-icon { width: 56px; height: 56px; }
    .hero-icon iconify-icon { font-size: 28px; }
    .products-grid { grid-template-columns: 1fr; gap: 12px; }
    .product-card { border-radius: 14px; }
    .floating-hearts { display: none; }
    .synced-badge { display: none; }
}
</style>
</head>
<body>

<?php include __DIR__ . '/../../../includes/cart.php'; ?>

<?php include __DIR__ . '/includes/header.php'; ?>

<section class="favorites-hero">
    <div class="floating-hearts">
        <iconify-icon icon="solar:heart-bold" class="floating-heart"></iconify-icon>
        <iconify-icon icon="solar:heart-bold" class="floating-heart"></iconify-icon>
        <iconify-icon icon="solar:heart-bold" class="floating-heart"></iconify-icon>
        <iconify-icon icon="solar:heart-bold" class="floating-heart"></iconify-icon>
        <iconify-icon icon="solar:heart-bold" class="floating-heart"></iconify-icon>
        <iconify-icon icon="solar:heart-bold" class="floating-heart"></iconify-icon>
        <iconify-icon icon="solar:heart-bold" class="floating-heart"></iconify-icon>
    </div>
    <div class="hero-icon">
        <iconify-icon icon="solar:heart-bold"></iconify-icon>
    </div>
    <h1 class="hero-title">Meus Favoritos</h1>
    <p class="hero-subtitle">Seus produtos preferidos em um só lugar</p>
    <div class="hero-count" id="hero-count">
        <iconify-icon icon="solar:heart-bold" width="18"></iconify-icon>
        <span id="count-text">Carregando...</span>
        <?php if ($isLoggedIn): ?>
        <span class="synced-badge" id="synced-badge" style="display: none;">
            <iconify-icon icon="solar:cloud-check-bold" width="14"></iconify-icon>
            Sincronizado
        </span>
        <?php endif; ?>
    </div>
</section>

<main class="main-content">
    <?php if (!$isLoggedIn): ?>
    <div class="login-banner" id="login-banner">
        <iconify-icon icon="solar:user-circle-bold"></iconify-icon>
        <div class="login-banner-content">
            <strong>Salve seus favoritos na sua conta!</strong>
            <span>Faça login para sincronizar seus favoritos em qualquer dispositivo.</span>
        </div>
        <a href="<?php echo storeUrl('entrar?redirect=favoritos'); ?>" class="btn-login">Entrar</a>
    </div>
    <?php endif; ?>
    
    <div class="favorites-toolbar" id="toolbar" style="display: none;">
        <div class="toolbar-left">
            <div class="view-toggle">
                <button class="view-btn active" data-view="grid" title="Grade">
                    <iconify-icon icon="solar:widget-bold" width="20"></iconify-icon>
                </button>
                <button class="view-btn" data-view="list" title="Lista">
                    <iconify-icon icon="solar:list-bold" width="20"></iconify-icon>
                </button>
            </div>
        </div>
        <button class="btn-clear-all" onclick="showClearAllModal()">
            <iconify-icon icon="solar:trash-bin-trash-bold" width="18"></iconify-icon>
            Limpar Tudo
        </button>
    </div>
    
    <div class="empty-state" id="empty-state" style="display: none;">
        <div class="empty-illustration">
            <div class="empty-circle">
                <iconify-icon icon="solar:heart-broken-bold"></iconify-icon>
            </div>
        </div>
        <h2 class="empty-title">Sua lista está vazia</h2>
        <p class="empty-text">Você ainda não salvou nenhum produto. Explore nossa loja e clique no coração para adicionar aos favoritos!</p>
        <a href="<?php echo storeUrl(); ?>" class="btn-explore">
            <iconify-icon icon="solar:bag-heart-bold" width="22"></iconify-icon>
            Explorar Produtos
        </a>
    </div>
    
    <div class="products-grid" id="favorites-grid"></div>
</main>

<?php include __DIR__ . '/includes/footer.php'; ?>

<div class="confirm-modal" id="confirm-modal">
    <div class="confirm-content">
        <div class="confirm-icon">
            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
        </div>
        <h3 class="confirm-title">Limpar Favoritos?</h3>
        <p class="confirm-text">Tem certeza que deseja remover todos os produtos da sua lista de favoritos?</p>
        <div class="confirm-buttons">
            <button class="confirm-btn cancel" onclick="hideModal()">Cancelar</button>
            <button class="confirm-btn danger" onclick="clearAllFavorites()">Sim, Limpar</button>
        </div>
    </div>
</div>

<div class="toast" id="toast"></div>

<script>
const storeSlug = '<?php echo $storeSlug; ?>';
const baseUrl = '<?php echo storeUrl(); ?>';
const storeId = <?php echo $currentStoreId; ?>;
const isLoggedIn = <?php echo $isLoggedIn ? 'true' : 'false'; ?>;
const favoritesKey = `montaloja_favorites_${storeSlug}`;
let currentView = 'grid';

function getLocalFavorites() {
    try { return JSON.parse(localStorage.getItem(favoritesKey)) || []; }
    catch { return []; }
}

function saveLocalFavorites(favorites) {
    localStorage.setItem(favoritesKey, JSON.stringify(favorites));
}

async function syncWithServer() {
    if (!isLoggedIn) return;
    const localFavorites = getLocalFavorites();
    try {
        if (localFavorites.length > 0) {
            const formData = new FormData();
            formData.append('action', 'sync');
            formData.append('store_id', storeId);
            formData.append('favorites', JSON.stringify(localFavorites));
            await fetch('/api/favorites.php', { method: 'POST', body: formData });
        }
        const response = await fetch(`/api/favorites.php?action=list&store_id=${storeId}`);
        const data = await response.json();
        if (data.success && data.favorites) {
            saveLocalFavorites(data.favorites);
            document.getElementById('synced-badge').style.display = 'inline-flex';
            return data.favorites;
        }
    } catch (error) { console.error('Sync error:', error); }
    return localFavorites;
}

async function removeFromFavorites(productId) {
    let favorites = getLocalFavorites();
    favorites = favorites.filter(item => String(item.id) !== String(productId));
    saveLocalFavorites(favorites);
    if (isLoggedIn) {
        try {
            const formData = new FormData();
            formData.append('action', 'remove');
            formData.append('store_id', storeId);
            formData.append('product_id', productId);
            await fetch('/api/favorites.php', { method: 'POST', body: formData });
        } catch (e) {}
    }
    renderFavorites();
    updateFavoritesCount();
    showToast('Produto removido dos favoritos', 'info');
}

async function clearAllFavorites() {
    saveLocalFavorites([]);
    if (isLoggedIn) {
        try {
            const formData = new FormData();
            formData.append('action', 'clear');
            formData.append('store_id', storeId);
            await fetch('/api/favorites.php', { method: 'POST', body: formData });
        } catch (e) {}
    }
    hideModal();
    renderFavorites();
    updateFavoritesCount();
    showToast('Todos os favoritos foram removidos', 'info');
}

function showClearAllModal() { document.getElementById('confirm-modal').classList.add('show'); }
function hideModal() { document.getElementById('confirm-modal').classList.remove('show'); }

function updateFavoritesCount() {
    const favorites = getLocalFavorites();
    const countBadge = document.querySelector('.wishlist-btn .badge');
    if (countBadge) {
        if (favorites.length > 0) { countBadge.textContent = favorites.length; countBadge.style.display = 'flex'; }
        else { countBadge.style.display = 'none'; }
    }
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const now = new Date();
    const diffDays = Math.floor(Math.abs(now - date) / (1000 * 60 * 60 * 24));
    if (diffDays === 0) return 'Hoje';
    if (diffDays === 1) return 'Ontem';
    if (diffDays < 7) return `${diffDays} dias atrás`;
    return date.toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' });
}

function renderFavorites() {
    const favorites = getLocalFavorites();
    const grid = document.getElementById('favorites-grid');
    const emptyState = document.getElementById('empty-state');
    const countText = document.getElementById('count-text');
    const toolbar = document.getElementById('toolbar');
    const loginBanner = document.getElementById('login-banner');
    
    if (favorites.length === 0) {
        grid.innerHTML = '';
        emptyState.style.display = 'block';
        toolbar.style.display = 'none';
        if (loginBanner) loginBanner.style.display = 'none';
        countText.textContent = '0 produtos';
        return;
    }
    
    emptyState.style.display = 'none';
    toolbar.style.display = 'flex';
    if (loginBanner) loginBanner.style.display = 'flex';
    countText.textContent = `${favorites.length} produto${favorites.length > 1 ? 's' : ''}`;
    
    if (currentView === 'list') {
        grid.classList.add('list-view');
        grid.innerHTML = favorites.map(product => `
            <div class="product-card">
                <div class="product-image-wrapper">
                    <div class="product-image">
                        ${product.image ? `<img src="${product.image}" alt="${product.name}">` : `<div class="placeholder"><iconify-icon icon="solar:box-bold"></iconify-icon></div>`}
                    </div>
                </div>
                <div class="product-info">
                    <h3 class="product-name">${product.name}</h3>
                    <div class="product-meta">
                        <div class="product-price">R$ ${parseFloat(product.price).toFixed(2).replace('.', ',')}</div>
                        <div class="product-date"><iconify-icon icon="solar:clock-circle-outline" width="14"></iconify-icon>${formatDate(product.addedAt)}</div>
                    </div>
                    <div class="product-actions-list">
                        <button class="btn-action btn-cart" onclick="addToCart(${product.id}, '${product.name.replace(/'/g, "\\'")}', ${product.price}, '${product.image || ''}')">
                            <iconify-icon icon="solar:bag-4-bold" width="18"></iconify-icon>Adicionar ao Carrinho
                        </button>
                        <a href="${baseUrl}/produto/${product.id}" class="btn-action btn-view-product">
                            <iconify-icon icon="solar:eye-bold" width="18"></iconify-icon>Ver
                        </a>
                        <button class="btn-action btn-remove" onclick="removeFromFavorites('${product.id}')">
                            <iconify-icon icon="solar:trash-bin-trash-bold" width="18"></iconify-icon>Remover
                        </button>
                    </div>
                </div>
            </div>
        `).join('');
    } else {
        grid.classList.remove('list-view');
        grid.innerHTML = favorites.map(product => `
            <div class="product-card">
                <div class="product-image-wrapper">
                    <div class="product-image">
                        ${product.image ? `<img src="${product.image}" alt="${product.name}">` : `<div class="placeholder"><iconify-icon icon="solar:box-bold"></iconify-icon></div>`}
                        <div class="image-overlay"></div>
                    </div>
                    <span class="favorite-badge"><iconify-icon icon="solar:heart-bold" width="12"></iconify-icon>Favorito</span>
                    <button class="remove-btn" onclick="removeFromFavorites('${product.id}')" title="Remover dos favoritos">
                        <iconify-icon icon="solar:trash-bin-trash-bold" width="20"></iconify-icon>
                    </button>
                    <div class="quick-actions">
                        <button class="quick-btn" onclick="addToCart(${product.id}, '${product.name.replace(/'/g, "\\'")}', ${product.price}, '${product.image || ''}')">
                            <iconify-icon icon="solar:bag-4-bold" width="18"></iconify-icon>Adicionar
                        </button>
                        <a href="${baseUrl}/produto/${product.id}" class="quick-btn view-btn-action">
                            <iconify-icon icon="solar:eye-bold" width="18"></iconify-icon>
                        </a>
                    </div>
                </div>
                <div class="product-info">
                    <h3 class="product-name">${product.name}</h3>
                    <div class="product-meta">
                        <div class="product-price">R$ ${parseFloat(product.price).toFixed(2).replace('.', ',')}</div>
                        <div class="product-date"><iconify-icon icon="solar:clock-circle-outline" width="14"></iconify-icon>${formatDate(product.addedAt)}</div>
                    </div>
                </div>
            </div>
        `).join('');
    }
}

function setView(view) {
    currentView = view;
    document.querySelectorAll('.view-btn').forEach(btn => { btn.classList.toggle('active', btn.dataset.view === view); });
    renderFavorites();
}

function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    const icon = type === 'success' ? 'solar:check-circle-bold' : 'solar:info-circle-bold';
    toast.innerHTML = `<iconify-icon icon="${icon}" width="20"></iconify-icon> ${message}`;
    toast.className = 'toast show ' + type;
    setTimeout(() => toast.classList.remove('show'), 3000);
}

document.addEventListener('DOMContentLoaded', async () => {
    if (isLoggedIn) { await syncWithServer(); }
    renderFavorites();
    updateFavoritesCount();
    document.querySelectorAll('.view-btn').forEach(btn => { btn.addEventListener('click', () => setView(btn.dataset.view)); });
    document.getElementById('confirm-modal').addEventListener('click', (e) => { if (e.target === e.currentTarget) hideModal(); });
});
</script>

</body>
</html>
