All files / app/(onboarding)/onboarding page.tsx

57.43% Statements 278/484
85.1% Branches 40/47
57.14% Functions 4/7
57.43% Lines 278/484

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 5831x                                       76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x   76x 50x 50x 50x 50x 50x 50x 50x   50x 2x 2x 2x   48x 48x 48x 48x 48x   50x 4x 4x   4x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x   44x 50x       50x   50x 76x   76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x   76x 17x 12x 12x 12x 12x   5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x   5x 5x 5x 5x   5x 76x   76x 2x 2x 2x 2x 2x 2x   76x                                                                                                                                                                                                                                                                                               76x                   76x 33x 33x 33x 33x   33x   43x 43x 43x   43x 43x 43x 43x     43x 43x 43x 129x 129x 129x 129x 43x 86x 2x 84x 129x   129x 2x   127x   129x 129x 86x 86x 86x 2x 84x 86x 86x   129x 43x 43x 43x     43x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x   41x 41x 41x 41x 41x 41x 41x 41x 41x 5x   41x 12x   41x 41x 41x 12x   41x   41x 41x   41x 41x 41x 41x 41x   41x 41x 41x 41x 41x       76x 2x 2x 2x 2x   2x 2x 2x 2x 2x                   2x 2x   2x 2x 2x 2x 2x 2x 2x 2x     2x   2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x   2x   2x 2x 2x           2x   2x 2x   2x 2x 2x 2x 2x       76x                                                                                                                             76x 76x   76x  
'use client';
 
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { ArrowRight, ArrowLeft, Check, Loader2, Copy, CheckCircle2 } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { createClient } from '@/lib/supabase/client';
import { createProfileSchema, type CreateProfileInput } from '@/lib/validations/profile';
import { generateIdentityCode } from '@/lib/identity';
import { useToast } from '@/hooks/use-toast';
import { debounce, copyToClipboard } from '@/lib/utils';
 
type Step = 'loading' | 'username' | 'profile' | 'complete';
 
