import { useState, useEffect, useMemo } 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 { validatePhoneNumber, isValidPhoneNumber, validatePassword, parsePhoneNumber, formatE164Phone, validateEmail } 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 { BillingPhoneModal } from './components/checkout/BillingPhoneModal'; import { LoggedOutView } from './components/auth/LoggedOutView'; import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation'; const getInitialTab = (): 'storefront' | 'subscriptions' | 'logged-out' => { if (typeof window !== 'undefined') { const path = window.location.pathname.toLowerCase(); if (path.includes('/logged-out')) return 'logged-out'; if (path.includes('/subscriptions')) return 'subscriptions'; const params = new URLSearchParams(window.location.search); if (params.get('logged_out') === 'true' || params.get('status') === 'logged-out') { return 'logged-out'; } } return 'storefront'; }; const getInitialRegion = (): { currency: Currency; country: string; dialCode: string } => { if (typeof Intl !== 'undefined') { try { const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; if (tz.includes('Kolkata') || tz.includes('Calcutta')) { return { currency: 'INR', country: 'India', dialCode: '+91' }; } if (tz.startsWith('Europe/')) { return { currency: 'EUR', country: 'Germany', dialCode: '+49' }; } } catch { // ignore } } return { currency: 'USD', country: 'United States', dialCode: '+1' }; }; export default function App() { const [activeTab, setActiveTab] = useState<'storefront' | 'subscriptions' | 'logged-out'>(getInitialTab); const switchTab = (tab: 'storefront' | 'subscriptions' | 'logged-out') => { 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 initialRegion = useMemo(getInitialRegion, []); const [currency, setCurrency] = useState(initialRegion.currency); // 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); // Auto-clear change password success banner after 4 seconds useEffect(() => { if (changePasswordSuccess) { const timer = setTimeout(() => { setChangePasswordSuccess(false); }, 4000); return () => clearTimeout(timer); } }, [changePasswordSuccess]); // Auth Form State const [authEmail, setAuthEmail] = useState(''); const [authPassword, setAuthPassword] = useState(''); const [authDisplayName, setAuthDisplayName] = useState(''); const [authPhone, setAuthPhone] = useState(''); const [authDialCode, setAuthDialCode] = useState(initialRegion.dialCode); const [authCountry, setAuthCountry] = useState(initialRegion.country); 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); setCart([]); setAppliedCoupon(null); setCouponCode(''); setPricingCalc(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); // Billing Contact Phone Modal State const [showBillingPhoneModal, setShowBillingPhoneModal] = useState(false); const [pendingCheckoutAfterPhone, setPendingCheckoutAfterPhone] = 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); fetchModuleCategories(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 (plansList?: PublicPlan[]) => { try { const res = await axios.get(`${API_BASE}/api/contents/modules`); const apiModules: any[] = res.data?.modules || []; const currentPlans = plansList && plansList.length > 0 ? plansList : publicPlans; if (apiModules.length > 0) { const normalizeCategory = (cat?: string): string | null => { if (!cat) return null; const c = cat.toLowerCase().trim(); if (c === 'point' || c === 'points') return 'Points'; if (c === 'pattern' || c === 'patterns' || c === 'five-elements') return 'Pattern'; if (c === 'nutrition') return 'Nutrition'; if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics'; if (c === 'lifetime') return 'Lifetime'; return cat.charAt(0).toUpperCase() + cat.slice(1); }; setCurriculumModules((prev) => prev.map((item) => { // 1. If item maps directly to a plan with single module slug, match by that slug const matchedPlan = currentPlans.find((p) => p.code === item.code || p.base_code === item.code); let matched: any = null; if (matchedPlan) { const slugs: string[] = matchedPlan.module_slugs || (matchedPlan.modules || []).map((m: any) => m.slug).filter(Boolean); if (slugs.length === 1) { const targetSlug = slugs[0].toLowerCase(); matched = apiModules.find((m) => (m.slug || '').toLowerCase() === targetSlug); } } // 2. Direct code match if (!matched) { const iCode = (item.code || '').toLowerCase(); matched = apiModules.find((m) => (m.code || '').toLowerCase() === iCode); } // 3. Normalized semantic match without collisions if (!matched) { const iName = item.name.toLowerCase(); const cleanI = iName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim(); matched = apiModules.find((m) => { const mSlug = (m.slug || '').toLowerCase(); const mName = (m.name || '').toLowerCase(); const cleanM = mName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim(); if (cleanI.includes('scalp') && (cleanM.includes('scalp') || mSlug.includes('scalp'))) return true; // Disambiguate Ear Reflexology / Auriculotherapy vs Ear Acupuncture if (cleanI.includes('reflexology') || item.code === 'THERAPEUTICS_EAR') { return mSlug.includes('auriculo') || cleanM.includes('reflexology') || mSlug.includes('reflexology'); } if (cleanI.includes('ear') || item.code === 'POINTS_EAR') { return mSlug.includes('ear-acupuncture') || (cleanM.includes('ear') && !mSlug.includes('auriculo') && !cleanM.includes('reflexology')); } if (cleanI.includes('acu') && cleanM.includes('acupuncture') && !cleanI.includes('scalp') && !cleanI.includes('ear')) return true; if (cleanI.includes('gyneco') && mSlug.includes('gyneco')) return true; if (cleanI.includes('eight') && mSlug.includes('eight')) return true; if (cleanI.includes('zang') && mSlug.includes('tcm-pattern')) return true; if (cleanI.includes('qi') && mSlug.includes('qi')) return true; if (cleanI.includes('pathogenic') && mSlug.includes('pathogenic')) return true; if (cleanI.includes('six') && mSlug.includes('six')) return true; if (cleanI.includes('four') && mSlug.includes('four')) return true; if (cleanI.includes('three') && mSlug.includes('three')) return true; if (cleanI.includes('five') && mSlug.includes('five')) return true; if (cleanI.includes('food') && mSlug.includes('nutrition')) return true; return false; }); } const rawCat = matched?.category || matched?.metadata?.category || matched?.metadata?.kind; const updatedCat = normalizeCategory(rawCat); 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: livePlan.price_eur ?? livePlan.price_usd ?? 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(() => { // Normalize URL if opened at /store without trailing slash if (typeof window !== 'undefined' && window.location.pathname === '/store') { const normalizedPath = '/store/' + (window.location.search || '') + (window.location.hash || ''); window.history.replaceState(window.history.state, document.title, normalizedPath); } 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'); const shouldOpenLogin = params.get('login') === 'true' || params.get('auth') === 'login'; if (shouldOpenLogin) { setAuthMode('login'); setShowAuthModal(true); } if (urlReturnRoute) { setReturnRoute(urlReturnRoute); } if (urlScheme) { setAppScheme(urlScheme); } let activeToken = urlToken || localStorage.getItem('access_token'); if (urlToken) { localStorage.setItem('access_token', urlToken); setUserToken(urlToken); fetchUserProfile(urlToken); setShowAuthModal(false); } else if (activeToken) { fetchUserProfile(activeToken); } if (urlPlanCode) { const normalizedPlanCode = urlPlanCode.trim().toUpperCase(); const targetModule = curriculumModules.find(m => m.code.toUpperCase() === normalizedPlanCode); if (targetModule) { setCart([targetModule]); setShowLockedByCategory(prev => ({ ...prev, [targetModule.category]: true })); } } if (urlToken || urlPlanCode || shouldOpenLogin) { const isStorePrefix = window.location.pathname.startsWith('/store'); const basePath = isStorePrefix ? '/store/' : '/'; const cleanPath = activeTab === 'subscriptions' ? `${basePath}subscriptions` : activeTab === 'logged-out' ? `${basePath}logged-out` : basePath; window.history.replaceState({}, document.title, cleanPath); } // 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(); }, []); // 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 handleCloseProfileDrawer = () => { setShowProfileDrawer(false); setShowPasswordChange(false); setChangePasswordError(null); setChangePasswordSuccess(false); setChangeOldPassword(''); setChangeNewPassword(''); setChangeConfirmPassword(''); }; const handleLogout = () => { localStorage.removeItem('access_token'); setUserToken(null); setLoggedInUser(null); setCart([]); setAppliedCoupon(null); setCouponCode(''); setPricingCalc(null); handleCloseProfileDrawer(); setProfileDisplayName(''); setProfilePhone(''); setProfileCountry(initialRegion.country); setCurrency(initialRegion.currency); setProfileError(null); setProfileSuccess(false); setShowAuthModal(false); switchTab('logged-out'); }; 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 parsed = parsePhoneNumber(profilePhone, profileCountry); const phoneError = validatePhoneNumber(parsed.localDigits, parsed.dialCode, profileCountry); if (phoneError) { setProfileError(phoneError); setProfileSaving(false); return; } cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits, profileCountry); } 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 handleSaveBillingPhone = async (phoneE164: string, country: string): Promise => { if (!userToken) return false; try { const res = await axios.put(`${API_BASE}/api/auth/profile`, { phone_number: phoneE164, country: country, }, { headers: { 'Authorization': `Bearer ${userToken}` } }); if (res.data.status === 'success') { if (loggedInUser) { loggedInUser.phone_number = phoneE164; loggedInUser.country = country; setLoggedInUser({ ...loggedInUser }); } setProfilePhone(phoneE164); setProfileCountry(country); const countryRule = getCountryRuleByName(country); setCurrency(countryRule.currency); setShowBillingPhoneModal(false); if (pendingCheckoutAfterPhone) { setPendingCheckoutAfterPhone(false); setTimeout(() => { handleCheckout(); }, 200); } return true; } return false; } catch (err: any) { const errorMsg = err.response?.data?.detail || 'Failed to save billing phone number.'; alert(errorMsg); throw new Error(errorMsg); } }; const handleAuthSubmit = async (e: React.FormEvent) => { e.preventDefault(); setAuthLoading(true); setAuthError(null); const trimmedEmail = authEmail.trim(); const emailErr = validateEmail(trimmedEmail); if (emailErr) { setAuthError(emailErr); 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; } fullPhone = formatE164Phone(authDialCode, authPhone, authCountry); } 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(''); if (activeTab === 'logged-out') { switchTab('storefront'); } setShowPasswordChange(false); setChangeOldPassword(''); setChangeNewPassword(''); setChangeConfirmPassword(''); setChangePasswordError(null); setChangePasswordSuccess(false); } 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 (changeOldPassword === changeNewPassword) { setChangePasswordError('New password cannot be the same as current password.'); return; } if (changeNewPassword !== changeConfirmPassword) { setChangePasswordError('Confirm password 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}` } }); const userEmail = loggedInUser?.email || authEmail; // Invalidate active session so re-authentication is required handleLogout(); setShowProfileDrawer(false); // Pre-fill email and set auth mode to login for seamless re-auth setAuthEmail(userEmail); setAuthPassword(''); setAuthMode('login'); setAuthError(null); setChangeOldPassword(''); setChangeNewPassword(''); setChangeConfirmPassword(''); setShowPasswordChange(false); setChangePasswordSuccess(false); setChangePasswordError(null); setPasswordUpdatedPopup(true); } 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(); const emailErr = validateEmail(trimmedEmail); if (emailErr) { setAuthError(emailErr); 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, priceEur: live.priceEur, }; }) ); } }, [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, priceEur: live.priceEur, }; const exists = cart.find(item => item.code === module.code); if (exists) { const nextCart = cart.filter(item => item.code !== module.code); setCart(nextCart); if (nextCart.length === 0) { setAppliedCoupon(null); setCouponCode(''); setPricingCalc(null); } } 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); if (filteredCart.length === 0) { setAppliedCoupon(null); setCouponCode(''); setPricingCalc(null); } } } }, [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; } // Ensure the user has a valid billing contact phone number before opening Razorpay const hasValidPhone = loggedInUser?.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India'); if (!hasValidPhone) { setPendingCheckoutAfterPhone(true); setShowBillingPhoneModal(true); setCheckoutLoading(false); return; } let isPaymentCancelled = false; let isPaymentCompleted = false; // Sanitize contact for Razorpay: strictly E.164 (+) const parsedContact = parsePhoneNumber(loggedInUser?.phone_number, loggedInUser?.country || 'India'); const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits, loggedInUser?.country || 'India'); 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, prefill: { name: loggedInUser?.display_name || '', email: loggedInUser?.email || '', contact: sanitizedContact }, 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); setCouponCode(''); setPricingCalc(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 */} { setChangePasswordSuccess(false); setChangePasswordError(null); setShowProfileDrawer(true); }} onOpenAuth={(mode) => { setAuthMode(mode); setShowAuthModal(true); }} /> {/* ๐Ÿ“ฆ Main Body */}
{activeTab === 'storefront' ? (
{/* ๐Ÿ… Dynamic Gold Lifetime Banner */} {hasUserLifetimeAccess && }
{/* ๐Ÿ“ฆ Catalog Section */} {/* ๐Ÿ›’ Cart Drawer Summary */} setShowBillingPhoneModal(true)} verificationResult={verificationResult} checkoutLoading={checkoutLoading} handleCheckout={handleCheckout} />
) : activeTab === 'logged-out' ? ( { switchTab('storefront'); setAuthMode('login'); setShowAuthModal(true); }} /> ) : ( /* ๐Ÿงพ 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); setCart([]); setAppliedCoupon(null); setCouponCode(''); setPricingCalc(null); }} loggedInUser={loggedInUser} onDownloadInvoice={handleDownloadCheckoutInvoice} downloadingInvoice={downloadingModalInvoice} returnRoute={returnRoute} appScheme={appScheme} /> )} {/* ๐Ÿงญ Profile Drawer */} { handleCloseProfileDrawer(); switchTab('storefront'); }} onViewSubscriptions={() => { handleCloseProfileDrawer(); switchTab('subscriptions'); }} curriculumModules={curriculumModules} onDownloadInvoice={handleDownloadCheckoutInvoice} /> {/* ๐Ÿ” Password Updated Success Modal */} { setPasswordUpdatedPopup(false); setAuthMode('login'); setShowAuthModal(true); }} /> {/* ๐Ÿ“ž Billing Contact Phone Modal */} { setShowBillingPhoneModal(false); setPendingCheckoutAfterPhone(false); }} currentPhone={loggedInUser?.phone_number} currentCountry={loggedInUser?.country || profileCountry || 'India'} onSavePhone={handleSaveBillingPhone} />
); }