Xendercage/byd-electradrive-hub
0
1// Global variables2let currentUser = null;3let cart = [];4let currentOrder = null;5 6// API endpoints (mock data for demonstration)7const API_BASE = 'https://jsonplaceholder.typicode.com';8const CAR_DATA = [9 {10 id: 1,11 name: "BYD Han EV",12 price: 45000,13 image: "http://static.photos/automotive/640x360/1",14 description: "Luxury electric sedan with 605km range and 0-100km/h in 3.9s",15 type: "car",16 investment: false17 },18 {19 id: 2,20 name: "BYD Tang EV",21 price: 52000,22 image: "http://static.photos/automotive/640x360/2",23 description: "Premium electric SUV with 7-seater capacity and AWD",24 type: "car",25 investment: false26 },27 {28 id: 3,29 name: "BYD Dolphin",30 price: 28000,31 image: "http://static.photos/automotive/640x360/3",32 description: "Compact electric hatchback perfect for urban driving",33 type: "car",34 investment: false35 },36 {37 id: 4,38 name: "BYD Seal",39 price: 38000,40 image: "http://static.photos/automotive/640x360/4",41 description: "Sporty electric sedan with cutting-edge battery technology",42 type: "car",43 investment: false44 }45];46 47const INVESTMENT_DATA = [48 {49 id: 101,50 name: "BYD Factory Expansion",51 price: 10000,52 image: "http://static.photos/finance/640x360/1",53 description: "Invest in BYD's new manufacturing facility with 15% annual returns",54 type: "investment",55 investment: true56 },57 {58 id: 102,59 name: "Battery Tech R&D",60 price: 5000,61 image: "http://static.photos/technology/640x360/1",62 description: "Support next-generation battery development with 12% returns",63 type: "investment",64 investment: true65 },66 {67 id: 103,68 name: "Charging Network",69 price: 7500,70 image: "http://static.photos/construction/640x360/1",71 description: "Invest in BYD's nationwide charging infrastructure project",72 type: "investment",73 investment: true74 }75];76 77// Initialize application78document.addEventListener('DOMContentLoaded', function() {79 checkAuthStatus();80 initializeEventListeners();81});82 83// Authentication functions84function checkAuthStatus() {85 const userData = localStorage.getItem('currentUser');86 if (userData) {87 currentUser = JSON.parse(userData);88 updateUIForLoggedInUser();89 }90}91 92function loginUser(email, password) {93 // Mock login - in real app, this would call your backend94 currentUser = {95 id: 1,96 email: email,97 name: email.split('@')[0],98 phone: '+1234567890'99 };100 localStorage.setItem('currentUser', JSON.stringify(currentUser));101 updateUIForLoggedInUser();102 return true;103}104 105function logoutUser() {106 currentUser = null;107 localStorage.removeItem('currentUser');108 updateUIForLoggedOutUser();109}110 111function updateUIForLoggedInUser() {112 const loginBtn = document.getElementById('login-btn');113 const userMenu = document.getElementById('user-menu');114 115 if (loginBtn && userMenu) {116 loginBtn.classList.add('hidden');117 userMenu.classList.remove('hidden');118 document.getElementById('user-name').textContent = currentUser.name;119 }120}121 122function updateUIForLoggedOutUser() {123 const loginBtn = document.getElementById('login-btn');124 const userMenu = document.getElementById('user-menu');125 126 if (loginBtn && userMenu) {127 loginBtn.classList.remove('hidden');128 userMenu.classList.add('hidden');129 }130}131 132// Catalog functions133function loadCarCatalog() {134 const catalogContainer = document.getElementById('car-catalog');135 if (!catalogContainer) return;136 137 catalogContainer.innerHTML = CAR_DATA.map(car => `138 <div class="card-hover bg-white rounded-xl shadow-lg overflow-hidden fade-in">139 <img src="${car.image}" alt="${car.name}" class="w-full h-48 object-cover">140 <div class="p-6">141 <h3 class="text-xl font-semibold text-gray-800 mb-2">${car.name}</h3>142 <p class="text-gray-600 mb-4">${car.description}</p>143 <div class="flex justify-between items-center mb-4">144 <span class="text-2xl font-bold text-red-600">$${car.price.toLocaleString()}</span>145 <span class="security-badge">Available</span>146 </div>147 <div class="space-y-2">148 <button onclick="addToCart(${car.id}, 'buy')" class="btn-primary w-full">149 <i data-feather="shopping-cart" class="w-4 h-4 inline mr-2"></i>150 Buy Now151 </button>152 <button onclick="addToCart(${car.id}, 'invest')" class="btn-secondary w-full">153 <i data-feather="trending-up" class="w-4 h-4 inline mr-2"></i>154 Invest Now155 </button>156 </div>157 </div>158 `).join('');159 160 feather.replace();161}162 163function loadInvestmentCatalog() {164 const catalogContainer = document.getElementById('investment-catalog');165 if (!catalogContainer) return;166 167 catalogContainer.innerHTML = INVESTMENT_DATA.map(investment => `168 <div class="card-hover bg-white rounded-xl shadow-lg overflow-hidden fade-in">169 <img src="${investment.image}" alt="${investment.name}" class="w-full h-48 object-cover">170 <div class="p-6">171 <h3 class="text-xl font-semibold text-gray-800 mb-2">${investment.name}</h3>172 <p class="text-gray-600 mb-4">${investment.description}</p>173 <div class="flex justify-between items-center mb-4">174 <span class="text-2xl font-bold text-blue-600">$${investment.price.toLocaleString()}</span>175 <span class="security-badge">15% ROI</span>176 </div>177 <button onclick="addToCart(${investment.id}, 'invest')" class="btn-secondary w-full">178 <i data-feather="trending-up" class="w-4 h-4 inline mr-2"></i>179 Invest Now180 </button>181 </div>182 </div>183 `).join('');184 185 feather.replace();186}187 188// Cart and Order Management189function addToCart(itemId, action) {190 if (!currentUser) {191 showLoginModal();192 return;193 }194 195 const item = [...CAR_DATA, ...INVESTMENT_DATA].find(i => i.id === itemId);196 if (!item) return;197 198 const cartItem = {199 ...item,200 action: action,201 quantity: 1,202 timestamp: new Date().toISOString()203 };204 205 cart.push(cartItem);206 localStorage.setItem('cart', JSON.stringify(cart));207 208 // Redirect to checkout209 window.location.href = 'checkout.html';210}211 212function getCartItems() {213 return cart;214}215 216function clearCart() {217 cart = [];218 localStorage.setItem('cart', JSON.stringify(cart));219}220 221// Payment Processing222async function processPayment(paymentData) {223 // Mock payment processing224 const orderId = 'ORD_' + Math.random().toString(36).substr(2, 9).toUpperCase();225 226 const order = {227 id: orderId,228 userId: currentUser.id,229 items: [...cart],230 total: cart.reduce((sum, item) => sum + item.price, 0),231 paymentMethod: paymentData.method,232 status: 'pending',233 createdAt: new Date().toISOString(),234 paymentDetails: paymentData235 };236 237 // Save order to localStorage (in real app, this would be a backend API call)238 const orders = JSON.parse(localStorage.getItem('orders') || '[]');239 orders.push(order);240 localStorage.setItem('orders', JSON.stringify(orders));241 242 currentOrder = order;243 244 // Send confirmation (mock)245 await sendConfirmation(order);246 247 // Clear cart248 clearCart();249 250 return order;251}252 253async function sendConfirmation(order) {254 // Mock email/SMS sending255 console.log('Sending confirmation for order:', order.id);256 257 // In a real application, this would call your backend API258 // to send actual emails/SMS via services like SendGrid, Twilio, etc.259 260 // Update order status to completed261 order.status = 'completed';262 const orders = JSON.parse(localStorage.getItem('orders') || '[]');263 const orderIndex = orders.findIndex(o => o.id === order.id);264 if (orderIndex !== -1) {265 orders[orderIndex] = order;266 localStorage.setItem('orders', JSON.stringify(orders));267 }268 269 return true;270}271 272// Utility Functions273function formatCurrency(amount) {274 return new Intl.NumberFormat('en-US', {275 style: 'currency',276 currency: 'USD'277 }).format(amount);278}279 280function generateCryptoAddress(cryptoType) {281 // Mock crypto address generation282 const prefixes = {283 'bitcoin': 'bc1q',284 'ethereum': '0x',285 'usdt': '0x'286 };287 288 const prefix = prefixes[cryptoType.toLowerCase()] || '0x';289 const randomChars = Math.random().toString(36).substr(2, 10);290 291 return prefix + randomChars;292}293 294function showNotification(message, type = 'info') {295 // Create and show a notification296 const notification = document.createElement('div');297 notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${298 type === 'success' ? 'bg-green-500 text-white' :299 type === 'error' ? 'bg-red-500 text-white' :300 'bg-blue-500 text-white'301 }`;302 notification.textContent = message;303 304 document.body.appendChild(notification);305 306 setTimeout(() => {307 notification.remove();308 }, 3000);309}310 311function initializeEventListeners() {312 // Global event listeners can be added here313}314 315// Export functions for use in other modules316window.BYDElectraDriveHub = {317 loginUser,318 logoutUser,319 addToCart,320 processPayment,321 getCartItems,322 clearCart,323 formatCurrency,324 generateCryptoAddress,325 showNotification326};