import { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { useAuth } from '@/contexts/AuthContext'; import { usePolkadot } from '@/contexts/PolkadotContext'; import { supabase } from '@/lib/supabase'; import { User, Mail, Phone, Globe, MapPin, Calendar, Shield, AlertCircle, ArrowLeft, Award } from 'lucide-react'; import { useToast } from '@/hooks/use-toast'; import { fetchUserTikis, calculateTikiScore, getPrimaryRole, getTikiDisplayName, getTikiColor, getTikiEmoji, getUserRoleCategories } from '@/lib/tiki'; export default function Dashboard() { const { user } = useAuth(); const { api, isApiReady, selectedAccount } = usePolkadot(); const navigate = useNavigate(); const { toast } = useToast(); const [profile, setProfile] = useState(null); const [loading, setLoading] = useState(true); const [tikis, setTikis] = useState([]); const [tikiScore, setTikiScore] = useState(0); const [loadingTikis, setLoadingTikis] = useState(false); useEffect(() => { fetchProfile(); if (selectedAccount && api && isApiReady) { fetchTikiData(); } }, [user, selectedAccount, api, isApiReady]); const fetchProfile = async () => { if (!user) return; try { const { data, error } = await supabase .from('profiles') .select('*') .eq('id', user.id) .single(); if (error) throw error; setProfile(data); } catch (error) { console.error('Error fetching profile:', error); } finally { setLoading(false); } }; const fetchTikiData = async () => { if (!selectedAccount || !api) return; setLoadingTikis(true); try { const userTikis = await fetchUserTikis(api, selectedAccount.address); setTikis(userTikis); setTikiScore(calculateTikiScore(userTikis)); } catch (error) { console.error('Error fetching tiki data:', error); } finally { setLoadingTikis(false); } }; const sendVerificationEmail = async () => { if (!user?.email) { toast({ title: "Error", description: "No email address found", variant: "destructive" }); return; } console.log('🔄 Attempting to send verification email to:', user.email); console.log('🔐 User object:', user); try { // Method 1: Try resend API console.log('📧 Trying Supabase auth.resend()...'); const { error: resendError } = await supabase.auth.resend({ type: 'signup', email: user.email, }); if (resendError) { console.error('❌ Resend error:', resendError); } else { console.log('✅ Resend successful'); } // If resend fails, try alternative method if (resendError) { console.warn('Resend failed, trying alternative method:', resendError); // Method 2: Request password reset as verification alternative // This will send an email if the account exists const { error: resetError } = await supabase.auth.resetPasswordForEmail(user.email, { redirectTo: `${window.location.origin}/email-verification`, }); if (resetError) throw resetError; } toast({ title: "Verification Email Sent", description: "Please check your email inbox and spam folder", }); } catch (error: any) { console.error('Error sending verification email:', error); // Provide more detailed error message let errorMessage = "Failed to send verification email"; if (error.message?.includes('Email rate limit exceeded')) { errorMessage = "Too many requests. Please wait a few minutes and try again."; } else if (error.message?.includes('User not found')) { errorMessage = "Account not found. Please sign up first."; } else if (error.message) { errorMessage = error.message; } toast({ title: "Error", description: errorMessage, variant: "destructive" }); } }; const getRoleDisplay = (): string => { if (loadingTikis) return 'Loading...'; if (!selectedAccount) return 'Member'; if (tikis.length === 0) return 'Member'; const primaryRole = getPrimaryRole(tikis); return getTikiDisplayName(primaryRole); }; const getRoleCategories = (): string[] => { if (tikis.length === 0) return ['Member']; return getUserRoleCategories(tikis); }; if (loading) { return
Loading...
; } return (

User Dashboard

Account Status
{profile?.email_verified ? ( Verified ) : ( Unverified )}

Email verification status

Member Since
{new Date(profile?.joined_at || user?.created_at).toLocaleDateString()}

Registration date

Role
{getRoleDisplay()}

{selectedAccount ? 'From Tiki NFTs' : 'Connect wallet for roles'}

Tiki Score
{loadingTikis ? '...' : tikiScore}

{tikis.length} {tikis.length === 1 ? 'role' : 'roles'} assigned

Profile Roles & Tikis Security Activity Profile Information Your personal details and contact information
Full Name: {profile?.full_name || 'Not set'}
Email: {user?.email} {!profile?.email_verified && ( )}
Recovery Email: {profile?.recovery_email || 'Not set'} {profile?.recovery_email_verified && ( Verified )}
Phone: {profile?.phone_number || 'Not set'}
Website: {profile?.website || 'Not set'}
Location: {profile?.location || 'Not set'}
Roles & Tikis {selectedAccount ? 'Your roles from the blockchain (Pallet-Tiki)' : 'Connect your wallet to view your roles'} {!selectedAccount && (

Connect your Polkadot wallet to view your on-chain roles

)} {selectedAccount && loadingTikis && (

Loading roles from blockchain...

)} {selectedAccount && !loadingTikis && tikis.length === 0 && (

No roles assigned yet

Complete KYC to become a Citizen (Hemwelatî)

)} {selectedAccount && !loadingTikis && tikis.length > 0 && (
Primary Role: {getTikiEmoji(getPrimaryRole(tikis))} {getTikiDisplayName(getPrimaryRole(tikis))}
Total Score: {tikiScore}
Categories: {getRoleCategories().join(', ')}

All Roles ({tikis.length})

{tikis.map((tiki, index) => ( {getTikiEmoji(tiki)} {getTikiDisplayName(tiki)} ))}

Blockchain Address

{selectedAccount.address}

)}
Security Settings Manage your account security

Password

Last changed: Never

{!profile?.email_verified && (

Verify your email

Please verify your email to access all features

)}
Recent Activity Your recent actions and transactions

No recent activity

); }