// ─── Configuration ─────────────────────────────────────── const API = '/api'; // ─── Toast Notification System ─────────────────────────── function showToast(message, type = 'success') { let container = document.getElementById('toast-container'); if (!container) { container = document.createElement('div'); container.id = 'toast-container'; container.className = 'fixed top-4 left-4 z-[100] flex flex-col gap-2'; document.body.appendChild(container); } const colors = { success: 'bg-green-600', error: 'bg-red-600', warning: 'bg-amber-500', info: 'bg-blue-600' }; const icons = { success: 'check-circle', error: 'x-circle', warning: 'alert-triangle', info: 'info' }; const toast = document.createElement('div'); toast.className = `${colors[type] || colors.info} text-white px-5 py-3 rounded-xl shadow-2xl flex items-center gap-3 transform transition-all duration-300 translate-x-[-120%] max-w-sm`; toast.innerHTML = `${message}`; container.appendChild(toast); lucide.createIcons({ nodes: [toast] }); requestAnimationFrame(() => { toast.style.transform = 'translateX(0)'; }); setTimeout(() => { toast.style.transform = 'translateX(-120%)'; setTimeout(() => toast.remove(), 300); }, 3500); } // ─── Auth Helpers ──────────────────────────────────────── function getToken() { return localStorage.getItem('token'); } function getUser() { try { return JSON.parse(localStorage.getItem('currentUser')); } catch { return null; } } function isLoggedIn() { return !!getToken(); } function isSeller() { const u = getUser(); return u && u.type === 'seller'; } function requireAuth(requiredType) { if (!isLoggedIn()) { localStorage.setItem('redirectAfterLogin', window.location.pathname); window.location.href = 'login.html'; return false; } if (requiredType === 'seller' && !isSeller()) { showToast('فقط فروشندگان مجاز به دسترسی به این صفحه هستند', 'error'); setTimeout(() => { window.location.href = 'index.html'; }, 1500); return false; } return true; } function logout() { localStorage.removeItem('token'); localStorage.removeItem('currentUser'); window.location.href = 'index.html'; } // ─── API Helper ────────────────────────────────────────── async function api(endpoint, options = {}) { const token = getToken(); const headers = { 'Content-Type': 'application/json' }; if (token) headers['Authorization'] = `Bearer ${token}`; try { const res = await fetch(`${API}${endpoint}`, { ...options, headers: { ...headers, ...options.headers } }); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'خطای سرور'); return data; } catch (err) { throw err; } } // Fallback: use localStorage if API is unavailable async function apiWithFallback(endpoint, fallbackFn, options = {}) { try { return await api(endpoint, options); } catch { console.warn('API unavailable, using localStorage fallback'); return fallbackFn(); } } // ─── LocalStorage Fallbacks ────────────────────────────── function lsGetProducts() { return JSON.parse(localStorage.getItem('products') || '[]'); } function lsSaveProducts(products) { localStorage.setItem('products', JSON.stringify(products)); } function lsGetUsers() { return JSON.parse(localStorage.getItem('users') || '[]'); } // ─── Formatting ────────────────────────────────────────── function formatPrice(price) { return Number(price).toLocaleString('fa-IR'); } function formatDate(dateStr) { return new Date(dateStr).toLocaleDateString('fa-IR', { year: 'numeric', month: 'long', day: 'numeric' }); } function timeAgo(dateStr) { const diff = Date.now() - new Date(dateStr).getTime(); const mins = Math.floor(diff / 60000); if (mins < 60) return `${mins} دقیقه پیش`; const hrs = Math.floor(mins / 60); if (hrs < 24) return `${hrs} ساعت پیش`; const days = Math.floor(hrs / 24); if (days < 30) return `${days} روز پیش`; return formatDate(dateStr); } // ─── Product Card HTML ─────────────────────────────────── function productCardHTML(product) { return ` ${product.category} ${product.name} ${product.description || ''} ${formatPrice(product.price)} تومان ${product.location} `; } // ─── Header State ──────────────────────────────────────── function updateHeaderState() { const user = getUser(); const loginBtn = document.getElementById('header-login-btn'); const userMenu = document.getElementById('header-user-menu'); const userNameEl = document.getElementById('header-user-name'); if (user && loginBtn && userMenu) { loginBtn.classList.add('hidden'); userMenu.classList.remove('hidden'); if (userNameEl) userNameEl.textContent = user.name; } else if (loginBtn && userMenu) { loginBtn.classList.remove('hidden'); userMenu.classList.add('hidden'); } } // ─── Mobile Menu ──────────────────────────────────────── function initMobileMenu() { const btn = document.getElementById('menu-btn'); const menu = document.getElementById('mobile-menu'); if (btn && menu) { btn.addEventListener('click', () => menu.classList.toggle('hidden')); } } // ─── Init ──────────────────────────────────────────────── document.addEventListener('DOMContentLoaded', () => { updateHeaderState(); initMobileMenu(); lucide.createIcons(); });
${product.description || ''}