import { useState } from 'react'; import { Link } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { motion } from 'framer-motion'; import { useAuthStore } from '../store/auth'; import { authApi } from '../api/auth'; import { notificationsApi, NotificationSettings, NotificationSettingsUpdate, } from '../api/notifications'; import { referralApi } from '../api/referral'; import { brandingApi, type EmailAuthEnabled } from '../api/branding'; import ChangeEmailModal from '../components/ChangeEmailModal'; import { Card } from '@/components/data-display/Card'; import { Button } from '@/components/primitives/Button'; import { Switch } from '@/components/primitives/Switch'; import { staggerContainer, staggerItem } from '@/components/motion/transitions'; // Icons const CopyIcon = () => ( ); const CheckIcon = () => ( ); const ShareIcon = () => ( ); const ArrowRightIcon = () => ( ); const PencilIcon = () => ( ); export default function Profile() { const { t } = useTranslation(); const { user, setUser } = useAuthStore(); const queryClient = useQueryClient(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [copied, setCopied] = useState(false); const [showChangeEmailModal, setShowChangeEmailModal] = useState(false); // Referral data const { data: referralInfo } = useQuery({ queryKey: ['referral-info'], queryFn: referralApi.getReferralInfo, }); const { data: referralTerms } = useQuery({ queryKey: ['referral-terms'], queryFn: referralApi.getReferralTerms, }); const { data: branding } = useQuery({ queryKey: ['branding'], queryFn: brandingApi.getBranding, staleTime: 60000, }); // Check if email auth is enabled const { data: emailAuthConfig } = useQuery({ queryKey: ['email-auth-enabled'], queryFn: brandingApi.getEmailAuthEnabled, staleTime: 60000, }); const isEmailAuthEnabled = emailAuthConfig?.enabled ?? true; // Build referral link for cabinet const referralLink = referralInfo?.referral_code ? `${window.location.origin}/login?ref=${referralInfo.referral_code}` : ''; const copyReferralLink = () => { if (referralLink) { navigator.clipboard.writeText(referralLink); setCopied(true); setTimeout(() => setCopied(false), 2000); } }; const shareReferralLink = () => { if (!referralLink) return; const shareText = t('referral.shareMessage', { percent: referralInfo?.commission_percent || 0, botName: branding?.name || import.meta.env.VITE_APP_NAME || 'Cabinet', }); if (navigator.share) { navigator .share({ title: t('referral.title'), text: shareText, url: referralLink, }) .catch(() => {}); return; } const telegramUrl = `https://t.me/share/url?url=${encodeURIComponent(referralLink)}&text=${encodeURIComponent(shareText)}`; window.open(telegramUrl, '_blank', 'noopener,noreferrer'); }; const registerEmailMutation = useMutation({ mutationFn: ({ email, password }: { email: string; password: string }) => authApi.registerEmail(email, password), onSuccess: async () => { setSuccess(t('profile.emailSent')); setError(null); setEmail(''); setPassword(''); setConfirmPassword(''); const updatedUser = await authApi.getMe(); setUser(updatedUser); queryClient.invalidateQueries({ queryKey: ['user'] }); }, onError: (err: { response?: { data?: { detail?: string } } }) => { const detail = err.response?.data?.detail; if (detail?.includes('already registered')) { setError(t('profile.emailAlreadyRegistered')); } else if (detail?.includes('already have a verified email')) { setError(t('profile.alreadyHaveEmail')); } else { setError(detail || t('common.error')); } setSuccess(null); }, }); const resendVerificationMutation = useMutation({ mutationFn: authApi.resendVerification, onSuccess: () => { setSuccess(t('profile.verificationResent')); setError(null); }, onError: (err: { response?: { data?: { detail?: string } } }) => { setError(err.response?.data?.detail || t('common.error')); setSuccess(null); }, }); const { data: notificationSettings, isLoading: notificationsLoading } = useQuery({ queryKey: ['notification-settings'], queryFn: notificationsApi.getSettings, }); const updateNotificationsMutation = useMutation({ mutationFn: notificationsApi.updateSettings, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['notification-settings'] }); }, }); const handleNotificationToggle = (key: keyof NotificationSettings, value: boolean) => { const update: NotificationSettingsUpdate = { [key]: value }; updateNotificationsMutation.mutate(update); }; const handleNotificationValue = (key: keyof NotificationSettings, value: number) => { const update: NotificationSettingsUpdate = { [key]: value }; updateNotificationsMutation.mutate(update); }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); setError(null); setSuccess(null); const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!email.trim() || !emailRegex.test(email.trim())) { setError(t('profile.invalidEmail', 'Please enter a valid email address')); return; } if (!password || password.length < 8) { setError(t('profile.passwordMinLength')); return; } if (password !== confirmPassword) { setError(t('profile.passwordsMismatch')); return; } registerEmailMutation.mutate({ email, password }); }; return (

