import React, { useCallback, useEffect, useMemo, useState } from "react"; import { ActivityIndicator, Alert, Linking, Platform, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { router, useFocusEffect, useLocalSearchParams } from "expo-router"; import { Ionicons } from "@expo/vector-icons"; import { moderateScale, verticalScale } from "react-native-size-matters"; import Constants from "expo-constants"; import { Colors } from "@/theme"; import { useAuthStore } from "@/store/auth.store"; import { calculateCart } from "@/features/commerce"; import type { CartCalculationResponse } from "@/features/commerce"; import PrimaryButton from "@/components/buttons/PrimaryButton"; function param(value: string | string[] | undefined): string { return typeof value === "string" ? value : ""; } function money(value: number, currency: string): string { try { return new Intl.NumberFormat("en-IN", { style: "currency", currency, maximumFractionDigits: 2, }).format(value); } catch { return `${currency} ${value.toFixed(2)}`; } } function resolveStorefrontUrl(): string { const envUrl = process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim(); if (envUrl) return envUrl; const apiUrl = process.env.EXPO_PUBLIC_API_URL ?? ""; if (apiUrl.startsWith("https://")) { try { const parsed = new URL(apiUrl); if (!parsed.hostname.includes("localhost") && !parsed.hostname.includes("127.0.0.1")) { return parsed.origin; } } catch {} } const hostUri = Constants.expoConfig?.hostUri; const metroHost = hostUri?.split(":")[0]; if (metroHost && /^[0-9.]+$/.test(metroHost) && metroHost !== "127.0.0.1") { return `http://${metroHost}:3000`; } if (Platform.OS === "web" && typeof window !== "undefined") { return `${window.location.protocol}//${window.location.hostname}`; } const ipMatch = apiUrl.match(/http:\/\/([0-9.]+)/); if (ipMatch?.[1]) return `http://${ipMatch[1]}:3000`; return "http://localhost:3000"; } export default function SubscriptionScreen() { const params = useLocalSearchParams(); const accessToken = useAuthStore((state) => state.accessToken); const access = useAuthStore((state) => state.access); const refreshAccess = useAuthStore((state) => state.refreshAccess); const moduleId = param(params.moduleId); const moduleCode = param(params.moduleCode); const title = param(params.title) || "Clinical Module"; const category = param(params.category); const description = param(params.desc); const planCode = param(params.planCode).trim().toUpperCase(); const [couponCode, setCouponCode] = useState(""); const [pricing, setPricing] = useState(null); const [loadingPricing, setLoadingPricing] = useState(false); const [openingCheckout, setOpeningCheckout] = useState(false); const [error, setError] = useState(null); const unlocked = useMemo(() => { if (!accessToken) return false; if (moduleCode && access?.unlocked_module_codes.includes(moduleCode)) return true; return false; }, [access, accessToken, moduleCode]); const loadPricing = useCallback(async (coupon?: string) => { if (!planCode) { setPricing(null); setError("This module does not have a commerce plan configured."); return; } setLoadingPricing(true); setError(null); try { const response = await calculateCart({ cart_item_codes: [planCode], coupon_code: coupon?.trim() || null, currency: "INR", }); setPricing(response); } catch (err: any) { const detail = err?.response?.data?.detail; setError(typeof detail === "string" ? detail : "Unable to load current subscription pricing."); setPricing(null); } finally { setLoadingPricing(false); } }, [planCode]); useEffect(() => { void loadPricing(); }, [loadPricing]); useFocusEffect( useCallback(() => { if (accessToken) { void refreshAccess().catch((error) => console.warn("Unable to refresh subscription access:", error)); } }, [accessToken, refreshAccess]), ); const showAlert = (alertTitle: string, message: string, onConfirm?: () => void) => { if (Platform.OS === "web") { alert(`${alertTitle}\n\n${message}`); onConfirm?.(); return; } Alert.alert( alertTitle, message, onConfirm ? [{ text: "Cancel", style: "cancel" }, { text: "Continue", onPress: onConfirm }] : [{ text: "OK" }], ); }; const handleCheckout = async () => { if (!accessToken) { router.push("/login"); return; } if (!planCode) { showAlert("Subscription unavailable", "No access plan is configured for this module."); return; } setOpeningCheckout(true); try { const storefrontUrl = resolveStorefrontUrl(); const query = new URLSearchParams(); query.set("token", accessToken); query.set("planCode", planCode); if (couponCode.trim()) query.set("couponCode", couponCode.trim().toUpperCase()); const apiUrl = process.env.EXPO_PUBLIC_API_URL; if (apiUrl) query.set("apiUrl", apiUrl); if (moduleId) query.set("moduleId", moduleId); if (moduleCode) query.set("moduleCode", moduleCode); const checkoutUrl = `${storefrontUrl}?${query.toString()}`; showAlert( "Complete payment", "Checkout will open in the secure web storefront. Return to AcuPedia after payment; access will refresh automatically.", () => { void Linking.openURL(checkoutUrl); }, ); } catch { showAlert("Unable to open checkout", "Please try again."); } finally { setOpeningCheckout(false); } }; return ( router.back()} style={styles.backButton}> Subscription {unlocked ? `${title} is unlocked` : `Unlock ${title}`} {unlocked ? "Your current entitlement already includes this module." : "Pricing and discounts below are calculated by the current commerce API."} {(category || description) ? ( {category ? {category} : null} {description ? {description} : null} {planCode ? Plan: {planCode} : null} ) : null} {!unlocked ? ( <> {loadingPricing ? ( Loading current pricing… ) : pricing ? ( <> {pricing.cart_items.map((item) => ( {item.name} {money(item.price, pricing.currency)} ))} Subtotal{money(pricing.base_subtotal, pricing.currency)} {pricing.total_discounts > 0 ? Discounts− {money(pricing.total_discounts, pricing.currency)} : null} {pricing.convenience_fee > 0 ? Convenience fee{money(pricing.convenience_fee, pricing.currency)} : null} GST{money(pricing.gst_amount, pricing.currency)} Total{money(pricing.grand_total, pricing.currency)} {pricing.coupon_applied ? Coupon applied: {pricing.coupon_applied} : null} ) : ( {error ?? "Pricing is unavailable."} )} void loadPricing(couponCode)} disabled={loadingPricing} > Apply {error && pricing ? {error} : null} {openingCheckout ? : ( void handleCheckout()} disabled={loadingPricing || !planCode} /> )} ) : ( router.replace("/modules")} /> )} ); } const styles = StyleSheet.create({ safeArea: { flex: 1, backgroundColor: "#FFFFFF" }, header: { minHeight: 64, flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingHorizontal: moderateScale(16), paddingTop: Platform.OS === "web" ? 14 : moderateScale(8), paddingBottom: moderateScale(8), borderBottomWidth: 1, borderBottomColor: "#ECECEC", backgroundColor: "#FFFFFF", }, backButton: { padding: 4 }, headerTitle: { fontSize: moderateScale(18), fontWeight: "700", color: Colors.textPrimary }, placeholder: { width: 32 }, content: { paddingHorizontal: moderateScale(24), paddingTop: verticalScale(28), paddingBottom: verticalScale(40) }, iconContainer: { alignItems: "center", marginBottom: verticalScale(16) }, title: { fontSize: moderateScale(24), fontWeight: "800", color: Colors.textPrimary, textAlign: "center" }, subtitle: { fontSize: moderateScale(14), color: Colors.textSecondary, textAlign: "center", lineHeight: 20, marginTop: verticalScale(8), marginBottom: verticalScale(22) }, infoBox: { flexDirection: "row", backgroundColor: "#EEF2FF", borderRadius: moderateScale(14), padding: moderateScale(14), marginBottom: verticalScale(18) }, infoText: { flex: 1, marginLeft: moderateScale(10) }, infoTitle: { fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary }, infoDescription: { marginTop: 3, fontSize: moderateScale(12), color: Colors.textSecondary, lineHeight: 18 }, planCode: { marginTop: 5, fontSize: moderateScale(11), color: Colors.primary, fontWeight: "600" }, pricingCard: { backgroundColor: "#FFFFFF", borderRadius: moderateScale(16), borderWidth: 1, borderColor: "#E5E7EB", padding: moderateScale(16) }, loadingRow: { flexDirection: "row", alignItems: "center", justifyContent: "center", paddingVertical: verticalScale(16) }, loadingText: { marginLeft: moderateScale(10), color: Colors.textSecondary, fontSize: moderateScale(13) }, priceRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginVertical: verticalScale(5) }, priceLabel: { flex: 1, fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary, marginRight: 10 }, priceValue: { fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary }, secondaryLabel: { fontSize: moderateScale(13), color: Colors.textSecondary }, secondaryValue: { fontSize: moderateScale(13), color: Colors.textPrimary }, discountLabel: { fontSize: moderateScale(13), color: "#15803D" }, discountValue: { fontSize: moderateScale(13), color: "#15803D", fontWeight: "600" }, totalLabel: { fontSize: moderateScale(15), fontWeight: "800", color: Colors.textPrimary }, totalValue: { fontSize: moderateScale(18), fontWeight: "800", color: Colors.primary }, divider: { height: 1, backgroundColor: "#ECECEC", marginVertical: verticalScale(8) }, appliedText: { marginTop: verticalScale(8), fontSize: moderateScale(12), color: "#15803D", fontWeight: "600" }, errorText: { fontSize: moderateScale(13), color: "#B91C1C", textAlign: "center", paddingVertical: verticalScale(14) }, couponRow: { flexDirection: "row", marginTop: verticalScale(14) }, couponInput: { flex: 1, minHeight: 46, backgroundColor: "#FFFFFF", borderWidth: 1, borderColor: "#D1D5DB", borderRadius: moderateScale(12), paddingHorizontal: moderateScale(12), color: Colors.textPrimary }, applyButton: { marginLeft: moderateScale(10), minWidth: 78, minHeight: 46, alignItems: "center", justifyContent: "center", backgroundColor: "#EEF2FF", borderRadius: moderateScale(12) }, applyText: { fontSize: moderateScale(13), fontWeight: "700", color: Colors.primary }, inlineError: { marginTop: verticalScale(8), fontSize: moderateScale(12), color: "#B91C1C" }, buttonContainer: { marginTop: verticalScale(24) }, });