Spaces:
Running
Running
Download script.js from 2ota/digital-bazaar-delight: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/spaces/2ota/digital-bazaar-delight/resolve/main/script.js
- Command line
-
hf download hf://spaces/2ota/digital-bazaar-delight/script.js
-
curl -L -o script.js https://huggingface.co/spaces/2ota/digital-bazaar-delight/resolve/main/script.js
19.2 kB
| // Global configuration | |
| const API_BASE_URL = 'https://api.3raky.com/v1'; | |
| const STRIPE_PUBLIC_KEY = 'pk_test_51...'; // Replace with your Stripe public key | |
| const PAYPAL_CLIENT_ID = 'Ae...'; // Replace with your PayPal client ID | |
| // Initialize app | |
| document.addEventListener('DOMContentLoaded', function() { | |
| checkAuthStatus(); | |
| setupEventListeners(); | |
| }); | |
| // Check authentication status | |
| function checkAuthStatus() { | |
| const token = localStorage.getItem('authToken'); | |
| if (token) { | |
| fetch(`${API_BASE_URL}/auth/verify`, { | |
| headers: { | |
| 'Authorization': `Bearer ${token}` | |
| } | |
| }) | |
| .then(response => { | |
| if (response.ok) { | |
| updateAuthUI(true); | |
| } else { | |
| localStorage.removeItem('authToken'); | |
| updateAuthUI(false); | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Auth verification failed:', error); | |
| updateAuthUI(false); | |
| }); | |
| } else { | |
| updateAuthUI(false); | |
| } | |
| } | |
| // Update UI based on auth status | |
| function updateAuthUI(isAuthenticated) { | |
| const authElements = document.querySelectorAll('[data-auth]'); | |
| authElements.forEach(el => { | |
| const showWhen = el.getAttribute('data-auth'); | |
| if ((showWhen === 'logged-in' && isAuthenticated) || | |
| (showWhen === 'logged-out' && !isAuthenticated)) { | |
| el.classList.remove('hidden'); | |
| } else { | |
| el.classList.add('hidden'); | |
| } | |
| }); | |
| if (isAuthenticated) { | |
| loadUserProfile(); | |
| } | |
| } | |
| // Load user profile | |
| function loadUserProfile() { | |
| const token = localStorage.getItem('authToken'); | |
| fetch(`${API_BASE_URL}/users/me`, { | |
| headers: { | |
| 'Authorization': `Bearer ${token}` | |
| } | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| const avatarElements = document.querySelectorAll('.user-avatar'); | |
| const nameElements = document.querySelectorAll('.user-name'); | |
| avatarElements.forEach(el => { | |
| el.src = data.avatar || 'http://static.photos/people/200x200'; | |
| el.alt = data.name; | |
| }); | |
| nameElements.forEach(el => { | |
| el.textContent = data.name || 'User'; | |
| }); | |
| }) | |
| .catch(error => console.error('Profile load failed:', error)); | |
| } | |
| // Setup event listeners | |
| function setupEventListeners() { | |
| // Language toggle | |
| const langToggle = document.getElementById('languageToggle'); | |
| if (langToggle) { | |
| langToggle.addEventListener('click', toggleLanguage); | |
| } | |
| // Auth modal toggles | |
| document.querySelectorAll('[data-auth-modal]').forEach(btn => { | |
| btn.addEventListener('click', () => { | |
| const modalType = btn.getAttribute('data-auth-modal'); | |
| toggleAuthModal(modalType); | |
| }); | |
| }); | |
| // Close modals | |
| document.querySelectorAll('.modal-close').forEach(btn => { | |
| btn.addEventListener('click', closeAllModals); | |
| }); | |
| // Overlay click to close | |
| document.querySelectorAll('.modal-overlay').forEach(overlay => { | |
| overlay.addEventListener('click', closeAllModals); | |
| }); | |
| } | |
| // Load featured products | |
| function loadFeaturedProducts() { | |
| fetch(`${API_BASE_URL}/products/featured`) | |
| .then(response => response.json()) | |
| .then(products => { | |
| const container = document.getElementById('featuredProducts'); | |
| if (container) { | |
| container.innerHTML = products.map(product => ` | |
| <div class="product-card bg-white rounded-lg overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 animate-fadeIn"> | |
| <div class="relative pb-[75%] overflow-hidden"> | |
| <img src="${product.image || 'http://static.photos/technology/640x360'}" | |
| alt="${product.name}" | |
| class="absolute h-full w-full object-cover"> | |
| <div class="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent flex items-end p-4"> | |
| <span class="bg-accent-500 text-white text-sm font-medium px-3 py-1 rounded-full"> | |
| $${product.price} | |
| </span> | |
| </div> | |
| </div> | |
| <div class="p-4"> | |
| <h3 class="font-heading font-semibold text-lg mb-2">${product.name}</h3> | |
| <p class="text-primary-600 text-sm mb-4">${product.shortDescription || ''}</p> | |
| <div class="flex justify-between items-center"> | |
| <a href="/product.html?id=${product.id}" | |
| class="text-primary-700 hover:text-primary-900 font-medium text-sm flex items-center"> | |
| <span>View Details</span> | |
| <i data-feather="arrow-right" class="w-4 h-4 ml-1"></i> | |
| </a> | |
| <button class="text-accent-500 hover:text-accent-600" data-product-id="${product.id}"> | |
| <i data-feather="heart" class="w-5 h-5"></i> | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| `).join(''); | |
| feather.replace(); | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Failed to load featured products:', error); | |
| }); | |
| } | |
| // Language toggle functionality | |
| function toggleLanguage() { | |
| const currentLang = document.documentElement.lang || 'en'; | |
| const newLang = currentLang === 'en' ? 'ar' : 'en'; | |
| document.documentElement.lang = newLang; | |
| document.documentElement.dir = newLang === 'ar' ? 'rtl' : 'ltr'; | |
| // Update UI text based on language | |
| updateTextForLanguage(newLang); | |
| // Save preference | |
| localStorage.setItem('preferredLanguage', newLang); | |
| } | |
| function updateTextForLanguage(lang) { | |
| document.querySelectorAll('[data-i18n]').forEach(el => { | |
| const key = el.getAttribute('data-i18n'); | |
| el.textContent = translations[lang][key] || key; | |
| }); | |
| } | |
| // Translations object | |
| const translations = { | |
| en: { | |
| "hero_title": "Digital Treasures", | |
| "hero_subtitle": "At Your Fingertips", | |
| "hero_description": "Discover premium digital products - PDFs, stickers, and templates to boost your productivity and creativity.", | |
| "shop_now": "Shop Now", | |
| "learn_more": "Learn More", | |
| "featured_products": "Featured Products", | |
| "featured_description": "Check out our most popular digital assets", | |
| "browse_categories": "Browse Categories", | |
| "categories_description": "Find exactly what you need", | |
| "category_pdf": "PDF Documents", | |
| "category_pdf_desc": "Guides, planners, and educational materials", | |
| "category_sticker": "Stickers", | |
| "category_sticker_desc": "Digital stickers for planners and social media", | |
| "category_template": "Templates", | |
| "category_template_desc": "Ready-to-use designs for various purposes", | |
| "testimonials_title": "What Our Customers Say", | |
| "testimonials_description": "Trusted by thousands of creators worldwide", | |
| "testimonial_1": "\"The PDF planner templates have completely transformed my productivity. Worth every penny!\"", | |
| "testimonial_2": "\"Incredible selection of Arabic content. The checkout was smooth and delivery instant.\"", | |
| "testimonial_3": "\"The sticker bundles are perfect for my digital bullet journal. So many options!\"", | |
| "cta_title": "Ready to Boost Your Digital Toolkit?", | |
| "cta_description": "Join thousands of satisfied customers who've transformed their workflow with our premium digital products.", | |
| "start_shopping": "Start Shopping Now" | |
| }, | |
| ar: { | |
| "hero_title": "كنوز رقمية", | |
| "hero_subtitle": "بين يديك", | |
| "hero_description": "اكتشف منتجات رقمية مميزة - ملفات PDF، ملصقات، وقوالب لتعزيز إنتاجيتك وإبداعك.", | |
| "shop_now": "تسوق الآن", | |
| "learn_more": "تعلم المزيد", | |
| "featured_products": "منتجات مميزة", | |
| "featured_description": "تصفح أكثر الأصول الرقمية شعبية لدينا", | |
| "browse_categories": "تصفح الفئات", | |
| "categories_description": "ابحث عما تحتاجه بالضبط", | |
| "category_pdf": "مستندات PDF", | |
| "category_pdf_desc": "أدلة، مخططات، ومواد تعليمية", | |
| "category_sticker": "ملصقات", | |
| "category_sticker_desc": "ملصقات رقمية للمخططات ووسائل التواصل الاجتماعي", | |
| "category_template": "قوالب", | |
| "category_template_desc": "تصاميم جاهزة للاستخدام لأغراض متنوعة", | |
| "testimonials_title": "ما يقوله عملاؤنا", | |
| "testimonials_description": "موثوق به من قبل آلاف المبدعين حول العالم", | |
| "testimonial_1": "\"قوالب مخطط PDF قد غيرت تمامًا إنتاجيتي. تستحق كل فلس!\"", | |
| "testimonial_2": "\"اختيار رائع للمحتوى العربي. كانت عملية الدفع سلسة والتسليم فوري.\"", | |
| "testimonial_3": "\"مجموعات الملصقات مثالية لمجلة النقاط الرقمية الخاصة بي. الكثير من الخيارات!\"", | |
| "cta_title": "هل أنت مستعد لتعزيز أدواتك الرقمية؟", | |
| "cta_description": "انضم إلى الآلاف من العملاء الراضين الذين قاموا بتحسين سير عملهم بمنتجاتنا الرقمية المميزة.", | |
| "start_shopping": "ابدأ التسوق الآن" | |
| } | |
| }; | |
| // Initialize language from localStorage or browser preference | |
| function initializeLanguageToggle() { | |
| const savedLang = localStorage.getItem('preferredLanguage'); | |
| const browserLang = navigator.language.startsWith('ar') ? 'ar' : 'en'; | |
| const initialLang = savedLang || browserLang; | |
| document.documentElement.lang = initialLang; | |
| document.documentElement.dir = initialLang === 'ar' ? 'rtl' : 'ltr'; | |
| updateTextForLanguage(initialLang); | |
| } | |
| // Authentication modals | |
| function toggleAuthModal(type) { | |
| const modal = document.getElementById(`${type}Modal`); | |
| if (modal) { | |
| document.querySelectorAll('.auth-modal').forEach(m => { | |
| m.classList.add('hidden'); | |
| }); | |
| modal.classList.remove('hidden'); | |
| document.body.classList.add('overflow-hidden'); | |
| } | |
| } | |
| function closeAllModals() { | |
| document.querySelectorAll('.auth-modal').forEach(modal => { | |
| modal.classList.add('hidden'); | |
| }); | |
| document.body.classList.remove('overflow-hidden'); | |
| } | |
| // Authentication functions | |
| async function handleLogin(e) { | |
| e.preventDefault(); | |
| const form = e.target; | |
| const formData = new FormData(form); | |
| try { | |
| const response = await fetch(`${API_BASE_URL}/auth/login`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ | |
| email: formData.get('email'), | |
| password: formData.get('password') | |
| }) | |
| }); | |
| const data = await response.json(); | |
| if (response.ok) { | |
| localStorage.setItem('authToken', data.token); | |
| updateAuthUI(true); | |
| closeAllModals(); | |
| showToast('Login successful!', 'success'); | |
| } else { | |
| throw new Error(data.message || 'Login failed'); | |
| } | |
| } catch (error) { | |
| showToast(error.message, 'error'); | |
| } | |
| } | |
| async function handleSignup(e) { | |
| e.preventDefault(); | |
| const form = e.target; | |
| const formData = new FormData(form); | |
| try { | |
| const response = await fetch(`${API_BASE_URL}/auth/register`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ | |
| name: formData.get('name'), | |
| email: formData.get('email'), | |
| password: formData.get('password') | |
| }) | |
| }); | |
| const data = await response.json(); | |
| if (response.ok) { | |
| localStorage.setItem('authToken', data.token); | |
| updateAuthUI(true); | |
| closeAllModals(); | |
| showToast('Registration successful!', 'success'); | |
| } else { | |
| throw new Error(data.message || 'Registration failed'); | |
| } | |
| } catch (error) { | |
| showToast(error.message, 'error'); | |
| } | |
| } | |
| function handleLogout() { | |
| localStorage.removeItem('authToken'); | |
| updateAuthUI(false); | |
| showToast('Logged out successfully', 'success'); | |
| } | |
| // Toast notification | |
| function showToast(message, type = 'info') { | |
| const toast = document.createElement('div'); | |
| toast.className = `fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg text-white ${ | |
| type === 'success' ? 'bg-green-500' : | |
| type === 'error' ? 'bg-red-500' : | |
| 'bg-primary-700' | |
| }`; | |
| toast.textContent = message; | |
| document.body.appendChild(toast); | |
| setTimeout(() => { | |
| toast.classList.add('opacity-0', 'translate-y-4'); | |
| setTimeout(() => toast.remove(), 300); | |
| }, 3000); | |
| } | |
| // Initialize Stripe | |
| function initStripe() { | |
| return Stripe(STRIPE_PUBLIC_KEY); | |
| } | |
| // Initialize PayPal | |
| function initPayPal() { | |
| return { | |
| buttons: function(options) { | |
| return paypal.Buttons({ | |
| ...options, | |
| style: { | |
| color: 'gold', | |
| shape: 'rect', | |
| label: 'paypal', | |
| layout: 'vertical' | |
| } | |
| }); | |
| } | |
| }; | |
| } | |
| // Checkout functions | |
| async function initiateCheckout(productId) { | |
| const token = localStorage.getItem('authToken'); | |
| if (!token) { | |
| toggleAuthModal('login'); | |
| showToast('Please login to proceed with checkout', 'error'); | |
| return; | |
| } | |
| try { | |
| const response = await fetch(`${API_BASE_URL}/checkout/create-session`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| 'Authorization': `Bearer ${token}` | |
| }, | |
| body: JSON.stringify({ | |
| productId, | |
| cancelUrl: window.location.href, | |
| successUrl: `${window.location.origin}/checkout-success.html` | |
| }) | |
| }); | |
| const { sessionId } = await response.json(); | |
| if (response.ok) { | |
| const stripe = await initStripe(); | |
| const { error } = await stripe.redirectToCheckout({ sessionId }); | |
| if (error) { | |
| throw error; | |
| } | |
| } else { | |
| throw new Error('Failed to create checkout session'); | |
| } | |
| } catch (error) { | |
| console.error('Checkout error:', error); | |
| showToast(error.message, 'error'); | |
| } | |
| } | |
| // Product page functions | |
| async function loadProductDetails(productId) { | |
| try { | |
| const response = await fetch(`${API_BASE_URL}/products/${productId}`); | |
| const product = await response.json(); | |
| if (response.ok) { | |
| renderProductDetails(product); | |
| } else { | |
| throw new Error('Product not found'); | |
| } | |
| } catch (error) { | |
| console.error('Failed to load product:', error); | |
| showToast(error.message, 'error'); | |
| } | |
| } | |
| function renderProductDetails(product) { | |
| // Implementation for product details page | |
| const container = document.getElementById('productDetails'); | |
| if (container) { | |
| container.innerHTML = ` | |
| <div class="grid md:grid-cols-2 gap-8"> | |
| <div class="bg-white p-6 rounded-xl shadow-lg"> | |
| <img src="${product.image || 'http://static.photos/technology/640x360'}" | |
| alt="${product.name}" | |
| class="w-full rounded-lg mb-4"> | |
| </div> | |
| <div> | |
| <h1 class="text-3xl font-heading font-bold mb-2">${product.name}</h1> | |
| <div class="flex items-center mb-4"> | |
| <div class="text-accent-400 flex mr-2"> | |
| ${Array(5).fill().map((_, i) => ` | |
| <i data-feather="${i < product.rating ? 'star' : 'star'}" | |
| class="w-4 h-4 ${i < product.rating ? 'fill-current' : ''}"></i> | |
| `).join('')} | |
| </div> | |
| <span class="text-primary-600 text-sm">${product.reviewCount} reviews</span> | |
| </div> | |
| <p class="text-primary-700 mb-6">${product.description}</p> | |
| <div class="bg-primary-50 p-4 rounded-lg mb-6"> | |
| <h3 class="font-heading font-semibold mb-2">Product Details</h3> | |
| <ul class="text-sm text-primary-600 space-y-1"> | |
| <li><strong>File Type:</strong> ${product.fileType}</li> | |
| <li><strong>File Size:</strong> ${product.fileSize}</li> | |
| <li><strong>Compatibility:</strong> ${product.compatibility}</li> | |
| <li><strong>License:</strong> ${product.license}</li> | |
| </ul> | |
| </div> | |
| <div class="flex items-center justify-between mb-6"> | |
| <span class="text-2xl font-bold text-primary-900">$${product.price}</span> | |
| <button class="bg-accent-500 hover:bg-accent-600 text-white px-6 py-2 rounded-lg" | |
| onclick="initiateCheckout('${product.id}')"> | |
| Buy Now | |
| </button> | |
| </div> | |
| <div class="flex space-x-4"> | |
| <button class="text-primary-600 hover:text-accent-500 flex items-center"> | |
| <i data-feather="heart" class="w-5 h-5 mr-1"></i> | |
| Add to Wishlist | |
| </button> | |
| <button class="text-primary-600 hover:text-accent-500 flex items-center"> | |
| <i data-feather="share-2" class="w-5 h-5 mr-1"></i> | |
| Share | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| `; | |
| feather.replace(); | |
| } | |
| } | |
| // Expose functions to window for HTML onclick attributes | |
| window.handleLogin = handleLogin; | |
| window.handleSignup = handleSignup; | |
| window.handleLogout = handleLogout; | |
| window.initiateCheckout = initiateCheckout; | |
| window.toggleAuthModal = toggleAuthModal; |