{t('profile.title')}

{/* User Info Card */}

{t('profile.accountInfo')}

{t('profile.telegramId')} {user?.telegram_id}
{user?.username && (
{t('profile.username')} @{user.username}
)}
{t('profile.name')} {user?.first_name} {user?.last_name}
{t('profile.registeredAt')} {user?.created_at ? new Date(user.created_at).toLocaleDateString() : '-'}
{/* Referral Link Widget */} {referralTerms?.is_enabled && referralLink && (

{t('referral.yourLink')}

{t('referral.title')}

{t('referral.shareHint', { percent: referralInfo?.commission_percent || 0 })}

)} {/* Email Section - only show when email auth is enabled */} {isEmailAuthEnabled && (

{t('profile.emailAuth')}

{user?.email ? (
Email
{user.email} {user.email_verified ? ( {t('profile.verified')} ) : ( {t('profile.notVerified')} )}
{!user.email_verified && (

{t('profile.verificationRequired')}

)} {user.email_verified && (

{t('profile.canLoginWithEmail')}

)}
) : (

{t('profile.linkEmailDescription')}

setEmail(e.target.value)} placeholder="your@email.com" className="input" />
setPassword(e.target.value)} placeholder={t('profile.passwordPlaceholder')} className="input" />

{t('profile.passwordHint')}

setConfirmPassword(e.target.value)} placeholder={t('profile.confirmPasswordPlaceholder')} className="input" />
{error && (
{error}
)} {success && (
{success}
)}
)} {(error || success) && user?.email && (
{error && (
{error}
)} {success && (
{success}
)}
)}
)} {/* Notification Settings */}

{t('profile.notifications.title')}

{notificationsLoading ? (
) : notificationSettings ? (
{/* Subscription Expiry */}

{t('profile.notifications.subscriptionExpiry')}

{t('profile.notifications.subscriptionExpiryDesc')}

handleNotificationToggle('subscription_expiry_enabled', checked) } />
{notificationSettings.subscription_expiry_enabled && (
{t('profile.notifications.daysBeforeExpiry')}
)}
{/* Traffic Warning */}

{t('profile.notifications.trafficWarning')}

{t('profile.notifications.trafficWarningDesc')}

handleNotificationToggle('traffic_warning_enabled', checked) } />
{notificationSettings.traffic_warning_enabled && (
{t('profile.notifications.atPercent')}
)}
{/* Balance Low */}

{t('profile.notifications.balanceLow')}

{t('profile.notifications.balanceLowDesc')}

handleNotificationToggle('balance_low_enabled', checked) } />
{notificationSettings.balance_low_enabled && (
{t('profile.notifications.threshold')} handleNotificationValue('balance_low_threshold', Number(e.target.value)) } min={0} className="input w-24 py-1" />
)}
{/* News */}

{t('profile.notifications.news')}

{t('profile.notifications.newsDesc')}

handleNotificationToggle('news_enabled', checked)} />
{/* Promo Offers */}

{t('profile.notifications.promoOffers')}

{t('profile.notifications.promoOffersDesc')}

handleNotificationToggle('promo_offers_enabled', checked) } />
) : (

{t('profile.notifications.unavailable')}

)} {/* Change Email Modal */} {showChangeEmailModal && user?.email && ( setShowChangeEmailModal(false)} currentEmail={user.email} /> )} ); }