export default function OnboardingPage() {
  const [step, setStep] = useState<Step>('loading');
  const [username, setUsername] = useState('');
  const [isCheckingUsername, setIsCheckingUsername] = useState(false);
  const [usernameAvailable, setUsernameAvailable] = useState<boolean | null>(null);
  const [usernameError, setUsernameError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [generatedCode, setGeneratedCode] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const router = useRouter();
  const { toast } = useToast();
 
  useEffect(() => {
    const checkOnboardingStatus = async () => {
      try {
        const supabase = createClient();
        const {
          data: { user },
          error: authError,
        } = await supabase.auth.getUser();
 
        if (authError || !user) {
          router.push('/login');
          return;
        }
 
        const { data: userData } = await supabase
          .from('users')
          .select('onboarding_status')
          .eq('id', user.id)
          .single();
 
        if (userData?.onboarding_status === 'completed') {
          const hash = typeof window !== 'undefined' ? window.location.hash : '';
          const isEmailVerified = hash.includes('Confirmation') || hash.includes('confirmed');
 
          if (isEmailVerified) {
            const isRealEmail = user.email && !user.email.endsWith('@proofid.internal');
            if (user.email_confirmed_at && isRealEmail) {
              const { data: profile } = await supabase
                .from('profiles')
                .select('id')
                .eq('user_id', user.id)
                .single();
 
              if (profile) {
                const { data: emailVerificationType } = await supabase
                  .from('verification_types')
                  .select('id')
                  .eq('code', 'email')
                  .single();
 
                if (emailVerificationType) {
                  await supabase.from('user_verifications').upsert(
                    {
                      user_id: user.id,
                      profile_id: profile.id,
                      verification_type_id: emailVerificationType.id,
                      status: 'verified',
                      verified_at: user.email_confirmed_at,
                      completed_at: user.email_confirmed_at,
                    },
                    {
                      onConflict: 'user_id,verification_type_id',
                    }
                  );
                }
              }
            }
            router.push('/dashboard?email_verified=true');
          } else {
            router.push('/dashboard');
          }
          return;
        }
 
        setStep('username');
      } catch (error) {
        console.error('Error checking onboarding status:', error);
        setStep('username');
      }
    };
 
    checkOnboardingStatus();
  }, [router]);
 
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<CreateProfileInput>({
    resolver: zodResolver(createProfileSchema),
    defaultValues: {
      username: '',
      display_name: '',
      bio: '',
      role: '',
      whatsapp: '',
      email_public: '',
      linkedin_url: '',
      website_url: '',
    },
  });
 
  useEffect(() => {
    if (!username || username.length < 3) {
      setUsernameAvailable(null);
      setUsernameError(null);
      return;
    }
 
    const checkUsername = debounce(async (name: string) => {
      setIsCheckingUsername(true);
      try {
        const response = await fetch(
          `/api/profiles/check-username?username=${encodeURIComponent(name)}`
        );
        const data = await response.json();
 
        if (data.success) {
          setUsernameAvailable(data.data.available);
          setUsernameError(data.data.available ? null : data.data.reason);
        }
      } catch (error) {
        console.error('Error checking username:', error);
      } finally {
        setIsCheckingUsername(false);
      }
    }, 300);
 
    checkUsername(username);
  }, [username]);
 
  const handleUsernameSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (usernameAvailable) {
      setValue('username', username.toLowerCase());
      setStep('profile');
    }
  };
 
  const onProfileSubmit = async (data: CreateProfileInput) => {
    setIsSubmitting(true);
    try {
      const supabase = createClient();
      const {
        data: { user },
        error: authError,
      } = await supabase.auth.getUser();
 
      if (authError || !user) {
        toast({
          variant: 'destructive',
          title: 'Session Expired',
          description: 'Please log in again.',
        });
        router.push('/login');
        return;
      }
 
      const { data: existingUser, error: userCheckError } = await supabase
        .from('users')
        .select('id')
        .eq('id', user.id)
        .single();
 
      if (userCheckError || !existingUser) {
        const { error: createUserError } = await supabase.from('users').insert({
          id: user.id,
          email: user.email || '',
        });
 
        if (createUserError) {
          console.error('Error creating user record:', createUserError);
        }
      }
 
      const identityCode = generateIdentityCode();
      const referralCode = crypto.randomUUID().replace(/-/g, '').substring(0, 8);
 
      const profileData = {
        user_id: user.id,
        username: username.toLowerCase(),
        identity_code: identityCode,
        referral_code: referralCode,
        display_name: data.display_name,
        bio: data.bio || null,
        role: data.role || null,
        whatsapp: data.whatsapp || null,
        email_public: data.email_public || null,
        linkedin_url: data.linkedin_url || null,
        website_url: data.website_url || null,
        is_published: true,
      };
 
      const { data: profile, error: profileError } = await supabase
        .from('profiles')
        .insert(profileData)
        .select()
        .single();
 
      if (profileError) {
        toast({
          variant: 'destructive',
          title: 'Error',
          description: profileError.message || 'Error',
        });
        return;
      }
 
      const isRealEmail = user.email && !user.email.endsWith('@proofid.internal');
      if (user.email_confirmed_at && profile && isRealEmail) {
        try {
          const { data: emailVerificationType } = await supabase
            .from('verification_types')
            .select('id')
            .eq('code', 'email')
            .single();
 
          if (emailVerificationType) {
            await supabase.from('user_verifications').upsert(
              {
                user_id: user.id,
                profile_id: profile.id,
                verification_type_id: emailVerificationType.id,
                status: 'verified',
                verified_at: user.email_confirmed_at,
                completed_at: user.email_confirmed_at,
              },
              {
                onConflict: 'user_id,verification_type_id',
              }
            );
          }
        } catch (badgeError) {
          console.error('Failed to create email verification badge:', badgeError);
        }
      }
 
      await supabase.from('users').update({ onboarding_status: 'completed' }).eq('id', user.id);
 
      if (typeof window !== 'undefined') {
        const inviteToken = sessionStorage.getItem('invite_token');
        if (inviteToken) {
          try {
            await fetch('/api/invites/accept', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ token: inviteToken, userId: user.id }),
            });
            sessionStorage.removeItem('invite_token');
          } catch (inviteError) {
            console.error('Failed to accept invite:', inviteError);
          }
        }
 
        // Handle referral code signup
        const storedReferralCode = sessionStorage.getItem('referral_code');
        if (storedReferralCode) {
          try {
            await fetch('/api/referrals/track', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ referralCode: storedReferralCode, userId: user.id }),
            });
            sessionStorage.removeItem('referral_code');
          } catch (refError) {
            console.error('Failed to track referral:', refError);
          }
        }
      }
 
      setGeneratedCode(identityCode);
      setStep('complete');
    } catch (error) {
      toast({
        variant: 'destructive',
        title: 'Error',
        description: error instanceof Error ? error.message : 'Error',
      });
    } finally {
      setIsSubmitting(false);
    }
  };
 
  const handleCopyCode = async () => {
    if (generatedCode) {
      const success = await copyToClipboard(generatedCode);
      if (success) {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }
    }
  };
 
  if (step === 'loading') {
    return (
      <div className="flex min-h-screen items-center justify-center p-4">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }
 
  return (
    <div className="flex min-h-screen items-center justify-center p-4">
      <Card className="w-full max-w-lg">
        {/* Logo */}
        <div className="flex flex-col items-center gap-2 px-6 pt-6">
          <Image src="/logo-3.png" width={48} height={48} alt="ProofID" />
          <span className="gradient-text text-xl font-bold">ProofID</span>
        </div>
 
        {/* Step Indicator */}
        <div className="border-b px-6 py-4">
          <div className="flex items-center justify-between">
            {['username', 'profile', 'complete'].map((s, i) => (
              <div key={s} className="flex items-center">
                <div
                  className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${
                    step === s
                      ? 'bg-primary text-primary-foreground'
                      : i < ['username', 'profile', 'complete'].indexOf(step)
                        ? 'bg-green-500 text-white'
                        : 'bg-muted text-muted-foreground'
                  }`}
                >
                  {i < ['username', 'profile', 'complete'].indexOf(step) ? (
                    <Check className="h-4 w-4" />
                  ) : (
                    i + 1
                  )}
                </div>
                {i < 2 && (
                  <div
                    className={`mx-2 h-0.5 w-12 ${
                      i < ['username', 'profile', 'complete'].indexOf(step)
                        ? 'bg-green-500'
                        : 'bg-muted'
                    }`}
                  />
                )}
              </div>
            ))}
          </div>
        </div>
 
        {/* Username Step */}
        {step === 'username' && (
          <>
            <CardHeader>
              <CardTitle>Choose your username</CardTitle>
              <CardDescription>
                {`This will be your unique URL: proofid.in/${username || 'username'}`}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleUsernameSubmit} className="space-y-4">
                <div className="space-y-2">
                  <div className="relative">
                    <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 select-none text-sm text-muted-foreground">
                      proofid.in/
                    </span>
                    <Input
                      placeholder="username"
                      value={username}
                      onChange={(e) => setUsername(e.target.value.toLowerCase())}
                      className="pl-[100px]"
                      maxLength={20}
                    />
                    {isCheckingUsername && (
                      <Loader2 className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 animate-spin text-muted-foreground" />
                    )}
                    {!isCheckingUsername && usernameAvailable === true && (
                      <Check className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-green-500" />
                    )}
                  </div>
                  {usernameError && <p className="text-sm text-destructive">{usernameError}</p>}
                  {usernameAvailable === true && (
                    <p className="text-sm text-green-500">Username is available!</p>
                  )}
                  <p className="text-xs text-muted-foreground">
                    3-20 characters, letters, numbers, and underscores only
                  </p>
                </div>
 
                <Button
                  type="submit"
                  className="w-full"
                  disabled={!usernameAvailable || isCheckingUsername}
                >
                  Continue
                  <ArrowRight className="ml-2 h-4 w-4" />
                </Button>
              </form>
            </CardContent>
          </>
        )}
 
        {/* Profile Step */}
        {step === 'profile' && (
          <>
            <CardHeader>
              <CardTitle>Set up your profile</CardTitle>
              <CardDescription>
                Tell people about yourself and how they can reach you
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form
                onSubmit={handleSubmit(onProfileSubmit, (formErrors) => {
                  toast({
                    variant: 'destructive',
                    title: 'Validation Error',
                    description:
                      Object.values(formErrors)
                        .map((e) => e?.message)
                        .filter(Boolean)
                        .join(', ') || 'Please check your inputs',
                  });
                })}
                className="space-y-4"
              >
                <div className="space-y-2">
                  <label className="text-sm font-medium">Display Name *</label>
                  <Input
                    {...register('display_name')}
                    placeholder="John Doe"
                    disabled={isSubmitting}
                  />
                  {errors.display_name && (
                    <p className="text-sm text-destructive">{errors.display_name.message}</p>
                  )}
                </div>
 
                <div className="space-y-2">
                  <label className="text-sm font-medium">Role/Title</label>
                  <Input
                    {...register('role')}
                    placeholder="Full-Stack Developer"
                    disabled={isSubmitting}
                  />
                  {errors.role && <p className="text-sm text-destructive">{errors.role.message}</p>}
                </div>
 
                <div className="space-y-2">
                  <label className="text-sm font-medium">Bio</label>
                  <textarea
                    {...register('bio')}
                    placeholder="Tell people about yourself..."
                    className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    disabled={isSubmitting}
                  />
                </div>
 
                <div className="space-y-2">
                  <label className="text-sm font-medium">WhatsApp Number (recommended)</label>
                  <Input
                    {...register('whatsapp')}
                    placeholder="+919876543210"
                    disabled={isSubmitting}
                  />
                  <p className="text-xs text-muted-foreground">Include country code</p>
                </div>
 
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setStep('username')}
                    disabled={isSubmitting}
                  >
                    <ArrowLeft className="mr-2 h-4 w-4" />
                    Back
                  </Button>
                  <Button type="submit" className="flex-1" disabled={isSubmitting}>
                    {isSubmitting ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Creating...
                      </>
                    ) : (
                      <>
                        Create ProofID
                        <ArrowRight className="ml-2 h-4 w-4" />
                      </>
                    )}
                  </Button>
                </div>
              </form>
            </CardContent>
          </>
        )}
 
        {/* Complete Step */}
        {step === 'complete' && (
          <>
            <CardHeader className="text-center">
              <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-green-100">
                <CheckCircle2 className="h-8 w-8 text-green-600" />
              </div>
              <CardTitle>Your ProofID is ready!</CardTitle>
              <CardDescription>Here is your identity triplet</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-3 rounded-lg bg-muted/50 p-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Username:</span>
                  <span className="font-medium">{username}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Identity Code:</span>
                  <div className="flex items-center gap-2">
                    <code className="identity-code rounded bg-background px-2 py-1 text-primary">
                      {generatedCode}
                    </code>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-7 w-7"
                      onClick={handleCopyCode}
                    >
                      {copied ? (
                        <Check className="h-3.5 w-3.5 text-green-500" />
                      ) : (
                        <Copy className="h-3.5 w-3.5" />
                      )}
                    </Button>
                  </div>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Profile URL:</span>
                  <Link href={`/${username}`} className="font-medium text-primary hover:underline">
                    proofid.in/{username}
                  </Link>
                </div>
              </div>
 
              <div className="text-center text-sm text-muted-foreground">
                <p>
                  You can share your identity code on resumes, business cards, and social media.
                </p>
              </div>
 
              <div className="flex flex-col gap-2">
                <Button asChild>
                  <Link href="/dashboard">
                    Go to Dashboard
                    <ArrowRight className="ml-2 h-4 w-4" />
                  </Link>
                </Button>
                <Button variant="outline" asChild>
                  <Link href={`/${username}`}>View Your Profile</Link>
                </Button>
              </div>
            </CardContent>
          </>
        )}
      </Card>
    </div>
  );
}