Refactor profile screen and organize project structure

- Extract ProfileScreen and components to features/profile
- Move shared hooks and stores to top-level
- Add RLS policies for admin permissions
- Add RELEASING.md guide
- Update .gitignore
This commit is contained in:
Jamie Brunton committed 2026-01-01 23:03:43 +00:00
1 parent df4c4d486b
commit 8f8c6e401d
79 files changed
+6689 -4944

No files matched your search

@@ -0,0 +1,533 @@
import React from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, useWindowDimensions, Platform, ActivityIndicator, Alert } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import Animated, { FadeInDown } from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient';
import { GradientBackground, GlassCard } from '../../components/ui';
import { FeedbackModal } from '../../components/feedback';
import { Paywall } from '../../components/paywall';
import { colors, featureColors, spacing, typography, radius, shadows } from '../../theme';
import { useAuthStore, useSubscriptionStore } from '../../store';
import { resetSwipeTutorial } from '../../lib/swipeTutorialSeen';
import { resetMatchesTutorial } from '../../lib/matchesTutorialSeen';
import { supabase } from '../../lib/supabase'; // Needed for debug reset
// Hooks
import { useProfileSettings, useCoupleManagement } from './hooks';
// Components
import { ProfileHeader, CoupleStatus, PrivacySettings, DangerZone, SettingsSection, MenuItem } from './components';
const MAX_CONTENT_WIDTH = 500;
const ACCENT_GRADIENT = featureColors.profile.gradient as [string, string];
export function ProfileScreen() {
const { width } = useWindowDimensions();
const isWideScreen = width > MAX_CONTENT_WIDTH;
const { user, partner, couple, fetchUser } = useAuthStore();
const { subscription } = useSubscriptionStore();
// Hooks
const settings = useProfileSettings();
const {
handleUnpair,
handleDeleteRelationship,
handleResetProgress,
isResettingProgress,
handleSignOut,
navigateToPairing
} = useCoupleManagement();
const [showFeedbackModal, setShowFeedbackModal] = React.useState(false);
// Derived formatting
const isOwnSubscription = user?.is_premium && subscription.isProUser;
const hasPremiumAccess = user?.is_premium || partner?.is_premium || subscription.isProUser;
const formatExpirationDate = (date: Date | null | string) => {
if (!date) return "Never";
const d = new Date(date);
return d.toLocaleDateString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
});
};
return (
<GradientBackground>
<ScrollView
style={styles.container}
contentContainerStyle={[
styles.contentContainer,
isWideScreen && styles.contentContainerWide,
]}
showsVerticalScrollIndicator={false}
>
{/* Header title */}
<Animated.View
entering={FadeInDown.delay(100).duration(500)}
style={styles.header}
>
<Text style={styles.headerLabel}>YOUR SAUCI</Text>
<Text style={styles.title}>Settings</Text>
<View style={styles.separator}>
<View style={styles.separatorLine} />
<View style={styles.separatorDiamond} />
<View style={styles.separatorLine} />
</View>
</Animated.View>
{/* Profile Header */}
<ProfileHeader
user={user}
isUploadingAvatar={settings.isUploadingAvatar}
isEditingName={settings.isEditingName}
newName={settings.newName}
isUpdatingName={settings.isUpdatingName}
onAvatarPress={settings.handleAvatarPress}
onNewNameChange={settings.setNewName}
onUpdateName={settings.handleUpdateName}
onCancelEditName={settings.handleCancelEditName}
onStartEditingName={() => settings.setIsEditingName(true)}
/>
{/* Partner */}
<CoupleStatus
partner={partner}
couple={couple}
onUnpair={handleUnpair}
onPairingPress={navigateToPairing}
/>
{/* Subscription Section */}
<SettingsSection title="Subscription" delay={350}>
{hasPremiumAccess ? (
<View style={styles.rowContainer}>
<View style={styles.rowLeft}>
<LinearGradient
colors={ACCENT_GRADIENT}
style={styles.partnerIconGradient}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
>
<Ionicons name="star" size={20} color={colors.text} />
</LinearGradient>
<View style={styles.rowTextContainer}>
<Text style={styles.rowValue}>Pro Member</Text>
<Text style={styles.rowLabel}>
{isOwnSubscription
? `Renews ${formatExpirationDate(subscription.expirationDate)}`
: "Via partner's subscription"
}
</Text>
</View>
</View>
{isOwnSubscription && (
<TouchableOpacity
style={styles.manageButton}
onPress={settings.handleManageSubscription}
activeOpacity={0.7}
>
<Text style={styles.manageButtonText}>Manage</Text>
</TouchableOpacity>
)}
</View>
) : (
<TouchableOpacity
style={styles.rowContainer}
onPress={() => settings.setShowPaywall(true)}
activeOpacity={0.7}
>
<View style={styles.rowLeft}>
<View style={styles.emptyPartnerIcon}>
<Ionicons name="star-outline" size={20} color={colors.textTertiary} />
</View>
<View style={styles.rowTextContainer}>
<Text style={styles.rowValueMuted}>Free Plan</Text>
<Text style={styles.rowLabel}>Upgrade to unlock all packs</Text>
</View>
</View>
<LinearGradient
colors={ACCENT_GRADIENT}
style={styles.upgradeButton}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
>
<Text style={styles.upgradeButtonText}>Upgrade</Text>
</LinearGradient>
</TouchableOpacity>
)}
{/* Restore Purchases Link */}
{!hasPremiumAccess && (
<TouchableOpacity
style={styles.restoreLink}
onPress={settings.handleRestorePurchases}
disabled={settings.isPurchasing}
>
<Text style={styles.restoreLinkText}>
{settings.isPurchasing ? "Restoring..." : "Restore Purchases"}
</Text>
</TouchableOpacity>
)}
</SettingsSection>
{/* Preferences */}
<PrivacySettings
showExplicit={settings.showExplicit}
isUpdatingExplicit={settings.isUpdatingExplicit}
onExplicitToggle={settings.handleExplicitToggle}
biometricAvailable={settings.biometricAvailable}
biometricEnabled={settings.biometricEnabled}
biometricType={settings.biometricType}
isUpdatingBiometric={settings.isUpdatingBiometric}
onBiometricToggle={settings.handleBiometricToggle}
/>
{/* Account */}
<SettingsSection title="Account" delay={425}>
<MenuItem
icon="log-out-outline"
label="Sign Out"
onPress={handleSignOut}
variant="danger"
showChevron={true}
/>
</SettingsSection>
{/* Support */}
<SettingsSection title="Support" delay={475}>
<MenuItem
icon="chatbubble-ellipses-outline"
label="Send Feedback"
description="Report bugs or request features"
onPress={() => setShowFeedbackModal(true)}
/>
</SettingsSection>
{/* Reset Progress Layout */}
{couple && (
<SettingsSection title="Reset Progress" delay={500}>
<View style={styles.resetContent}>
<View style={styles.resetInfo}>
<View style={styles.resetIconContainer}>
<Ionicons name="refresh" size={20} color={colors.warning} />
</View>
<View style={styles.resetTextContainer}>
<Text style={styles.resetTitle}>Start Fresh</Text>
<Text style={styles.resetDescription}>
Delete all swipes, matches, and chats while keeping your partner connection.
</Text>
</View>
</View>
<TouchableOpacity
style={[styles.resetButton, isResettingProgress && styles.resetButtonDisabled]}
onPress={handleResetProgress}
disabled={isResettingProgress}
activeOpacity={0.7}
>
{isResettingProgress ? (
<ActivityIndicator size="small" color={colors.warning} />
) : (
<>
<Ionicons name="refresh-outline" size={16} color={colors.warning} />
<Text style={styles.resetButtonText}>Reset</Text>
</>
)}
</TouchableOpacity>
</View>
</SettingsSection>
)}
{/* Debug Section */}
{__DEV__ && (
<SettingsSection title="Debug" delay={550}>
<MenuItem
icon="refresh"
label="Reset Swipe Tutorial"
description="Show the tutorial again"
onPress={async () => {
await resetSwipeTutorial();
Alert.alert("Success", "Swipe tutorial has been reset.");
}}
variant="danger"
// Using danger just for yellow/warning color simulation via props? No, MenuItem uses error color for danger.
// I'll stick to default and standard styling or custom if needed.
// The original used warning color (yellow).
// I will use default for now.
/>
<View style={styles.preferencesDivider} />
<MenuItem
icon="heart"
label="Reset Matches Tutorial"
description="Show the tutorial again"
onPress={async () => {
await resetMatchesTutorial();
Alert.alert("Success", "Matches tutorial has been reset.");
}}
/>
<View style={styles.preferencesDivider} />
<MenuItem
icon="school-outline"
label="Reset Onboarding"
description="Show onboarding flow again"
onPress={async () => {
if (!user?.id) return;
try {
const { error } = await supabase
.from('profiles')
.update({ onboarding_completed: false })
.eq('id', user.id);
if (error) throw error;
await fetchUser();
Alert.alert("Success", "Onboarding has been reset.");
} catch (error) {
Alert.alert("Error", "Failed to reset onboarding.");
}
}}
/>
</SettingsSection>
)}
{/* Danger Zone */}
{couple && (
<DangerZone onDeleteRelationship={handleDeleteRelationship} />
)}
{/* Version */}
<Animated.View
entering={FadeInDown.delay(couple ? 650 : 525).duration(500)}
style={styles.versionContainer}
>
<View style={styles.versionBadge}>
<Ionicons name="heart" size={12} color={featureColors.profile.accent} />
<Text style={styles.version}>Sauci v1.0.0</Text>
</View>
</Animated.View>
<View style={styles.bottomSpacer} />
</ScrollView>
{/* Modals */}
<FeedbackModal
visible={showFeedbackModal}
onClose={() => setShowFeedbackModal(false)}
/>
<Paywall
visible={settings.showPaywall}
onClose={() => settings.setShowPaywall(false)}
/>
</GradientBackground>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
contentContainer: {
paddingBottom: Platform.OS === 'ios' ? 100 : 80,
},
contentContainerWide: {
alignSelf: 'center',
width: '100%',
maxWidth: MAX_CONTENT_WIDTH,
},
header: {
paddingTop: 60,
paddingHorizontal: spacing.lg,
paddingBottom: spacing.md,
alignItems: 'center',
},
headerLabel: {
...typography.caption2,
fontWeight: '600',
letterSpacing: 3,
color: colors.secondary,
marginBottom: spacing.xs,
},
title: {
...typography.largeTitle,
color: colors.text,
textAlign: 'center',
},
separator: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
marginVertical: spacing.md,
width: 100,
},
separatorLine: {
flex: 1,
height: 1,
backgroundColor: 'rgba(155, 89, 182, 0.3)',
},
separatorDiamond: {
width: 6,
height: 6,
backgroundColor: colors.secondary,
transform: [{ rotate: '45deg' }],
marginHorizontal: spacing.sm,
opacity: 0.6,
},
// Shared row styles
rowContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: spacing.sm,
},
rowLeft: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
partnerIconGradient: {
width: 44,
height: 44,
borderRadius: 22,
justifyContent: 'center',
alignItems: 'center',
},
emptyPartnerIcon: {
width: 44,
height: 44,
borderRadius: 22,
backgroundColor: colors.glass.background,
justifyContent: 'center',
alignItems: 'center',
},
rowTextContainer: {
marginLeft: spacing.md,
flex: 1,
},
rowValue: {
...typography.body,
fontWeight: '600',
color: colors.text,
},
rowValueMuted: {
...typography.body,
fontWeight: '600',
color: colors.textSecondary,
},
rowLabel: {
...typography.caption1,
color: colors.textTertiary,
marginTop: 2,
},
preferencesDivider: {
height: 1,
backgroundColor: colors.glass.border,
marginVertical: spacing.md,
},
// Subscription styles
manageButton: {
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm,
borderRadius: radius.md,
backgroundColor: colors.glass.background,
borderWidth: 1,
borderColor: colors.glass.border,
},
manageButtonText: {
...typography.subhead,
color: colors.secondary,
fontWeight: "600",
},
upgradeButton: {
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm,
borderRadius: radius.md,
},
upgradeButtonText: {
...typography.subhead,
color: colors.text,
fontWeight: "600",
},
restoreLink: {
alignItems: "center",
marginTop: spacing.sm,
padding: spacing.sm,
},
restoreLinkText: {
...typography.caption1,
color: colors.textTertiary,
},
// Reset Progress Styles
resetContent: {
gap: spacing.md,
},
resetInfo: {
flexDirection: "row",
alignItems: "flex-start",
},
resetIconContainer: {
width: 44,
height: 44,
borderRadius: 22,
backgroundColor: colors.warningLight,
justifyContent: "center",
alignItems: "center",
},
resetTextContainer: {
flex: 1,
marginLeft: spacing.md,
},
resetTitle: {
...typography.headline,
color: colors.text,
marginBottom: spacing.xs,
},
resetDescription: {
...typography.subhead,
color: colors.textSecondary,
lineHeight: 20,
},
resetButton: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
backgroundColor: colors.warningLight,
paddingVertical: spacing.sm,
paddingHorizontal: spacing.md,
borderRadius: radius.md,
borderWidth: 1,
borderColor: 'rgba(243, 156, 18, 0.3)',
gap: spacing.xs,
alignSelf: "flex-end",
},
resetButtonDisabled: {
opacity: 0.5,
},
resetButtonText: {
...typography.subhead,
color: colors.warning,
fontWeight: "600",
},
// Version Badge
versionContainer: {
alignItems: "center",
marginTop: spacing.lg,
},
versionBadge: {
flexDirection: "row",
alignItems: "center",
backgroundColor: colors.glass.background,
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm,
borderRadius: radius.full,
gap: spacing.xs,
},
version: {
...typography.caption1,
color: colors.textTertiary,
},
bottomSpacer: {
height: spacing.lg,
},
});
@@ -0,0 +1,161 @@
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { SettingsSection } from './SettingsSection';
import { colors, featureColors, spacing, typography } from '../../../theme';
import { Profile, Couple } from '../../../types';
const ACCENT_GRADIENT = featureColors.profile.gradient as [string, string];
interface CoupleStatusProps {
partner: Profile | null;
couple: Couple | null;
onUnpair: () => void;
onPairingPress: () => void;
}
export const CoupleStatus: React.FC<CoupleStatusProps> = ({
partner,
couple,
onUnpair,
onPairingPress,
}) => {
return (
<SettingsSection title="Partner" delay={300}>
{partner ? (
<View style={styles.rowContainer}>
<View style={styles.rowLeft}>
<LinearGradient
colors={ACCENT_GRADIENT}
style={styles.partnerIconGradient}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
>
<Ionicons name="heart" size={20} color={colors.text} />
</LinearGradient>
<View style={styles.rowTextContainer}>
<Text style={styles.rowValue}>
{partner.name || partner.email || 'Your partner'}
</Text>
<Text style={styles.rowLabel}>Connected</Text>
</View>
</View>
<TouchableOpacity
onPress={onUnpair}
style={styles.unlinkButton}
activeOpacity={0.7}
>
<Ionicons name="unlink-outline" size={18} color={colors.textTertiary} />
</TouchableOpacity>
</View>
) : couple ? (
<TouchableOpacity
style={styles.rowContainer}
onPress={onPairingPress}
activeOpacity={0.7}
>
<View style={styles.rowLeft}>
<LinearGradient
colors={ACCENT_GRADIENT}
style={styles.partnerIconGradient}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
>
<Ionicons name="hourglass-outline" size={20} color={colors.text} />
</LinearGradient>
<View style={styles.rowTextContainer}>
<Text style={styles.rowValue}>Waiting for partner</Text>
<Text style={styles.rowLabel}>Tap to view invite code</Text>
</View>
</View>
<View style={styles.chevronContainer}>
<Ionicons name="chevron-forward" size={18} color={colors.textTertiary} />
</View>
</TouchableOpacity>
) : (
<TouchableOpacity
style={styles.rowContainer}
onPress={onPairingPress}
activeOpacity={0.7}
>
<View style={styles.rowLeft}>
<View style={styles.emptyPartnerIcon}>
<Ionicons name="heart-outline" size={20} color={colors.textTertiary} />
</View>
<View style={styles.rowTextContainer}>
<Text style={styles.rowValueMuted}>Not paired yet</Text>
<Text style={styles.rowLabel}>Tap to connect</Text>
</View>
</View>
<View style={styles.chevronContainer}>
<Ionicons name="chevron-forward" size={18} color={colors.textTertiary} />
</View>
</TouchableOpacity>
)}
</SettingsSection>
);
};
const styles = StyleSheet.create({
rowContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
rowLeft: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
partnerIconGradient: {
width: 44,
height: 44,
borderRadius: 22,
justifyContent: 'center',
alignItems: 'center',
},
emptyPartnerIcon: {
width: 44,
height: 44,
borderRadius: 22,
backgroundColor: colors.glass.background,
justifyContent: 'center',
alignItems: 'center',
},
rowTextContainer: {
marginLeft: spacing.md,
flex: 1,
},
rowValue: {
...typography.body,
fontWeight: '600',
color: colors.text,
},
rowValueMuted: {
...typography.body,
fontWeight: '600',
color: colors.textSecondary,
},
rowLabel: {
...typography.caption1,
color: colors.textTertiary,
marginTop: 2,
},
unlinkButton: {
width: 36,
height: 36,
borderRadius: 18,
backgroundColor: colors.glass.background,
justifyContent: 'center',
alignItems: 'center',
},
chevronContainer: {
width: 28,
height: 28,
borderRadius: 14,
backgroundColor: colors.glass.background,
justifyContent: 'center',
alignItems: 'center',
},
});
@@ -0,0 +1,336 @@
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Modal, TextInput, ActivityIndicator } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import Animated, { FadeInDown } from 'react-native-reanimated';
import { GlassCard } from '../../../components/ui';
import { colors, spacing, radius, typography } from '../../../theme';
interface DangerZoneProps {
onDeleteRelationship: () => Promise<void>;
}
export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship }) => {
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deleteConfirmText, setDeleteConfirmText] = useState("");
const [isDeleting, setIsDeleting] = useState(false);
const handleDelete = async () => {
if (deleteConfirmText !== "DELETE") return;
setIsDeleting(true);
try {
await onDeleteRelationship();
setShowDeleteModal(false);
setDeleteConfirmText("");
} catch (error) {
// Error handling relies on parent throwing or managing its own alerts
// If parent throws, we stay on modal or close it?
// Usually parent alerts.
} finally {
setIsDeleting(false);
}
};
return (
<>
<Animated.View
entering={FadeInDown.delay(600).duration(500)}
style={styles.section}
>
<Text style={styles.dangerSectionTitle}>Danger Zone</Text>
<GlassCard style={styles.dangerCard}>
<View style={styles.dangerContent}>
<View style={styles.dangerInfo}>
<View style={styles.dangerIconContainer}>
<Ionicons name="warning" size={20} color={colors.error} />
</View>
<View style={styles.dangerTextContainer}>
<Text style={styles.dangerTitle}>Delete All Data</Text>
<Text style={styles.dangerDescription}>
Permanently delete your relationship including all matches, chats, and shared photos.
</Text>
</View>
</View>
<TouchableOpacity
style={styles.dangerButton}
onPress={() => setShowDeleteModal(true)}
activeOpacity={0.7}
>
<Ionicons name="trash-outline" size={16} color={colors.error} />
<Text style={styles.dangerButtonText}>Delete</Text>
</TouchableOpacity>
</View>
</GlassCard>
</Animated.View>
<Modal
visible={showDeleteModal}
transparent
animationType="fade"
onRequestClose={() => !isDeleting && setShowDeleteModal(false)}
>
<View style={styles.modalOverlay}>
<View style={styles.modalContent}>
<View style={styles.modalHeader}>
<View style={styles.modalIconContainer}>
<Ionicons name="warning" size={32} color={colors.error} />
</View>
<Text style={styles.modalTitle}>Delete All Data?</Text>
</View>
<Text style={styles.modalDescription}>
This action cannot be undone. This will permanently delete:
</Text>
<View style={styles.deleteList}>
<View style={styles.deleteListItem}>
<Ionicons name="heart-dislike" size={16} color={colors.error} />
<Text style={styles.deleteListText}>Your couple connection</Text>
</View>
<View style={styles.deleteListItem}>
<Ionicons name="checkmark-circle" size={16} color={colors.error} />
<Text style={styles.deleteListText}>All matches and responses</Text>
</View>
<View style={styles.deleteListItem}>
<Ionicons name="chatbubbles" size={16} color={colors.error} />
<Text style={styles.deleteListText}>All chat messages</Text>
</View>
<View style={styles.deleteListItem}>
<Ionicons name="images" size={16} color={colors.error} />
<Text style={styles.deleteListText}>All shared photos</Text>
</View>
</View>
<Text style={styles.confirmLabel}>
Type <Text style={styles.confirmKeyword}>DELETE</Text> to confirm:
</Text>
<TextInput
style={styles.confirmInput}
value={deleteConfirmText}
onChangeText={setDeleteConfirmText}
placeholder="Type DELETE"
placeholderTextColor={colors.textTertiary}
autoCapitalize="characters"
autoCorrect={false}
editable={!isDeleting}
/>
<View style={styles.modalButtons}>
<TouchableOpacity
style={styles.cancelButton}
onPress={() => {
setShowDeleteModal(false);
setDeleteConfirmText("");
}}
disabled={isDeleting}
activeOpacity={0.7}
>
<Text style={styles.cancelButtonText}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.confirmDeleteButton,
deleteConfirmText !== "DELETE" && styles.confirmDeleteButtonDisabled,
]}
onPress={handleDelete}
disabled={deleteConfirmText !== "DELETE" || isDeleting}
activeOpacity={0.7}
>
{isDeleting ? (
<ActivityIndicator size="small" color={colors.text} />
) : (
<>
<Ionicons name="trash" size={16} color={colors.text} />
<Text style={styles.confirmDeleteButtonText}>Delete</Text>
</>
)}
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
</>
);
};
const styles = StyleSheet.create({
section: {
paddingHorizontal: spacing.lg,
marginBottom: spacing.lg,
},
dangerSectionTitle: {
...typography.caption1,
color: colors.error,
textTransform: "uppercase",
letterSpacing: 1.5,
marginBottom: spacing.sm,
marginLeft: spacing.xs,
},
dangerCard: {
borderColor: 'rgba(231, 76, 60, 0.3)',
borderWidth: 1,
},
dangerContent: {
gap: spacing.md,
},
dangerInfo: {
flexDirection: "row",
alignItems: "flex-start",
},
dangerIconContainer: {
width: 44,
height: 44,
borderRadius: 22,
backgroundColor: colors.errorLight,
justifyContent: "center",
alignItems: "center",
},
dangerTextContainer: {
flex: 1,
marginLeft: spacing.md,
},
dangerTitle: {
...typography.headline,
color: colors.text,
marginBottom: spacing.xs,
},
dangerDescription: {
...typography.subhead,
color: colors.textSecondary,
lineHeight: 20,
},
dangerButton: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
backgroundColor: colors.errorLight,
paddingVertical: spacing.sm,
paddingHorizontal: spacing.md,
borderRadius: radius.md,
borderWidth: 1,
borderColor: 'rgba(231, 76, 60, 0.3)',
gap: spacing.xs,
alignSelf: "flex-end",
},
dangerButtonText: {
...typography.subhead,
color: colors.error,
fontWeight: "600",
},
// Modal styles
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.8)",
justifyContent: "center",
alignItems: "center",
padding: spacing.lg,
},
modalContent: {
backgroundColor: colors.backgroundLight,
borderRadius: radius.xl,
padding: spacing.xl,
width: "100%",
maxWidth: 400,
borderWidth: 1,
borderColor: colors.glass.border,
},
modalHeader: {
alignItems: "center",
marginBottom: spacing.lg,
},
modalIconContainer: {
width: 64,
height: 64,
borderRadius: 32,
backgroundColor: colors.errorLight,
justifyContent: "center",
alignItems: "center",
marginBottom: spacing.md,
},
modalTitle: {
...typography.title2,
color: colors.text,
textAlign: "center",
},
modalDescription: {
...typography.body,
color: colors.textSecondary,
marginBottom: spacing.lg,
textAlign: "center",
},
deleteList: {
backgroundColor: colors.glass.background,
borderRadius: radius.lg,
padding: spacing.md,
gap: spacing.sm,
marginBottom: spacing.xl,
},
deleteListItem: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
},
deleteListText: {
...typography.subhead,
color: colors.text,
},
confirmLabel: {
...typography.subhead,
color: colors.textSecondary,
marginBottom: spacing.xs,
textAlign: "center",
},
confirmKeyword: {
fontWeight: "bold",
color: colors.error,
},
confirmInput: {
backgroundColor: colors.background,
borderRadius: radius.md,
padding: spacing.md,
color: colors.text,
fontSize: 16,
borderWidth: 1,
borderColor: colors.error,
marginBottom: spacing.xl,
textAlign: "center",
},
modalButtons: {
flexDirection: "row",
gap: spacing.md,
},
cancelButton: {
flex: 1,
paddingVertical: spacing.md,
borderRadius: radius.md,
backgroundColor: colors.glass.background,
alignItems: "center",
borderWidth: 1,
borderColor: colors.glass.border,
},
cancelButtonText: {
...typography.body,
color: colors.text,
fontWeight: "600",
},
confirmDeleteButton: {
flex: 1,
flexDirection: "row",
paddingVertical: spacing.md,
borderRadius: radius.md,
backgroundColor: colors.error,
alignItems: "center",
justifyContent: "center",
gap: spacing.xs,
},
confirmDeleteButtonDisabled: {
opacity: 0.5,
backgroundColor: colors.errorLight,
},
confirmDeleteButtonText: {
...typography.body,
color: colors.text,
fontWeight: "600",
},
});
@@ -0,0 +1,130 @@
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radius, typography, featureColors } from '../../../theme';
export interface MenuItemProps {
/** Icon name (Ionicons) */
icon: string;
/** Main label text */
label: string;
/** Description text below label */
description?: string;
/** Action when pressed */
onPress: () => void;
/** Optional element to show on the right */
rightElement?: React.ReactNode;
/** Whether to show chevron arrow */
showChevron?: boolean;
/** Visual variant */
variant?: 'default' | 'danger';
/** Disable the item */
disabled?: boolean;
}
const ACCENT_GRADIENT = featureColors.profile.gradient as [string, string];
/**
* Reusable menu item row for settings screens.
*/
export function MenuItem({
icon,
label,
description,
onPress,
rightElement,
showChevron = true,
variant = 'default',
disabled = false,
}: MenuItemProps) {
const isDanger = variant === 'danger';
const iconColor = isDanger ? colors.error : colors.text;
const labelColor = isDanger ? colors.error : colors.text;
return (
<TouchableOpacity
style={styles.container}
onPress={onPress}
activeOpacity={0.7}
disabled={disabled}
>
<View style={styles.left}>
{isDanger ? (
<View style={styles.dangerIconContainer}>
<Ionicons name={icon as any} size={20} color={iconColor} />
</View>
) : (
<LinearGradient
colors={ACCENT_GRADIENT}
style={styles.iconContainer}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
>
<Ionicons name={icon as any} size={20} color={iconColor} />
</LinearGradient>
)}
<View style={styles.textContainer}>
<Text style={[styles.label, { color: labelColor }]}>{label}</Text>
{description && (
<Text style={styles.description}>{description}</Text>
)}
</View>
</View>
{rightElement || (showChevron && (
<View style={styles.chevron}>
<Ionicons name="chevron-forward" size={18} color={colors.textTertiary} />
</View>
))}
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: spacing.xs,
},
left: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
marginRight: spacing.md,
},
iconContainer: {
width: 40,
height: 40,
borderRadius: radius.lg,
justifyContent: 'center',
alignItems: 'center',
marginRight: spacing.md,
},
dangerIconContainer: {
width: 40,
height: 40,
borderRadius: radius.lg,
justifyContent: 'center',
alignItems: 'center',
marginRight: spacing.md,
backgroundColor: 'rgba(239, 68, 68, 0.1)',
},
textContainer: {
flex: 1,
},
label: {
...typography.body,
fontWeight: '500',
},
description: {
...typography.caption1,
color: colors.textSecondary,
marginTop: 2,
},
chevron: {
padding: spacing.xs,
},
});
export default MenuItem;
@@ -0,0 +1,61 @@
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { SettingsSection } from './SettingsSection';
import { SwitchItem } from './SwitchItem';
import { colors, spacing } from '../../../theme';
interface PrivacySettingsProps {
showExplicit: boolean;
isUpdatingExplicit: boolean;
onExplicitToggle: (value: boolean) => void;
biometricAvailable: boolean;
biometricEnabled: boolean;
biometricType: string;
isUpdatingBiometric: boolean;
onBiometricToggle: (value: boolean) => void;
}
export const PrivacySettings: React.FC<PrivacySettingsProps> = ({
showExplicit,
isUpdatingExplicit,
onExplicitToggle,
biometricAvailable,
biometricEnabled,
biometricType,
isUpdatingBiometric,
onBiometricToggle,
}) => {
return (
<SettingsSection title="Preferences" delay={375}>
<SwitchItem
icon="flame"
label="Spicy Content"
description="Show spicy question packs"
value={showExplicit}
onValueChange={onExplicitToggle}
disabled={isUpdatingExplicit}
/>
{biometricAvailable && (
<>
<View style={styles.divider} />
<SwitchItem
icon={biometricType === "Face ID" || biometricType === "Face Recognition" ? "scan-outline" : "finger-print-outline"}
label={biometricType}
description="Require unlock when opening app"
value={biometricEnabled}
onValueChange={onBiometricToggle}
disabled={isUpdatingBiometric}
/>
</>
)}
</SettingsSection>
);
};
const styles = StyleSheet.create({
divider: {
height: 1,
backgroundColor: colors.glass.border,
marginVertical: spacing.md,
},
});
@@ -0,0 +1,263 @@
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, ActivityIndicator } from 'react-native';
import { Image } from 'expo-image';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import Animated, { FadeInDown } from 'react-native-reanimated';
import { GlassCard } from '../../../components/ui';
import { colors, featureColors, spacing, typography } from '../../../theme';
import { Profile } from '../../../types';
const ACCENT_GRADIENT = featureColors.profile.gradient as [string, string];
interface ProfileHeaderProps {
user: Profile | null;
isUploadingAvatar: boolean;
isEditingName: boolean;
newName: string;
isUpdatingName: boolean;
onAvatarPress: () => void;
onNewNameChange: (text: string) => void;
onUpdateName: () => void;
onCancelEditName: () => void;
onStartEditingName: () => void;
}
export const ProfileHeader: React.FC<ProfileHeaderProps> = ({
user,
isUploadingAvatar,
isEditingName,
newName,
isUpdatingName,
onAvatarPress,
onNewNameChange,
onUpdateName,
onCancelEditName,
onStartEditingName,
}) => {
return (
<Animated.View
entering={FadeInDown.delay(200).duration(500)}
style={styles.profileSection}
>
<GlassCard variant="elevated">
<View style={styles.profileContent}>
<TouchableOpacity
onPress={onAvatarPress}
disabled={isUploadingAvatar}
activeOpacity={0.7}
style={styles.avatarTouchable}
>
<LinearGradient
colors={ACCENT_GRADIENT}
style={styles.avatarGradient}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
>
{user?.avatar_url ? (
<Image
source={{ uri: user.avatar_url }}
style={styles.avatarImage}
cachePolicy="disk"
transition={200}
/>
) : (
<View style={styles.avatarInner}>
<Text style={styles.avatarText}>
{user?.name?.[0]?.toUpperCase() || "U"}
</Text>
</View>
)}
</LinearGradient>
{isUploadingAvatar ? (
<View style={styles.avatarOverlay}>
<ActivityIndicator size="large" color={colors.text} />
</View>
) : (
<View style={styles.avatarEditBadge}>
<Ionicons name="camera" size={14} color={colors.text} />
</View>
)}
</TouchableOpacity>
<View style={styles.profileInfo}>
{isEditingName ? (
<View style={styles.editNameContainer}>
<TextInput
style={styles.nameInput}
value={newName}
onChangeText={onNewNameChange}
placeholder="Enter your name"
placeholderTextColor={colors.textTertiary}
autoFocus
editable={!isUpdatingName}
onSubmitEditing={onUpdateName}
returnKeyType="done"
/>
<View style={styles.editNameButtons}>
<TouchableOpacity
style={styles.cancelEditButton}
onPress={onCancelEditName}
disabled={isUpdatingName}
activeOpacity={0.7}
>
<Ionicons name="close" size={20} color={colors.textSecondary} />
</TouchableOpacity>
<TouchableOpacity
style={styles.saveEditButton}
onPress={onUpdateName}
disabled={isUpdatingName}
activeOpacity={0.7}
>
{isUpdatingName ? (
<ActivityIndicator size="small" color={colors.text} />
) : (
<Ionicons name="checkmark" size={20} color={colors.text} />
)}
</TouchableOpacity>
</View>
</View>
) : (
<TouchableOpacity
style={styles.nameContainer}
onPress={onStartEditingName}
activeOpacity={0.7}
>
<Text style={styles.name}>{user?.name || "User"}</Text>
<View style={styles.editNameIcon}>
<Ionicons name="pencil" size={14} color={colors.textTertiary} />
</View>
</TouchableOpacity>
)}
<Text style={styles.email}>{user?.email}</Text>
</View>
</View>
</GlassCard>
</Animated.View>
);
};
const styles = StyleSheet.create({
profileSection: {
marginBottom: spacing.xl,
},
profileContent: {
flexDirection: 'row',
alignItems: 'center',
},
avatarTouchable: {
marginRight: spacing.md,
},
avatarGradient: {
width: 80,
height: 80,
borderRadius: 40,
padding: 3,
justifyContent: 'center',
alignItems: 'center',
shadowColor: featureColors.profile.accent,
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 6,
},
avatarImage: {
width: '100%',
height: '100%',
borderRadius: 40,
backgroundColor: colors.background,
},
avatarInner: {
width: '100%',
height: '100%',
borderRadius: 40,
backgroundColor: colors.background,
justifyContent: 'center',
alignItems: 'center',
},
avatarText: {
...typography.title1,
fontSize: 32,
color: colors.text,
},
avatarOverlay: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
borderRadius: 40,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center',
alignItems: 'center',
},
avatarEditBadge: {
position: 'absolute',
bottom: 0,
right: 0,
backgroundColor: colors.surfaceSolid,
width: 28,
height: 28,
borderRadius: 14,
justifyContent: 'center',
alignItems: 'center',
borderWidth: 2,
borderColor: colors.background,
},
profileInfo: {
flex: 1,
justifyContent: 'center',
},
nameContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: spacing.xs,
},
name: {
...typography.title2,
color: colors.text,
marginRight: spacing.xs,
},
editNameIcon: {
padding: 4,
},
email: {
...typography.body,
color: colors.textSecondary,
fontSize: 14,
},
editNameContainer: {
flexDirection: 'row',
alignItems: 'center',
},
nameInput: {
...typography.title2,
color: colors.text,
flex: 1,
paddingVertical: 0,
paddingHorizontal: 0,
marginRight: spacing.sm,
borderBottomWidth: 1,
borderBottomColor: featureColors.profile.accent,
},
editNameButtons: {
flexDirection: 'row',
alignItems: 'center',
},
saveEditButton: {
width: 32,
height: 32,
borderRadius: 16,
backgroundColor: featureColors.profile.accent,
justifyContent: 'center',
alignItems: 'center',
marginLeft: spacing.xs,
},
cancelEditButton: {
width: 32,
height: 32,
borderRadius: 16,
backgroundColor: colors.glass.highlight,
justifyContent: 'center',
alignItems: 'center',
},
});
@@ -0,0 +1,47 @@
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Animated, { FadeInDown } from 'react-native-reanimated';
import { GlassCard } from '../../../components/ui';
import { colors, typography, spacing } from '../../../theme';
export interface SettingsSectionProps {
/** Section title displayed above the card */
title: string;
/** Animation delay in ms */
delay?: number;
/** Content to render inside the card */
children: React.ReactNode;
}
/**
* Reusable settings section with title and glass card container.
*/
export function SettingsSection({ title, delay = 200, children }: SettingsSectionProps) {
return (
<Animated.View
entering={FadeInDown.delay(delay).duration(500)}
style={styles.container}
>
<Text style={styles.title}>{title}</Text>
<GlassCard>
{children}
</GlassCard>
</Animated.View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: spacing.lg,
},
title: {
...typography.caption1,
fontWeight: '600',
letterSpacing: 2,
color: colors.textTertiary,
marginBottom: spacing.sm,
textTransform: 'uppercase',
},
});
export default SettingsSection;
@@ -0,0 +1,100 @@
import React from 'react';
import { View, Text, Switch, StyleSheet } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radius, typography, featureColors } from '../../../theme';
export interface SwitchItemProps {
/** Icon name (Ionicons) */
icon: string;
/** Main label text */
label: string;
/** Description text below label */
description: string;
/** Switch value */
value: boolean;
/** Whether the switch is disabled */
disabled?: boolean;
/** Callback when value changes */
onValueChange: (value: boolean) => void;
}
const ACCENT_GRADIENT = featureColors.profile.gradient as [string, string];
const ACCENT_COLOR = featureColors.profile.accent;
/**
* Reusable toggle switch row for settings screens.
*/
export function SwitchItem({
icon,
label,
description,
value,
disabled = false,
onValueChange,
}: SwitchItemProps) {
return (
<View style={styles.container}>
<View style={styles.left}>
<LinearGradient
colors={ACCENT_GRADIENT}
style={styles.iconContainer}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
>
<Ionicons name={icon as any} size={20} color={colors.text} />
</LinearGradient>
<View style={styles.textContainer}>
<Text style={styles.label}>{label}</Text>
<Text style={styles.description}>{description}</Text>
</View>
</View>
<Switch
value={value}
onValueChange={onValueChange}
disabled={disabled}
trackColor={{ false: colors.glass.border, true: colors.secondaryLight }}
thumbColor={value ? ACCENT_COLOR : colors.textTertiary}
ios_backgroundColor={colors.glass.border}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: spacing.xs,
},
left: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
marginRight: spacing.md,
},
iconContainer: {
width: 40,
height: 40,
borderRadius: radius.lg,
justifyContent: 'center',
alignItems: 'center',
marginRight: spacing.md,
},
textContainer: {
flex: 1,
},
label: {
...typography.body,
fontWeight: '500',
color: colors.text,
},
description: {
...typography.caption1,
color: colors.textSecondary,
marginTop: 2,
},
});
export default SwitchItem;
@@ -0,0 +1,12 @@
// Profile feature components
export { ProfileHeader } from './ProfileHeader';
export { CoupleStatus } from './CoupleStatus';
export { PrivacySettings } from './PrivacySettings';
export { DangerZone } from './DangerZone';
export { SettingsSection } from './SettingsSection';
export type { SettingsSectionProps } from './SettingsSection';
export { SwitchItem } from './SwitchItem';
export type { SwitchItemProps } from './SwitchItem';
export { MenuItem } from './MenuItem';
export type { MenuItemProps } from './MenuItem';
@@ -0,0 +1,3 @@
// Profile feature hooks
export { useProfileSettings } from './useProfileSettings';
export { useCoupleManagement } from './useCoupleManagement';
@@ -0,0 +1,129 @@
import { useState } from 'react';
import { Alert } from 'react-native';
import { useRouter } from 'expo-router';
import { useAuthStore, useMatchStore, useMessageStore, usePacksStore } from '../../../store';
import { supabase } from '../../../lib/supabase';
import { Events } from '../../../lib/analytics';
export function useCoupleManagement() {
const router = useRouter();
const { fetchCouple, fetchUser, signOut } = useAuthStore();
const { clearMatches } = useMatchStore();
const { clearMessages } = useMessageStore();
const { clearPacks } = usePacksStore();
const [isResettingProgress, setIsResettingProgress] = useState(false);
const handleUnpair = async () => {
Alert.alert(
"Unpair Partner",
"Are you sure you want to unpair? This cannot be undone.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Unpair",
style: "destructive",
onPress: async () => {
try {
await supabase.functions.invoke("manage-couple", {
method: "DELETE",
});
await fetchCouple();
// Refresh user to update UI state
await fetchUser();
} catch (error) {
Alert.alert("Error", "Failed to unpair");
}
},
},
]
);
};
const handleDeleteRelationship = async () => {
try {
const { error } = await supabase.functions.invoke("delete-relationship", {
method: "DELETE",
});
if (error) throw error;
// Clear local stores
clearMatches();
clearMessages();
clearPacks();
// Refresh user data
await fetchUser();
Events.relationshipEnded();
Alert.alert("Success", "All relationship data has been deleted.");
} catch (error) {
console.error("Delete relationship error:", error);
Alert.alert("Error", "Failed to delete relationship data. Please try again.");
throw error;
}
};
const handleResetProgress = async () => {
Alert.alert(
"Reset Progress",
"This will delete all your swipes, matches, and chat messages. You'll stay connected with your partner and can start fresh. This cannot be undone.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Reset",
style: "destructive",
onPress: async () => {
setIsResettingProgress(true);
try {
const { error } = await supabase.functions.invoke("reset-couple-progress", {
method: "DELETE",
});
if (error) throw error;
// Clear local stores
clearMatches();
clearMessages();
Alert.alert("Success", "Your progress has been reset. You can now start swiping again!");
} catch (error) {
Alert.alert("Error", "Failed to reset progress. Please try again.");
} finally {
setIsResettingProgress(false);
}
},
},
]
);
};
const handleSignOut = () => {
Alert.alert(
"Sign Out",
"Are you sure you want to sign out?",
[
{ text: "Cancel", style: "cancel" },
{
text: "Sign Out",
style: "destructive",
onPress: signOut,
},
]
);
};
const navigateToPairing = () => {
router.push("/(app)/pairing");
};
return {
isResettingProgress,
handleUnpair,
handleDeleteRelationship,
handleResetProgress,
handleSignOut,
navigateToPairing,
};
}
@@ -0,0 +1,334 @@
import { useState, useEffect, useCallback } from 'react';
import { Alert, Platform, ActionSheetIOS, Linking } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import { decode } from 'base64-arraybuffer';
import { useAuthStore, useSubscriptionStore, usePacksStore } from '../../../store';
import { supabase } from '../../../lib/supabase';
import { Events } from '../../../lib/analytics';
import {
isBiometricAvailable,
isBiometricEnabled,
setBiometricEnabled,
getBiometricType,
} from '../../../lib/biometricAuth';
export function useProfileSettings() {
const { user, fetchUser } = useAuthStore();
const { fetchPacks } = usePacksStore();
const { restorePurchases, isPurchasing } = useSubscriptionStore();
// Name Editing
const [isEditingName, setIsEditingName] = useState(false);
const [newName, setNewName] = useState(user?.name || "");
const [isUpdatingName, setIsUpdatingName] = useState(false);
// Avatar
const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
// Preferences
const [showExplicit, setShowExplicit] = useState(user?.show_explicit_content ?? true);
const [isUpdatingExplicit, setIsUpdatingExplicit] = useState(false);
// Biometrics
const [biometricAvailable, setBiometricAvailable] = useState(false);
const [biometricEnabledState, setBiometricEnabledState] = useState(false);
const [biometricType, setBiometricType] = useState("Face ID");
const [isUpdatingBiometric, setIsUpdatingBiometric] = useState(false);
// Paywall
const [showPaywall, setShowPaywall] = useState(false);
// Initialize state from user object
useEffect(() => {
if (user?.name) {
setNewName(user.name);
}
if (user?.show_explicit_content !== undefined) {
setShowExplicit(user.show_explicit_content);
}
}, [user]);
// Check biometric availability
useEffect(() => {
const checkBiometric = async () => {
const available = await isBiometricAvailable();
setBiometricAvailable(available);
if (available) {
const enabled = await isBiometricEnabled();
setBiometricEnabledState(enabled);
const type = await getBiometricType();
setBiometricType(type);
}
};
checkBiometric();
}, []);
// Name Actions
const handleUpdateName = async () => {
if (!user?.id) return;
const trimmedName = newName.trim();
if (!trimmedName) {
Alert.alert("Error", "Name cannot be empty");
return;
}
if (trimmedName === user.name) {
setIsEditingName(false);
return;
}
setIsUpdatingName(true);
try {
const { error } = await supabase
.from('profiles')
.update({
name: trimmedName,
updated_at: new Date().toISOString(),
})
.eq('id', user.id);
if (error) throw error;
await fetchUser();
setIsEditingName(false);
Events.profileUpdated(["name"]);
} catch (error) {
Alert.alert("Error", "Failed to update name. Please try again.");
setNewName(user.name || "");
} finally {
setIsUpdatingName(false);
}
};
const handleCancelEditName = useCallback(() => {
setNewName(user?.name || "");
setIsEditingName(false);
}, [user?.name]);
// Avatar Actions
const handleAvatarPress = () => {
if (Platform.OS === 'ios') {
ActionSheetIOS.showActionSheetWithOptions(
{
options: ['Cancel', 'Take Photo', 'Choose from Library'],
cancelButtonIndex: 0,
},
(buttonIndex) => {
if (buttonIndex === 1) {
pickAvatar('camera');
} else if (buttonIndex === 2) {
pickAvatar('library');
}
}
);
} else {
Alert.alert(
'Change Profile Photo',
'Choose an option',
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Take Photo', onPress: () => pickAvatar('camera') },
{ text: 'Choose from Library', onPress: () => pickAvatar('library') },
]
);
}
};
const pickAvatar = async (source: 'camera' | 'library') => {
try {
let result: ImagePicker.ImagePickerResult;
if (source === 'camera') {
const { status } = await ImagePicker.requestCameraPermissionsAsync();
if (status !== 'granted') {
Alert.alert('Permission Denied', 'Camera access is required to take a photo.');
return;
}
result = await ImagePicker.launchCameraAsync({
mediaTypes: ['images'],
allowsEditing: true,
aspect: [1, 1],
quality: 0.8,
});
} else {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
Alert.alert('Permission Denied', 'Photo library access is required to choose a photo.');
return;
}
result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsEditing: true,
aspect: [1, 1],
quality: 0.8,
});
}
if (!result.canceled && result.assets[0]) {
await uploadAvatar(result.assets[0].uri);
}
} catch (error) {
console.error('Error picking avatar:', error);
Alert.alert('Error', 'Failed to pick image. Please try again.');
}
};
const uploadAvatar = async (uri: string) => {
if (!user?.id) return;
setIsUploadingAvatar(true);
try {
let fileBody;
let ext = 'jpg';
if (Platform.OS === 'web') {
const response = await fetch(uri);
const blob = await response.blob();
fileBody = blob;
if (blob.type === 'image/png') ext = 'png';
else if (blob.type === 'image/webp') ext = 'webp';
} else {
const base64 = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64 });
fileBody = decode(base64);
const uriExt = uri.split('.').pop()?.toLowerCase();
if (uriExt && ['jpg', 'jpeg', 'png', 'webp'].includes(uriExt)) {
ext = uriExt === 'jpeg' ? 'jpg' : uriExt;
}
}
const fileName = `${user.id}/${Date.now()}.${ext}`;
const contentType = `image/${ext === 'jpg' ? 'jpeg' : ext}`;
// Upload to storage
const { error: uploadError } = await supabase.storage
.from('avatars')
.upload(fileName, fileBody, {
contentType,
upsert: true,
});
if (uploadError) throw uploadError;
// Get public URL
const { data: { publicUrl } } = supabase.storage
.from('avatars')
.getPublicUrl(fileName);
// Update profile with avatar URL
const { error: updateError } = await supabase
.from('profiles')
.update({
avatar_url: publicUrl,
updated_at: new Date().toISOString(),
})
.eq('id', user.id);
if (updateError) throw updateError;
// Refresh user data
await fetchUser();
Events.avatarUploaded();
} catch (error) {
console.error('Error uploading avatar:', error);
Alert.alert('Error', 'Failed to upload photo. Please try again.');
} finally {
setIsUploadingAvatar(false);
}
};
// Preference Actions
const handleExplicitToggle = async (value: boolean) => {
if (!user?.id) return;
setShowExplicit(value);
setIsUpdatingExplicit(true);
try {
const { error } = await supabase
.from('profiles')
.update({
show_explicit_content: value,
updated_at: new Date().toISOString(),
})
.eq('id', user.id);
if (error) throw error;
// Refresh user data and packs to reflect the change
await fetchUser();
await fetchPacks();
Events.profileUpdated(["show_explicit_content"]);
} catch (error) {
// Revert on error
setShowExplicit(!value);
Alert.alert("Error", "Failed to update preference. Please try again.");
} finally {
setIsUpdatingExplicit(false);
}
};
const handleBiometricToggle = async (value: boolean) => {
setBiometricEnabledState(value);
setIsUpdatingBiometric(true);
try {
await setBiometricEnabled(value);
} catch (error) {
setBiometricEnabledState(!value);
Alert.alert("Error", `Failed to ${value ? "enable" : "disable"} ${biometricType}. Please try again.`);
} finally {
setIsUpdatingBiometric(false);
}
};
// Subscription Actions
const handleRestorePurchases = async () => {
const restored = await restorePurchases();
if (restored) {
Alert.alert("Success", "Your purchases have been restored!");
} else {
Alert.alert("No Purchases Found", "No previous purchases found to restore.");
}
};
const handleManageSubscription = () => {
Linking.openURL("https://apps.apple.com/account/subscriptions");
};
return {
// State
isEditingName,
setIsEditingName,
newName,
setNewName,
isUpdatingName,
isUploadingAvatar,
showExplicit,
isUpdatingExplicit,
biometricAvailable,
biometricEnabled: biometricEnabledState,
biometricType,
isUpdatingBiometric,
showPaywall,
setShowPaywall,
isPurchasing,
// Actions
handleUpdateName,
handleCancelEditName,
handleAvatarPress,
handleExplicitToggle,
handleBiometricToggle,
handleRestorePurchases,
handleManageSubscription,
};
}
@@ -0,0 +1,3 @@
export * from './components';
export * from './hooks';
export { ProfileScreen } from './ProfileScreen';
@@ -0,0 +1,7 @@
import { featureColors } from '../../theme';
/** Profile color palette constants */
export const PROFILE_COLORS = {
ACCENT: featureColors.profile.accent,
ACCENT_GRADIENT: featureColors.profile.gradient as [string, string],
} as const;