acupedia-mobile-ui/src/app/subscription/index.tsx

300 lines
8.9 KiB
TypeScript

import React, { useCallback, useMemo, useState } from "react";
import {
Alert,
BackHandler,
Linking,
Platform,
ScrollView,
StyleSheet,
Text,
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 PrimaryButton from "@/components/buttons/PrimaryButton";
function param(value: string | string[] | undefined): string {
return typeof value === "string" ? value : "";
}
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";
}
const DEFAULT_RETURN_ROUTE = "/modules";
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 description = param(params.desc);
const planCode = param(params.planCode).trim().toUpperCase();
const returnRoute = param(params.returnRoute) || param(params.returnTo) || DEFAULT_RETURN_ROUTE;
const [openingCheckout, setOpeningCheckout] = useState(false);
const unlocked = useMemo(() => {
if (!accessToken) return false;
if (moduleCode && access?.unlocked_module_codes.includes(moduleCode)) return true;
return false;
}, [access, accessToken, moduleCode]);
useFocusEffect(
useCallback(() => {
if (accessToken) {
void refreshAccess().catch((error) => console.warn("Unable to refresh subscription access:", error));
}
}, [accessToken, refreshAccess]),
);
const handleBack = useCallback(() => {
if (unlocked) {
router.replace(returnRoute as never);
return true;
}
if (router.canGoBack()) {
router.back();
} else {
router.replace(returnRoute as never);
}
return true;
}, [unlocked, returnRoute]);
useFocusEffect(
useCallback(() => {
const onBackPress = () => handleBack();
const subscription = BackHandler.addEventListener(
"hardwareBackPress",
onBackPress
);
return () => subscription.remove();
}, [handleBack])
);
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);
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 returnRouteClean = returnRoute.replace(/^\/+/, "");
if (returnRouteClean) query.set("returnRoute", returnRouteClean);
const appScheme = Array.isArray(Constants.expoConfig?.scheme)
? Constants.expoConfig?.scheme[0]
: Constants.expoConfig?.scheme;
if (appScheme) query.set("scheme", appScheme);
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 (
<SafeAreaView style={styles.safeArea} edges={["top", "bottom", "left", "right"]}>
<View style={styles.header}>
<TouchableOpacity
onPress={handleBack}
style={styles.backButton}
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
accessibilityRole="button"
accessibilityLabel="Go back"
>
<Ionicons name="chevron-back" size={24} color={Colors.textPrimary} />
</TouchableOpacity>
<Text style={styles.headerTitle} numberOfLines={1}>
{title}
</Text>
<View style={styles.placeholder} />
</View>
<ScrollView
contentContainerStyle={styles.scrollContent}
showsVerticalScrollIndicator={false}
bounces={false}
>
<View style={styles.centerContainer}>
<View style={styles.iconCircle}>
<Ionicons
name={unlocked ? "checkmark-circle" : "lock-closed"}
size={moderateScale(32)}
color={Colors.primary}
/>
</View>
<Text style={styles.title}>
{unlocked ? `${title} is Unlocked` : `Unlock ${title}`}
</Text>
{description ? (
<Text style={styles.descriptionText}>{description}</Text>
) : null}
</View>
</ScrollView>
<View style={styles.footer}>
{!unlocked ? (
<PrimaryButton
title={accessToken ? "Continue to Checkout" : "Log In to Subscribe"}
onPress={() => void handleCheckout()}
disabled={!planCode}
loading={openingCheckout}
/>
) : (
<PrimaryButton
title="Back to Modules"
onPress={() => router.replace(returnRoute as never)}
/>
)}
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeArea: { flex: 1, backgroundColor: "#FFFFFF" },
header: {
height: moderateScale(56),
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: moderateScale(16),
borderBottomWidth: 1,
borderBottomColor: "#F1F5F9",
backgroundColor: "#FFFFFF",
},
backButton: {
width: moderateScale(36),
height: moderateScale(36),
alignItems: "center",
justifyContent: "center",
},
headerTitle: {
flex: 1,
fontSize: moderateScale(17),
fontWeight: "700",
color: Colors.textPrimary,
textAlign: "center",
marginHorizontal: moderateScale(8),
},
placeholder: { width: moderateScale(36) },
scrollContent: {
flexGrow: 1,
justifyContent: "center",
alignItems: "center",
paddingHorizontal: moderateScale(24),
paddingVertical: verticalScale(24),
},
centerContainer: {
alignItems: "center",
justifyContent: "center",
maxWidth: moderateScale(360),
width: "100%",
},
iconCircle: {
width: moderateScale(68),
height: moderateScale(68),
borderRadius: moderateScale(34),
backgroundColor: "#E8F5E9",
alignItems: "center",
justifyContent: "center",
marginBottom: verticalScale(20),
},
title: {
fontSize: moderateScale(22),
fontWeight: "800",
color: Colors.textPrimary,
textAlign: "center",
lineHeight: moderateScale(28),
},
descriptionText: {
fontSize: moderateScale(15),
color: Colors.textSecondary,
textAlign: "center",
lineHeight: moderateScale(23),
marginTop: verticalScale(12),
paddingHorizontal: moderateScale(8),
},
footer: {
paddingHorizontal: moderateScale(20),
paddingTop: verticalScale(12),
paddingBottom: Platform.OS === "ios" ? verticalScale(8) : verticalScale(16),
borderTopWidth: 1,
borderTopColor: "#F1F5F9",
backgroundColor: "#FFFFFF",
},
});