CoolFace
Apppublic

FCB02/algerian-smart-souk

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
script.js212 linesDownload Raw Back to root
1// Global state management2const appState = {3    currentUser: null,4    products: [],5    chats: [],6    categories: ['إلكترونيات', 'ملابس', 'أثاث', 'سيارات', 'عقارات', 'هواتف', 'أجهزة منزلية']7};8 9// API base URL (using mock API for demo)10const API_BASE = 'https://jsonplaceholder.typicode.com';11 12// Utility functions13const formatPrice = (price) => {14    return new Intl.NumberFormat('ar-DZ', {15        style: 'currency',16        currency: 'DZD'17    }).format(price);18};19 20const formatDate = (dateString) => {21    return new Date(dateString).toLocaleDateString('ar-DZ', {22        year: 'numeric',23        month: 'long',24        day: 'numeric'25    });26};27 28// Authentication functions29const loginUser = async (email, password) => {30    // Mock login - in real app, this would call your backend31    const user = {32        id: 1,33        name: 'محمد أحمد',34        email: email,35        phone: '+213550123456',36        avatar: 'http://static.photos/people/200x200/1'37    };38    39    localStorage.setItem('currentUser', JSON.stringify(user));40    appState.currentUser = user;41    return user;42};43 44const logoutUser = () => {45    localStorage.removeItem('currentUser');46    appState.currentUser = null;47    window.location.href = 'index.html';48};49 50const checkAuth = () => {51    const user = localStorage.getItem('currentUser');52    if (user) {53        appState.currentUser = JSON.parse(user);54        return true;55    }56    return false;57};58 59// Product functions60const loadFeaturedProducts = async () => {61    const container = document.getElementById('products-container');62    if (!container) return;63 64    // Show loading65    container.innerHTML = '<div class="col-span-3 text-center"><div class="loading-spinner mx-auto"></div></div>';66 67    try {68        // Mock products data69        const mockProducts = [70            {71                id: 1,72                title: 'هاتف سامسونج جلاكسي S23',73                price: 65000,74                image: 'http://static.photos/technology/320x240/1',75                category: 'هواتف',76                location: 'الجزائر العاصمة',77                date: new Date().toISOString()78            },79            {80                id: 2,81                title: 'لاب توب ديل كوري i7',82                price: 120000,83                image: 'http://static.photos/technology/320x240/2',84                category: 'إلكترونيات',85                location: 'وهران',86                date: new Date(Date.now() - 86400000).toISOString()87            },88            {89                id: 3,90                title: 'ساعة أبل ووتش جديدة',91                price: 45000,92                image: 'http://static.photos/technology/320x240/3',93                category: 'إلكترونيات',94                location: 'قسنطينة',95                date: new Date(Date.now() - 172800000).toISOString()96            }97        ];98 99        container.innerHTML = mockProducts.map(product => `100            <div class="product-card bg-white rounded-lg shadow-md overflow-hidden fade-in">101                <img src="${product.image}" alt="${product.title}" class="w-full h-48 object-cover">102                <div class="p-4">103                    <h3 class="font-bold text-lg mb-2">${product.title}</h3>104                    <div class="flex justify-between items-center mb-2">105                        <span class="text-primary font-bold text-xl">${formatPrice(product.price)}</span>106                        <span class="text-sm text-gray-500">${product.location}</span>107                    </div>108                    <div class="flex justify-between items-center">109                        <span class="text-secondary text-sm">${product.category}</span>110                        <span class="text-gray-400 text-xs">${formatDate(product.date)}</span>111                    </div>112                    <button onclick="viewProduct(${product.id})" class="w-full mt-3 bg-primary text-white py-2 rounded hover:bg-blue-700 transition">113                        عرض التفاصيل114                    </button>115                </div>116            </div>117        `).join('');118    } catch (error) {119        container.innerHTML = '<div class="col-span-3 text-center text-red-500">خطأ في تحميل المنتجات</div>';120    }121};122 123const viewProduct = (productId) => {124    // Redirect to product page or show modal125    window.location.href = `product.html?id=${productId}`;126};127 128// Chat functions129const sendMessage = (chatId, message) => {130    if (!appState.currentUser) {131        alert('يجب تسجيل الدخول أولاً');132        return;133    }134 135    const chat = {136        id: Date.now(),137        sender: appState.currentUser.id,138        message: message,139        timestamp: new Date().toISOString()140    };141 142    // Add to local state143    if (!appState.chats[chatId]) {144        appState.chats[chatId] = [];145    }146    appState.chats[chatId].push(chat);147 148    // Update UI149    updateChatUI(chatId);150};151 152const updateChatUI = (chatId) => {153    const chatContainer = document.getElementById('chat-messages');154    if (!chatContainer) return;155 156    const messages = appState.chats[chatId] || [];157    chatContainer.innerHTML = messages.map(msg => `158        <div class="chat-bubble ${msg.sender === appState.currentUser.id ? 'own' : 'other'} p-3 rounded-lg mb-2">159            <p>${msg.message}</p>160            <span class="text-xs opacity-70">${new Date(msg.timestamp).toLocaleTimeString('ar-DZ')}</span>161        </div>162    `).join('');163 164    chatContainer.scrollTop = chatContainer.scrollHeight;165};166 167// File upload handling168const handleImageUpload = (file, callback) => {169    if (!file) return;170 171    const reader = new FileReader();172    reader.onload = (e) => {173        callback(e.target.result);174    };175    reader.readAsDataURL(file);176};177 178// Initialize app179document.addEventListener('DOMContentLoaded', function() {180    // Check authentication on page load181    checkAuth();182    183    // Update UI based on auth state184    updateAuthUI();185});186 187const updateAuthUI = () => {188    const authElements = document.querySelectorAll('[data-auth]');189    authElements.forEach(element => {190        if (appState.currentUser) {191            if (element.dataset.auth === 'logged-in') {192                element.style.display = 'block';193            } else {194                element.style.display = 'none';195            }196        } else {197            if (element.dataset.auth === 'logged-out') {198                element.style.display = 'block';199            } else {200                element.style.display = 'none';201            }202        }203    });204};205 206// Export functions for global use207window.loginUser = loginUser;208window.logoutUser = logoutUser;209window.loadFeaturedProducts = loadFeaturedProducts;210window.viewProduct = viewProduct;211window.sendMessage = sendMessage;212window.handleImageUpload = handleImageUpload;