Spaces:
Running

farming / app.js
king-navid's picture
🐳 16/06 - 06:52 - make this site better,, optimize it, make the design better, make the backend better
7fb1a3f verified
Raw History Blame Contribute Delete
7.36 kB
// ─── 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 = `<i data-lucide="${icons[type] || icons.info}" class="w-5 h-5 shrink-0"></i><span class="text-sm font-medium">${message}</span>`;
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 `
<a href="product-detail.html?id=${product.id}" class="group bg-white rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 hover:-translate-y-1 flex flex-col">
<div class="relative overflow-hidden">
<img src="${product.image}" alt="${product.name}" class="w-full h-52 object-cover group-hover:scale-105 transition-transform duration-500">
<span class="absolute top-3 right-3 bg-green-600/90 backdrop-blur-sm text-white text-xs font-semibold px-3 py-1 rounded-full">${product.category}</span>
</div>
<div class="p-5 flex flex-col flex-1">
<h3 class="text-lg font-bold text-gray-800 mb-1">${product.name}</h3>
<p class="text-gray-500 text-sm mb-3 line-clamp-2">${product.description || ''}</p>
<div class="mt-auto flex justify-between items-center">
<span class="text-xl font-bold text-green-700">${formatPrice(product.price)} <small class="text-xs font-normal text-gray-500">تومان</small></span>
<span class="text-gray-400 text-xs flex items-center gap-1"><i data-lucide="map-pin" class="w-3 h-3"></i>${product.location}</span>
</div>
</div>
</a>`;
}
// ─── 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();
});