import { useState, useEffect } from 'react'; import axios from 'axios'; import { CURRICULUM_MODULES } from './constants/modules'; import { getCountryRuleByName } from './constants/countries'; import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types'; import { API_BASE } from './services/api'; import { loadRazorpayScript } from './services/razorpay'; import { cleanPhoneInput, validatePhoneNumber } from './utils/validation'; // Modular Subcomponents import { StoreHeader } from './components/layout/StoreHeader'; import { StoreFooter } from './components/layout/StoreFooter'; import { LifetimeBanner } from './components/catalog/LifetimeBanner'; import { CatalogSection } from './components/catalog/CatalogSection'; import { CartDrawer } from './components/cart/CartDrawer'; import { SubscriptionsView } from './components/subscriptions/SubscriptionsView'; import { AuthModal } from './components/auth/AuthModal'; import { ProfileDrawer } from './components/auth/ProfileDrawer'; import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal'; import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal'; import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation'; const getInitialTab = (): 'storefront' | 'subscriptions' => { if (typeof window !== 'undefined') { const path = window.location.pathname.toLowerCase(); if (path.includes('/subscriptions')) return 'subscriptions'; } return 'storefront'; }; export default function App() { const [activeTab, setActiveTab] = useState<'storefront' | 'subscriptions'>(getInitialTab); const switchTab = (tab: 'storefront' | 'subscriptions') => { setActiveTab(tab); if (typeof window !== 'undefined') { const isStorePrefix = window.location.pathname.startsWith('/store'); const basePath = isStorePrefix ? '/store' : ''; const newPath = tab === 'storefront' ? (basePath || '/') : (basePath + '/' + tab); if (window.location.pathname !== newPath) { window.history.pushState({ tab }, '', newPath); } } }; const [currency, setCurrency] = useState('INR'); // Auth state const [userToken, setUserToken] = useState(localStorage.getItem('access_token')); const [loggedInUser, setLoggedInUser] = useState(null); const [showAuthModal, setShowAuthModal] = useState(false); const [authMode, setAuthMode] = useState<'login' | 'register' | 'forgot'>('login'); const [resetStep, setResetStep] = useState<'request' | 'verify'>('request'); const [resetOtp, setResetOtp] = useState(''); const [resetNewPassword, setResetNewPassword] = useState(''); const [resetConfirmPassword, setResetConfirmPassword] = useState(''); const [resetSuccessMessage, setResetSuccessMessage] = useState(null); const [passwordUpdatedPopup, setPasswordUpdatedPopup] = useState(false); // In-app Change Password state (Profile Drawer) const [showPasswordChange, setShowPasswordChange] = useState(false); const [changeOldPassword, setChangeOldPassword] = useState(''); const [changeNewPassword, setChangeNewPassword] = useState(''); const [changeConfirmPassword, setChangeConfirmPassword] = useState(''); const [changePasswordLoading, setChangePasswordLoading] = useState(false); const [changePasswordError, setChangePasswordError] = useState(null); const [changePasswordSuccess, setChangePasswordSuccess] = useState(false); // Auth Form State const [authEmail, setAuthEmail] = useState(''); const [authPassword, setAuthPassword] = useState(''); const [authDisplayName, setAuthDisplayName] = useState(''); const [authPhone, setAuthPhone] = useState(''); const [authDialCode, setAuthDialCode] = useState('+91'); const [authCountry, setAuthCountry] = useState('India'); const [authLoading, setAuthLoading] = useState(false); const [authError, setAuthError] = useState(null); // Cart state const [cart, setCart] = useState([]); const [couponCode, setCouponCode] = useState(''); const [appliedCoupon, setAppliedCoupon] = useState(null); // Storefront toggle states for showing locked modules in each category const [showLockedByCategory, setShowLockedByCategory] = useState<{ [key: string]: boolean }>({ Points: true, Pattern: true, Nutrition: true, Therapeutics: true, Lifetime: true }); // Calculation / API state const [pricingCalc, setPricingCalc] = useState(null); const [loadingPricing, setLoadingPricing] = useState(false); const [checkoutLoading, setCheckoutLoading] = useState(false); // Active payment state const [verificationResult, setVerificationResult] = useState(null); const [razorpayKeyId, setRazorpayKeyId] = useState(''); const [returnRoute, setReturnRoute] = useState(DEFAULT_RETURN_ROUTE); const [appScheme, setAppScheme] = useState(undefined); // Handle browser back button navigation useEffect(() => { const handlePopState = () => { // If purchase was completed and user presses the Back button, // redirect them to the mobile app's All Modules / Library instead of Subscription page if (verificationResult && verificationResult.status === 'success') { const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent); if (isMobile) { openMobileApp({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined }); } else { switchTab('subscriptions'); setVerificationResult(null); } return; } setActiveTab(getInitialTab()); }; window.addEventListener('popstate', handlePopState); return () => window.removeEventListener('popstate', handlePopState); }, [verificationResult, returnRoute, appScheme]); // Profile Update & Drawer State const [showProfileDrawer, setShowProfileDrawer] = useState(false); const [profileDisplayName, setProfileDisplayName] = useState(''); const [profilePhone, setProfilePhone] = useState(''); const [profileCountry, setProfileCountry] = useState('India'); const [profileSaving, setProfileSaving] = useState(false); const [profileError, setProfileError] = useState(null); const [profileSuccess, setProfileSuccess] = useState(false); // Dynamic Public Storefront Plans const [publicPlans, setPublicPlans] = useState([]); const fetchPublicPlans = async () => { try { const res = await axios.get(`${API_BASE}/api/plans`); if (Array.isArray(res.data)) { setPublicPlans(res.data); } } catch (err) { console.error('Failed to load public plans:', err); } }; const getLivePlan = (code: string) => { return publicPlans.find(p => p.code === code || p.base_code === code); }; const getModulePrice = (item: ModuleItem) => { const livePlan = getLivePlan(item.code); if (livePlan) { return { priceInr: livePlan.price_inr ?? item.priceInr, priceUsd: livePlan.price_usd ?? item.priceUsd, priceEur: item.priceEur, isActive: livePlan.is_active !== undefined ? livePlan.is_active : true, }; } return { priceInr: item.priceInr, priceUsd: item.priceUsd, priceEur: item.priceEur, isActive: true, }; }; // Load configuration & user profile on startup useEffect(() => { const params = new URLSearchParams(window.location.search); const urlToken = params.get('token'); const urlPlanCode = params.get('planCode'); const urlReturnRoute = params.get('returnRoute') || params.get('redirectPath') || params.get('redirect'); const urlScheme = params.get('scheme'); if (urlReturnRoute) { setReturnRoute(urlReturnRoute); } if (urlScheme) { setAppScheme(urlScheme); } let activeToken = userToken; if (urlToken) { localStorage.setItem('access_token', urlToken); setUserToken(urlToken); activeToken = urlToken; fetchUserProfile(urlToken); } if (urlPlanCode) { const targetModule = CURRICULUM_MODULES.find(m => m.code === urlPlanCode); if (targetModule) { setCart([targetModule]); setShowLockedByCategory(prev => ({ ...prev, [targetModule.category]: true })); } } if (urlToken || urlPlanCode) { const newUrl = window.location.pathname; window.history.replaceState({}, document.title, newUrl); } // Fetch public Razorpay Config axios.get(`${API_BASE}/api/checkout/config`) .then(res => { setRazorpayKeyId(res.data.razorpay_key_id); }) .catch(err => { console.error('Failed to load checkout config:', err); }); fetchPublicPlans(); if (activeToken && !urlToken) { fetchUserProfile(activeToken); } if (!activeToken && !urlToken) { setAuthMode('login'); setShowAuthModal(true); } }, [userToken]); // Recalculate price whenever cart, coupon, or currency changes useEffect(() => { if (cart.length === 0) { setPricingCalc(null); return; } calculatePricing(); }, [cart, appliedCoupon, currency]); // Update currency and dial code automatically on country selection during registration useEffect(() => { if (authMode === 'register') { const rule = getCountryRuleByName(authCountry); setCurrency(rule.currency); setAuthDialCode(rule.code); } }, [authCountry, authMode]); const fetchUserProfile = async (token: string) => { try { const headers = { 'Authorization': `Bearer ${token}` }; const [profileRes, accessRes] = await Promise.all([ axios.get(`${API_BASE}/api/auth/profile`, { headers }), axios.get(`${API_BASE}/api/access/me`, { headers }).catch(() => ({ data: {} })) ]); const mergedUser = { ...profileRes.data, active_subscriptions: accessRes.data.active_subscriptions || [], unlocked_module_slugs: accessRes.data.unlocked_module_slugs || [], }; setLoggedInUser(mergedUser); setProfileDisplayName(profileRes.data.display_name || ''); setProfilePhone(profileRes.data.phone_number || ''); setProfileCountry(profileRes.data.country || 'India'); const countryRule = getCountryRuleByName(profileRes.data.country || 'India'); setCurrency(countryRule.currency); } catch (err) { console.error('Failed to fetch user profile:', err); handleLogout(); } }; const handleLogout = () => { localStorage.removeItem('access_token'); setUserToken(null); setLoggedInUser(null); setCart([]); setAppliedCoupon(null); switchTab('storefront'); setShowProfileDrawer(false); setProfileDisplayName(''); setProfilePhone(''); setProfileCountry('India'); setProfileError(null); setProfileSuccess(false); }; const handleUpdateProfile = async (e: React.FormEvent) => { e.preventDefault(); if (!userToken) return; setProfileSaving(true); setProfileError(null); setProfileSuccess(false); if (profilePhone && profilePhone.trim()) { const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry); if (phoneError) { setProfileError(phoneError); setProfileSaving(false); return; } } try { await axios.put(`${API_BASE}/api/auth/profile`, { full_name: profileDisplayName, phone_number: profilePhone, country: profileCountry, }, { headers: { 'Authorization': `Bearer ${userToken}` } }); setProfileSuccess(true); await fetchUserProfile(userToken); setTimeout(() => setProfileSuccess(false), 3000); } catch (err: any) { console.error(err); setProfileError(err.response?.data?.detail || 'Failed to update profile details.'); } finally { setProfileSaving(false); } }; const handleAuthSubmit = async (e: React.FormEvent) => { e.preventDefault(); setAuthLoading(true); setAuthError(null); const trimmedEmail = authEmail.trim(); if (!trimmedEmail) { setAuthError('Email address is required.'); setAuthLoading(false); return; } const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(trimmedEmail)) { setAuthError('Please enter a valid email address.'); setAuthLoading(false); return; } if (!authPassword) { setAuthError('Password is required.'); setAuthLoading(false); return; } if (authMode === 'register' && !authDisplayName.trim()) { setAuthError('Display name is required.'); setAuthLoading(false); return; } if (authMode === 'register' && authPhone && authPhone.trim()) { const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry); if (phoneError) { setAuthError(phoneError); setAuthLoading(false); return; } } const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register'; if (authMode === 'register') { if (authPassword.length < 8) { setAuthError('Password must be at least 8 characters long.'); setAuthLoading(false); return; } if (!/[A-Z]/.test(authPassword)) { setAuthError('Password must contain at least one uppercase letter.'); setAuthLoading(false); return; } if (!/[0-9]/.test(authPassword)) { setAuthError('Password must contain at least one number.'); setAuthLoading(false); return; } if (!/[^A-Za-z0-9\s]/.test(authPassword)) { setAuthError('Password must contain at least one special character.'); setAuthLoading(false); return; } } const fullPhone = authPhone ? `${authDialCode}${authPhone}` : undefined; const payload = authMode === 'login' ? { email: trimmedEmail, password: authPassword } : { email: trimmedEmail, password: authPassword, full_name: authDisplayName.trim() || undefined, phone_number: fullPhone, country: authCountry }; try { const res = await axios.post(`${API_BASE}${endpoint}`, payload); const token = res.data.access_token; localStorage.setItem('access_token', token); setUserToken(token); await fetchUserProfile(token); setShowAuthModal(false); setAuthPassword(''); setAuthEmail(''); setAuthDisplayName(''); setAuthPhone(''); } catch (err: any) { setAuthError(err.response?.data?.detail || 'Authentication failed. Please check credentials.'); } finally { setAuthLoading(false); } }; const handleChangePassword = async (e: React.FormEvent) => { e.preventDefault(); if (!userToken) return; setChangePasswordError(null); setChangePasswordSuccess(false); if (!changeOldPassword) { setChangePasswordError('Please enter your current password.'); return; } if (changeNewPassword.length < 8) { setChangePasswordError('New password must be at least 8 characters long.'); return; } if (!/[A-Z]/.test(changeNewPassword)) { setChangePasswordError('New password must contain at least one uppercase letter.'); return; } if (!/[0-9]/.test(changeNewPassword)) { setChangePasswordError('New password must contain at least one number.'); return; } if (!/[^A-Za-z0-9\s]/.test(changeNewPassword)) { setChangePasswordError('New password must contain at least one special character.'); return; } if (changeNewPassword !== changeConfirmPassword) { setChangePasswordError('New passwords do not match.'); return; } setChangePasswordLoading(true); try { await axios.post(`${API_BASE}/api/auth/change-password`, { old_password: changeOldPassword, new_password: changeNewPassword }, { headers: { 'Authorization': `Bearer ${userToken}` } }); setChangePasswordSuccess(true); setPasswordUpdatedPopup(true); setChangeOldPassword(''); setChangeNewPassword(''); setChangeConfirmPassword(''); setShowPasswordChange(false); } catch (err: any) { console.error(err); setChangePasswordError(err.response?.data?.detail || 'Failed to update password.'); } finally { setChangePasswordLoading(false); } }; const handleForgotPasswordRequest = async (e: React.FormEvent) => { e.preventDefault(); setAuthLoading(true); setAuthError(null); setResetSuccessMessage(null); const trimmedEmail = authEmail.trim(); if (!trimmedEmail) { setAuthError('Email address is required.'); setAuthLoading(false); return; } const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(trimmedEmail)) { setAuthError('Please enter a valid email address.'); setAuthLoading(false); return; } try { const res = await axios.post(`${API_BASE}/api/auth/forgot-password`, { email: trimmedEmail }); setResetSuccessMessage(res.data.message || 'Verification code sent to your email.'); setResetStep('verify'); } catch (err: any) { console.error(err); setAuthError(err.response?.data?.detail || 'Failed to send reset code.'); } finally { setAuthLoading(false); } }; const handleResetPasswordSubmit = async (e: React.FormEvent) => { e.preventDefault(); setAuthLoading(true); setAuthError(null); if (resetNewPassword.length < 8) { setAuthError('New password must be at least 8 characters long.'); setAuthLoading(false); return; } if (!/[A-Z]/.test(resetNewPassword)) { setAuthError('New password must contain at least one uppercase letter.'); setAuthLoading(false); return; } if (!/[0-9]/.test(resetNewPassword)) { setAuthError('New password must contain at least one number.'); setAuthLoading(false); return; } if (!/[^A-Za-z0-9\s]/.test(resetNewPassword)) { setAuthError('New password must contain at least one special character.'); setAuthLoading(false); return; } if (resetNewPassword !== resetConfirmPassword) { setAuthError('Passwords do not match.'); setAuthLoading(false); return; } try { await axios.post(`${API_BASE}/api/auth/reset-password`, { email: authEmail, otp_code: resetOtp, new_password: resetNewPassword }); setPasswordUpdatedPopup(true); setAuthMode('login'); setResetStep('request'); setResetOtp(''); setResetNewPassword(''); setResetConfirmPassword(''); setAuthPassword(''); setAuthError(null); } catch (err: any) { console.error(err); setAuthError(err.response?.data?.detail || 'Failed to reset password.'); } finally { setAuthLoading(false); } }; // Keep cart items dynamic prices updated when publicPlans are loaded useEffect(() => { if (publicPlans.length > 0 && cart.length > 0) { setCart(prev => prev.map(item => { const live = getModulePrice(item); return { ...item, priceInr: live.priceInr, priceUsd: live.priceUsd, }; }) ); } }, [publicPlans]); const calculatePricing = async () => { setLoadingPricing(true); try { const headers = userToken ? { 'Authorization': `Bearer ${userToken}` } : {}; const res = await axios.post(`${API_BASE}/api/cart/calculate`, { cart_item_codes: cart.map(item => item.code), coupon_code: appliedCoupon || undefined, currency: currency }, { headers }); const calcData = res.data; if (appliedCoupon && (!calcData.coupon_applied || calcData.coupon_applied === 'None')) { calcData.coupon_error = calcData.coupon_error || 'Invalid or expired coupon code.'; } setPricingCalc(calcData); } catch (err: any) { console.error('Pricing engine calculation error:', err); if (appliedCoupon) { const errorMsg = err.response?.data?.detail || 'Invalid or expired coupon code.'; setPricingCalc((prev: any) => ({ ...(prev || {}), coupon_error: errorMsg, })); } else { setPricingCalc(null); } } finally { setLoadingPricing(false); } }; const toggleCartItem = (module: ModuleItem) => { if (isModuleUnlocked(module.code)) return; const live = getModulePrice(module); if (!live.isActive) return; const dynamicModule: ModuleItem = { ...module, priceInr: live.priceInr, priceUsd: live.priceUsd, }; const exists = cart.find(item => item.code === module.code); if (exists) { setCart(cart.filter(item => item.code !== module.code)); } else { if (module.code === 'LIFETIME_ALL') { setCart([dynamicModule]); } else if (module.code === 'POINTS_PACK') { setCart([ ...cart.filter(item => !['LIFETIME_ALL', 'POINTS_ACU', 'POINTS_SCALP', 'POINTS_EAR', 'POINTS_TUNG'].includes(item.code)), dynamicModule ]); } else if (['POINTS_ACU', 'POINTS_SCALP', 'POINTS_EAR', 'POINTS_TUNG'].includes(module.code)) { setCart([ ...cart.filter(item => !['LIFETIME_ALL', 'POINTS_PACK'].includes(item.code)), dynamicModule ]); } else if (module.code === 'THERAPEUTICS_CORE') { setCart([ ...cart.filter(item => !['LIFETIME_ALL', 'THERAPEUTICS_GYNAE', 'THERAPEUTICS_EAR'].includes(item.code)), dynamicModule ]); } else if (['THERAPEUTICS_GYNAE', 'THERAPEUTICS_EAR'].includes(module.code)) { setCart([ ...cart.filter(item => !['LIFETIME_ALL', 'THERAPEUTICS_CORE'].includes(item.code)), dynamicModule ]); } else { setCart([...cart.filter(item => item.code !== 'LIFETIME_ALL'), dynamicModule]); } } }; const applyPromoCode = () => { if (!couponCode.trim()) return; setAppliedCoupon(couponCode.toUpperCase().trim()); }; const removePromoCode = () => { setAppliedCoupon(null); setCouponCode(''); setPricingCalc((prev: any) => (prev ? { ...prev, coupon_error: null } : null)); }; const isModuleUnlocked = (code: string) => { if (!loggedInUser?.active_subscriptions) return false; const hasLifetime = loggedInUser.active_subscriptions.some((sub: any) => sub.plan_code === 'LIFETIME_ALL' || sub.plan_code === 'LIFETIME_ALL_USD' ); if (hasLifetime) return true; if (code === 'POINTS_ACU' || code === 'POINTS_SCALP' || code === 'POINTS_EAR' || code === 'POINTS_TUNG') { const hasPointsPack = loggedInUser.active_subscriptions.some((sub: any) => sub.plan_code === 'POINTS_PACK' || sub.plan_code === 'POINTS_PACK_USD' ); if (hasPointsPack) return true; } if (code === 'THERAPEUTICS_GYNAE' || code === 'THERAPEUTICS_EAR') { const hasTherapeuticsPack = loggedInUser.active_subscriptions.some((sub: any) => sub.plan_code === 'THERAPEUTICS_CORE' || sub.plan_code === 'THERAPEUTICS_CORE_USD' ); if (hasTherapeuticsPack) return true; } return loggedInUser.active_subscriptions.some((sub: any) => sub.plan_code === code || sub.plan_code === `${code}_USD`); }; // Automatically remove already unlocked modules from the cart useEffect(() => { if (loggedInUser && cart.length > 0) { const filteredCart = cart.filter(item => !isModuleUnlocked(item.code)); if (filteredCart.length !== cart.length) { setCart(filteredCart); } } }, [loggedInUser, cart]); const handleCheckout = async () => { if (cart.length === 0 || checkoutLoading) return; if (!userToken) { setAuthMode('register'); setShowAuthModal(true); return; } setCheckoutLoading(true); setVerificationResult(null); const isCouponValid = Boolean( pricingCalc && pricingCalc.coupon_applied && pricingCalc.coupon_applied !== 'None' && !pricingCalc.coupon_error ); try { const orderRes = await axios.post(`${API_BASE}/api/checkout/create-order`, { cart_item_codes: cart.map(item => item.code), coupon_code: isCouponValid ? appliedCoupon : undefined, currency: currency }, { headers: { 'Authorization': `Bearer ${userToken}` } }); const { razorpay_order_id, grand_total } = orderRes.data; const sdkLoaded = await loadRazorpayScript(); if (!sdkLoaded) { alert('Failed to load Razorpay SDK. Please check your network connection.'); setCheckoutLoading(false); return; } if (!razorpayKeyId) { alert('Payment system configuration is loading. Please try again in a moment.'); setCheckoutLoading(false); return; } if (!loggedInUser?.phone_number) { const inputPhone = prompt("A billing phone number is required for Razorpay checkout. Please enter your contact number:"); if (!inputPhone) { setCheckoutLoading(false); return; } const cleanedPhone = cleanPhoneInput(inputPhone); const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India'); if (phoneError) { alert(phoneError); setCheckoutLoading(false); return; } try { const res = await axios.put(`${API_BASE}/api/auth/profile`, { phone_number: cleanedPhone }, { headers: { 'Authorization': `Bearer ${userToken}` } }); if (res.data.status === 'success') { loggedInUser.phone_number = inputPhone; setLoggedInUser({ ...loggedInUser }); } } catch (err: any) { alert("Failed to save phone number: " + (err.response?.data?.detail || err.message)); setCheckoutLoading(false); return; } } let isPaymentCancelled = false; let isPaymentCompleted = false; const rzpOptions = { key: razorpayKeyId, amount: Math.round(grand_total * 100), currency: currency, name: 'Acupedia', description: cart.map(c => c.name).join(', '), order_id: razorpay_order_id, customer_id: loggedInUser?.external_ref || undefined, prefill: { name: loggedInUser?.display_name || '', email: loggedInUser?.email || '', contact: loggedInUser?.phone_number || loggedInUser?.phone || '' }, modal: { confirm_close: true, escape: true, backdropclose: false, ondismiss: function () { if (!isPaymentCompleted) { isPaymentCancelled = true; setCheckoutLoading(false); console.log('Razorpay payment modal dismissed / cancelled by user.'); } } }, handler: async function (response: any) { if (isPaymentCancelled) { console.warn('Payment was cancelled by the user. Verification ignored.'); setCheckoutLoading(false); return; } isPaymentCompleted = true; setCheckoutLoading(true); try { const verifyRes = await axios.post(`${API_BASE}/api/checkout/verify`, { razorpay_order_id: response.razorpay_order_id, razorpay_payment_id: response.razorpay_payment_id, razorpay_signature: response.razorpay_signature, currency: currency }, { headers: { 'Authorization': `Bearer ${userToken}` } }); setVerificationResult({ status: 'success', paymentId: response.razorpay_payment_id, orderId: response.razorpay_order_id, invoiceNumber: verifyRes.data.invoice_number, invoiceUrl: verifyRes.data.invoice_url, amount: grand_total, currency: currency, items: cart.map(c => c.name), message: verifyRes.data.message || 'Payment verified successfully and module entitlements unlocked!' }); // Push a history state so that pressing browser/device Back button will be intercepted // by popstate and redirected to All Modules / Library instead of returning to the Subscription page if (typeof window !== 'undefined') { window.history.pushState({ paymentCompleted: true }, document.title, window.location.href); } if (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) { setTimeout(() => { if (/Android/i.test(navigator.userAgent)) { // Use Android Intent format to avoid blocked navigation in Android Chrome window.location.href = 'intent://#Intent;scheme=acupedia;package=com.anonymous.acupedia;end'; setTimeout(() => { window.location.href = 'acupedia://'; }, 500); } else { window.location.href = 'acupedia://'; } }, 1500); } setCart([]); setAppliedCoupon(null); await fetchUserProfile(userToken); } catch (err: any) { setVerificationResult({ status: 'error', message: err.response?.data?.detail || 'Signature verification failed.' }); } finally { setCheckoutLoading(false); } }, theme: { color: '#6366F1' } }; const razorpayInstance = new (window as any).Razorpay(rzpOptions); razorpayInstance.on('payment.failed', function (resp: any) { setCheckoutLoading(false); alert(`Payment failed! Reason: ${resp.error.description}`); }); razorpayInstance.open(); } catch (err: any) { console.error(err); alert(err.response?.data?.detail || 'Failed to initialize Razorpay checkout transaction.'); } finally { setCheckoutLoading(false); } }; const [downloadingModalInvoice, setDownloadingModalInvoice] = useState(false); const handleDownloadCheckoutInvoice = async (paymentId: string, directUrl?: string) => { if (directUrl) { window.open(directUrl, '_blank'); switchTab('subscriptions'); setVerificationResult(null); return; } if (!userToken) return; setDownloadingModalInvoice(true); try { const headers = { 'Authorization': `Bearer ${userToken}` }; const res = await axios.get(`${API_BASE}/api/checkout/payment/${paymentId}/invoice`, { headers }); const { short_url } = res.data; if (short_url) { window.open(short_url, '_blank'); switchTab('subscriptions'); setVerificationResult(null); } else { throw new Error('Invoice download URL is not available.'); } } catch (err: any) { const errorMsg = err.response?.data?.detail || err.message || String(err); alert(`Could not download invoice: ${errorMsg}`); } finally { setDownloadingModalInvoice(false); } }; const hasUserLifetimeAccess = loggedInUser?.active_subscriptions?.some((sub: any) => sub.plan_code === 'LIFETIME_ALL' || sub.plan_code === 'LIFETIME_ALL_USD' ); return (
{/* ๐Ÿงญ Storefront Header */} setShowProfileDrawer(true)} onOpenAuth={(mode) => { setAuthMode(mode); setShowAuthModal(true); }} /> {/* ๐Ÿ“ฆ Main Body */}
{activeTab === 'storefront' ? (
{/* ๐Ÿ… Dynamic Gold Lifetime Banner */} {hasUserLifetimeAccess && }
{/* ๐Ÿ“ฆ Catalog Section */} {/* ๐Ÿ›’ Cart Drawer Summary */} { const newPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || ''); if (newPhone !== null && loggedInUser) { try { const res = await axios.put(`${API_BASE}/api/auth/profile`, { phone_number: newPhone }, { headers: { 'Authorization': `Bearer ${userToken}` } }); if (res.data.status === 'success') { setLoggedInUser({ ...loggedInUser, phone_number: newPhone }); alert('Phone number updated successfully for billing!'); } } catch (err: any) { alert(err.response?.data?.detail || 'Failed to update phone number.'); } } }} verificationResult={verificationResult} checkoutLoading={checkoutLoading} handleCheckout={handleCheckout} />
) : ( /* ๐Ÿงพ Tab: User Personal Subscriptions Ledger */ { setAuthMode('login'); setShowAuthModal(true); }} onSwitchTab={switchTab} curriculumModules={CURRICULUM_MODULES} /> )} {/* ๐Ÿ’ณ Footer */}
{/* ๐Ÿ” Auth Modal (Login / Register / Forgot Password) */} setShowAuthModal(false)} authMode={authMode} setAuthMode={setAuthMode} authEmail={authEmail} setAuthEmail={setAuthEmail} authPassword={authPassword} setAuthPassword={setAuthPassword} authDisplayName={authDisplayName} setAuthDisplayName={setAuthDisplayName} authPhone={authPhone} setAuthPhone={setAuthPhone} authDialCode={authDialCode} setAuthDialCode={setAuthDialCode} authCountry={authCountry} setAuthCountry={setAuthCountry} authLoading={authLoading} authError={authError} setAuthError={setAuthError} onAuthSubmit={handleAuthSubmit} resetStep={resetStep} setResetStep={setResetStep} resetOtp={resetOtp} setResetOtp={setResetOtp} resetNewPassword={resetNewPassword} setResetNewPassword={setResetNewPassword} resetConfirmPassword={resetConfirmPassword} setResetConfirmPassword={setResetConfirmPassword} resetSuccessMessage={resetSuccessMessage} setResetSuccessMessage={setResetSuccessMessage} onForgotPasswordRequest={handleForgotPasswordRequest} onResetPasswordSubmit={handleResetPasswordSubmit} /> {/* ๐ŸŽ‰ Payment Success Modal */} {verificationResult && verificationResult.status === 'success' && ( setVerificationResult(null)} loggedInUser={loggedInUser} onDownloadInvoice={handleDownloadCheckoutInvoice} downloadingInvoice={downloadingModalInvoice} returnRoute={returnRoute} appScheme={appScheme} /> )} {/* ๐Ÿงญ Profile Drawer */} setShowProfileDrawer(false)} loggedInUser={loggedInUser} profileDisplayName={profileDisplayName} setProfileDisplayName={setProfileDisplayName} profilePhone={profilePhone} setProfilePhone={setProfilePhone} profileCountry={profileCountry} setProfileCountry={setProfileCountry} setCurrency={setCurrency} profileSaving={profileSaving} profileError={profileError} profileSuccess={profileSuccess} onUpdateProfile={handleUpdateProfile} showPasswordChange={showPasswordChange} setShowPasswordChange={setShowPasswordChange} changeOldPassword={changeOldPassword} setChangeOldPassword={setChangeOldPassword} changeNewPassword={changeNewPassword} setChangeNewPassword={setChangeNewPassword} changeConfirmPassword={changeConfirmPassword} setChangeConfirmPassword={setChangeConfirmPassword} changePasswordLoading={changePasswordLoading} changePasswordError={changePasswordError} changePasswordSuccess={changePasswordSuccess} onChangePassword={handleChangePassword} onLogout={handleLogout} onBrowseStorefront={() => { setShowProfileDrawer(false); switchTab('storefront'); }} curriculumModules={CURRICULUM_MODULES} /> {/* ๐Ÿ” Password Updated Success Modal */} setPasswordUpdatedPopup(false)} />
); }