// 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 => `
$${product.price}
${product.name}
${product.shortDescription || ''}
`).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 = `
${product.name}
${Array(5).fill().map((_, i) => `
`).join('')}
${product.reviewCount} reviews
${product.description}
Product Details
- File Type: ${product.fileType}
- File Size: ${product.fileSize}
- Compatibility: ${product.compatibility}
- License: ${product.license}
$${product.price}
`;
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;