import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'; import { View, Text, StyleSheet, ScrollView, TouchableOpacity, RefreshControl, Image, Modal, TextInput, Alert, KeyboardAvoidingView, Platform, Animated, ActivityIndicator, Switch, } from 'react-native'; import { WebView } from 'react-native-webview'; import * as SecureStore from 'expo-secure-store'; import { useLocalSearchParams, router } from 'expo-router'; import { Ionicons } from '@expo/vector-icons'; import { SafeAreaView } from 'react-native-safe-area-context'; import * as ImagePicker from 'expo-image-picker'; import { usePaymentSheet } from '@stripe/stripe-react-native'; import { api } from '@/services/api'; import { useBeneficiary } from '@/contexts/BeneficiaryContext'; import { useAuth } from '@/contexts/AuthContext'; import { LoadingSpinner } from '@/components/ui/LoadingSpinner'; import { FullScreenError } from '@/components/ui/ErrorMessage'; import { Button } from '@/components/ui/Button'; import { SubscriptionPayment } from '@/components/SubscriptionPayment'; import { useToast } from '@/components/ui/Toast'; import MockDashboard from '@/components/MockDashboard'; import { AppColors, BorderRadius, FontSizes, Spacing, FontWeights, Shadows, AvatarSizes, } from '@/constants/theme'; import type { Beneficiary } from '@/types'; // Local beneficiaries have timestamp-based IDs (>1000000000) const isLocalBeneficiary = (id: string | number): boolean => { const numId = typeof id === 'string' ? parseInt(id, 10) : id; return numId > 1000000000; }; // Setup state types type SetupState = 'loading' | 'awaiting_equipment' | 'no_devices' | 'no_subscription' | 'ready'; // Stripe API const STRIPE_API_URL = 'https://wellnuo.smartlaunchhub.com/api/stripe'; // WebView Dashboard URL - uses test NDK account for demo data const DASHBOARD_URL = 'https://react.eluxnetworks.net/dashboard'; const TEST_NDK_DEPLOYMENT_ID = '1'; // anandk test deployment with real sensor data // Starter Kit info const STARTER_KIT = { name: 'WellNuo Starter Kit', price: '$249', priceValue: 249, features: [ 'Motion sensor (PIR)', 'Door/window sensor', 'Temperature & humidity sensor', 'WellNuo Hub', 'Mobile app access', '1 year subscription included', ], }; // No Devices Screen Component - Primary: Buy Kit with Stripe, Secondary: I have sensors function NoDevicesScreen({ beneficiary, beneficiaryId, onActivate, onPurchaseSuccess, userEmail, userId, }: { beneficiary: Beneficiary; beneficiaryId: string; onActivate: () => void; onPurchaseSuccess: () => void; userEmail?: string; userId?: string; }) { const [isProcessing, setIsProcessing] = useState(false); const { initPaymentSheet, presentPaymentSheet } = usePaymentSheet(); const toast = useToast(); const handlePurchase = async () => { setIsProcessing(true); try { // 1. Create Payment Sheet on server const response = await fetch(`${STRIPE_API_URL}/create-payment-sheet`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: userEmail || 'guest@wellnuo.com', amount: STARTER_KIT.priceValue * 100, // Convert to cents ($249.00) metadata: { userId: userId || 'guest', beneficiaryName: beneficiary.name, beneficiaryId: beneficiaryId, }, }), }); const data = await response.json(); if (!data.paymentIntent) { throw new Error(data.error || 'Failed to create payment sheet'); } // 2. Initialize the Payment Sheet const { error: initError } = await initPaymentSheet({ merchantDisplayName: 'WellNuo', paymentIntentClientSecret: data.paymentIntent, customerId: data.customer, customerEphemeralKeySecret: data.ephemeralKey, defaultBillingDetails: { email: userEmail || '', }, returnURL: 'wellnuo://stripe-redirect', applePay: { merchantCountryCode: 'US', }, googlePay: { merchantCountryCode: 'US', testEnv: true, }, }); if (initError) { throw new Error(initError.message); } // 3. Present the Payment Sheet const { error: presentError } = await presentPaymentSheet(); if (presentError) { if (presentError.code === 'Canceled') { // User cancelled - do nothing setIsProcessing(false); return; } throw new Error(presentError.message); } // 4. Payment successful! toast.success('Order Placed!', 'Your WellNuo Starter Kit is on its way.'); onPurchaseSuccess(); } catch (error) { console.error('Payment error:', error); toast.error( 'Payment Failed', error instanceof Error ? error.message : 'Something went wrong. Please try again.' ); } setIsProcessing(false); }; return ( Get Started with WellNuo To start monitoring {beneficiary.name}'s wellness, you need WellNuo sensors. {/* Primary: Buy Kit Card */} {STARTER_KIT.name} {STARTER_KIT.price} {STARTER_KIT.features.map((feature, index) => ( {feature} ))} {isProcessing ? ( ) : ( <> Buy Now - {STARTER_KIT.price} )} {/* Security Badge */} Secure payment by Stripe {/* Secondary: I already have sensors */} I already have sensors ); } // Equipment status configuration const equipmentStatusInfo = { ordered: { icon: 'cube-outline' as const, title: 'Kit Ordered', subtitle: 'Your WellNuo kit is being prepared for shipping', color: AppColors.info, bgColor: AppColors.infoLight, steps: [ { label: 'Order placed', done: true }, { label: 'Preparing', done: true }, { label: 'Shipped', done: false }, { label: 'Delivered', done: false }, ], }, shipped: { icon: 'car-outline' as const, title: 'In Transit', subtitle: 'Your WellNuo kit is on its way', color: AppColors.warning, bgColor: AppColors.warningLight, steps: [ { label: 'Order placed', done: true }, { label: 'Preparing', done: true }, { label: 'Shipped', done: true }, { label: 'Delivered', done: false }, ], }, delivered: { icon: 'checkmark-circle-outline' as const, title: 'Delivered', subtitle: 'Your kit has arrived! Time to set it up.', color: AppColors.success, bgColor: AppColors.successLight, steps: [ { label: 'Order placed', done: true }, { label: 'Preparing', done: true }, { label: 'Shipped', done: true }, { label: 'Delivered', done: true }, ], }, }; // Awaiting Equipment Screen Component function AwaitingEquipmentScreen({ beneficiary, onActivate, onMarkReceived, }: { beneficiary: Beneficiary; onActivate: () => void; onMarkReceived: () => void; }) { const status = beneficiary.equipmentStatus as 'ordered' | 'shipped' | 'delivered'; const info = equipmentStatusInfo[status] || equipmentStatusInfo.ordered; const isDelivered = status === 'delivered'; return ( {info.title} {info.subtitle} {/* Progress steps */} {info.steps.map((step, index) => ( {step.done && ( )} {step.label} {index < info.steps.length - 1 && ( )} ))} {/* Tracking number if available */} {beneficiary.trackingNumber && ( Tracking Number {beneficiary.trackingNumber} )} {/* Actions */} {isDelivered ? (