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, validatePassword } 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); } }; // Dynamic Curriculum Modules with Live Categories const [curriculumModules, setCurriculumModules] = useState(CURRICULUM_MODULES); const fetchModuleCategories = async () => { try { const res = await axios.get(`${API_BASE}/api/contents/modules`); const apiModules: any[] = res.data?.modules || []; if (apiModules.length > 0) { const normalizeCategory = (cat?: string) => { if (!cat) return null; const c = cat.toLowerCase(); if (c === 'point' || c === 'points') return 'Points'; if (c === 'pattern' || c === 'patterns') return 'Pattern'; if (c === 'nutrition') return 'Nutrition'; if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics'; return cat; }; setCurriculumModules((prev) => prev.map((item) => { const matched = apiModules.find((m) => { const mCode = (m.code || '').toLowerCase(); const iCode = (item.code || '').toLowerCase(); if (mCode && iCode && mCode === iCode) return true; const slug = (m.slug || '').toLowerCase(); const mName = (m.name || '').toLowerCase(); const iName = item.name.toLowerCase(); const cleanI = iName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim(); const cleanM = mName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim(); if (cleanI.includes('acu') && cleanM.includes('acupuncture') && !cleanI.includes('scalp') && !cleanI.includes('ear')) return true; if (cleanI.includes('scalp') && cleanM.includes('scalp')) return true; if (cleanI.includes('ear') && (cleanM.includes('ear') || slug.includes('auriculo'))) return true; if (cleanI.includes('gyneco') && slug.includes('gyneco')) return true; if (cleanI.includes('eight') && slug.includes('eight')) return true; if (cleanI.includes('zang') && slug.includes('tcm-pattern')) return true; if (cleanI.includes('qi') && slug.includes('qi')) return true; if (cleanI.includes('pathogenic') && slug.includes('pathogenic')) return true; if (cleanI.includes('six') && slug.includes('six')) return true; if (cleanI.includes('four') && slug.includes('four')) return true; if (cleanI.includes('three') && slug.includes('three')) return true; if (cleanI.includes('five') && slug.includes('five')) return true; if (cleanI.includes('food') && slug.includes('nutrition')) return true; return false; }); const updatedCat = normalizeCategory(matched?.metadata?.category || matched?.category); if (updatedCat) { return { ...item, category: updatedCat }; } return item; }) ); } } catch (err) { console.error('Failed to load module categories:', 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 = curriculumModules.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(); fetchModuleCategories(); if (activeToken && !urlToken) { fetchUserProfile(activeToken); } if (!activeToken && !urlToken) { setAuthMode('login'); setShowAuthModal(true); } }, [userToken]); // Recalculate price whenever cart, coupon, currency, or logged-in user changes useEffect(() => { if (cart.length === 0) { setPricingCalc(null); return; } calculatePricing(); }, [cart, appliedCoupon, currency, loggedInUser]); // 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); let cleanedPhoneToSave: string | null = null; if (profilePhone && profilePhone.trim()) { const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry); if (phoneError) { setProfileError(phoneError); setProfileSaving(false); return; } cleanedPhoneToSave = cleanPhoneInput(profilePhone.trim(), 16, true); } try { await axios.put(`${API_BASE}/api/auth/profile`, { full_name: profileDisplayName, phone_number: cleanedPhoneToSave, 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; } let fullPhone: string | undefined = undefined; if (authMode === 'register' && authPhone && authPhone.trim()) { const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry); if (phoneError) { setAuthError(phoneError); setAuthLoading(false); return; } const rawDigits = authPhone.replace(/\D/g, ''); fullPhone = `${authDialCode}${rawDigits}`; } const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register'; if (authMode === 'register') { const pwdError = validatePassword(authPassword, 'Password'); if (pwdError) { setAuthError(pwdError); setAuthLoading(false); return; } } 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; } const pwdError = validatePassword(changeNewPassword, 'New password'); if (pwdError) { setChangePasswordError(pwdError); 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); const pwdError = validatePassword(resetNewPassword, 'New password'); if (pwdError) { setAuthError(pwdError); 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}` } : {}; // Derive owned categories from loggedInUser to ensure loyalty discounts apply automatically const userOwnedCategories: string[] = []; if (loggedInUser?.active_subscriptions) { for (const sub of loggedInUser.active_subscriptions) { const code = (sub.plan_code || '').toUpperCase(); if (code.startsWith('POINT')) userOwnedCategories.push('Points'); else if (code.startsWith('PATTERN')) userOwnedCategories.push('Pattern'); else if (code.startsWith('NUTRITION')) userOwnedCategories.push('Nutrition'); else if (code.startsWith('THERAPEUTIC')) userOwnedCategories.push('Therapeutics'); else if (code === 'LIFETIME_ALL' || code === 'LIFETIME_ALL_USD') userOwnedCategories.push('Lifetime'); } } if (loggedInUser?.unlocked_module_slugs) { for (const slug of loggedInUser.unlocked_module_slugs) { const s = slug.toLowerCase(); if (s.includes('point') || s.includes('ear') || s.includes('scalp') || s.includes('tung')) userOwnedCategories.push('Points'); else if (s.includes('pattern') || s.includes('eight') || s.includes('principles') || s.includes('zang') || s.includes('stages') || s.includes('burners') || s.includes('channels') || s.includes('elements') || s.includes('vessel')) userOwnedCategories.push('Pattern'); else if (s.includes('nutrition') || s.includes('food')) userOwnedCategories.push('Nutrition'); else if (s.includes('therapeutic') || s.includes('gynae') || s.includes('auriculo')) userOwnedCategories.push('Therapeutics'); } } const uniqueOwnedCategories = Array.from(new Set(userOwnedCategories)); const res = await axios.post(`${API_BASE}/api/cart/calculate`, { cart_item_codes: cart.map(item => item.code), owned_category_names: uniqueOwnedCategories, is_first_purchase: uniqueOwnedCategories.length === 0, coupon_code: appliedCoupon || undefined, currency: currency }, { headers }); const calcData = res.data; if (appliedCoupon && (!calcData.coupon_applied || calcData.coupon_applied === 'None' || calcData.coupon_discount_amount <= 0)) { 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) => { if (!prev || prev.currency !== currency) { return { currency, coupon_error: errorMsg, }; } return { ...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_discount_amount > 0 && !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, 16, true); 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 = cleanedPhone; 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 || '' }, readonly: { contact: true, email: true, name: true }, 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); } 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) => { setDownloadingModalInvoice(true); try { let targetUrl = directUrl; if (!targetUrl || targetUrl.includes('rzp.io') || targetUrl.includes('razorpay.com')) { targetUrl = `/api/checkout/payment/${paymentId}/invoice/view`; } if (!targetUrl.startsWith('http')) { targetUrl = `${API_BASE}${targetUrl.startsWith('/') ? '' : '/'}${targetUrl}`; } window.open(targetUrl, '_blank'); switchTab('subscriptions'); setVerificationResult(null); } 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 inputPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || ''); if (inputPhone === null || !loggedInUser) return; const trimmed = inputPhone.trim(); if (!trimmed) { alert("A billing phone number is required."); return; } const cleanedPhone = cleanPhoneInput(trimmed, 16, true); const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser.country || 'India'); if (phoneError) { alert(phoneError); return; } try { const res = await axios.put(`${API_BASE}/api/auth/profile`, { phone_number: cleanedPhone }, { headers: { 'Authorization': `Bearer ${userToken}` } }); if (res.data.status === 'success') { setLoggedInUser({ ...loggedInUser, phone_number: cleanedPhone }); 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={curriculumModules} onDownloadInvoice={handleDownloadCheckoutInvoice} /> )} {/* ๐Ÿ’ณ 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={curriculumModules} onDownloadInvoice={handleDownloadCheckoutInvoice} /> {/* ๐Ÿ” Password Updated Success Modal */} setPasswordUpdatedPopup(false)} />
); }