File size: 6,274 Bytes
574e722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Global variables
let cart = JSON.parse(localStorage.getItem('cart')) || [];
let products = [];

// Fetch products from API
async function fetchProducts() {
    try {
        // In a real app, this would be your API endpoint
        // For demo purposes, we'll use mock data
        const mockProducts = [
            {
                id: 1,
                name: "Premium Wireless Headphones",
                price: 199.99,
                category: "electronics",
                image: "http://static.photos/technology/320x240/1",
                rating: 4.5,
                reviews: 128
            },
            {
                id: 2,
                name: "Organic Cotton T-Shirt",
                price: 29.99,
                category: "fashion",
                image: "http://static.photos/people/320x240/2",
                rating: 4.2,
                reviews: 56
            },
            {
                id: 3,
                name: "Smart Home Speaker",
                price: 149.99,
                category: "electronics",
                image: "http://static.photos/technology/320x240/3",
                rating: 4.7,
                reviews: 204
            },
            {
                id: 4,
                name: "Stainless Steel Water Bottle",
                price: 24.99,
                category: "home",
                image: "http://static.photos/office/320x240/4",
                rating: 4.3,
                reviews: 87
            }
        ];

        products = mockProducts;
        renderFeaturedProducts();
    } catch (error) {
        console.error('Error fetching products:', error);
    }
}

// Render featured products on homepage
function renderFeaturedProducts() {
    const productsContainer = document.querySelector('.grid');
    if (!productsContainer) return;

    productsContainer.innerHTML = products.map(product => `
        <div class="product-card bg-white rounded-lg overflow-hidden">
            <a href="/product.html?id=${product.id}" class="block">
                <div class="relative overflow-hidden">
                    <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover">
                    <div class="absolute top-2 right-2 bg-primary text-white text-xs px-2 py-1 rounded-full">New</div>
                </div>
                <div class="p-4">
                    <h3 class="font-semibold text-lg mb-1">${product.name}</h3>
                    <div class="flex items-center mb-2">
                        <div class="flex text-yellow-400 mr-2">
                            ${Array(Math.floor(product.rating)).fill('<i data-feather="star" class="w-4 h-4 fill-current"></i>').join('')}
                            ${product.rating % 1 ? '<i data-feather="star" class="w-4 h-4 fill-current"></i>' : ''}
                            ${Array(5 - Math.ceil(product.rating)).fill('<i data-feather="star" class="w-4 h-4"></i>').join('')}
                        </div>
                        <span class="text-gray-500 text-sm">(${product.reviews})</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="font-bold text-lg">$${product.price.toFixed(2)}</span>
                        <button class="add-to-cart bg-primary hover:bg-indigo-700 text-white p-2 rounded-full transition duration-300" data-id="${product.id}">
                            <i data-feather="shopping-cart" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>
            </a>
        </div>
    `).join('');

    feather.replace();
    setupAddToCartButtons();
}

// Setup add to cart buttons
function setupAddToCartButtons() {
    document.querySelectorAll('.add-to-cart').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = parseInt(this.getAttribute('data-id'));
            addToCart(productId);
        });
    });
}

// Add product to cart
function addToCart(productId) {
    const product = products.find(p => p.id === productId);
    if (!product) return;

    const existingItem = cart.find(item => item.id === productId);
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cart.push({
            id: product.id,
            name: product.name,
            price: product.price,
            image: product.image,
            quantity: 1
        });
    }

    updateCartCount();
    saveCartToLocalStorage();
    showToast(`${product.name} added to cart`);
}

// Update cart count in navbar
function updateCartCount() {
    const countElements = document.querySelectorAll('.cart-count');
    const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
    
    countElements.forEach(el => {
        el.textContent = totalItems;
        el.classList.toggle('hidden', totalItems === 0);
    });
}

// Save cart to localStorage
function saveCartToLocalStorage() {
    localStorage.setItem('cart', JSON.stringify(cart));
}

// Show toast notification
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'fixed bottom-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg animate-fade-in-up';
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('animate-fade-out');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Initialize the app
document.addEventListener('DOMContentLoaded', function() {
    updateCartCount();
    
    if (window.location.pathname === '/' || window.location.pathname === '/index.html') {
        fetchProducts();
    }
});

// Animation keyframes for toast
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeInUp {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    @keyframes fadeOut {
        from { opacity: 1; }
        to { opacity: 0; }
    }
    .animate-fade-in-up {
        animation: fadeInUp 0.3s ease forwards;
    }
    .animate-fade-out {
        animation: fadeOut 0.3s ease forwards;
    }
`;
document.head.appendChild(style);