import { VideoChat } from "@/components/video-chat"
import { createClient } from "@/lib/supabase/server"

export default async function Page() {
  const supabase = await createClient()
  const {
    data: { user },
  } = await supabase.auth.getUser()

  // Allow guests to view the homepage. Only signed-in users can actually
  // start a call — VideoChat will show a sign-in CTA for guests when they
  // try to Start.
  const adminEmail = process.env.ADMIN_EMAIL
  const isAdmin =
    !!user &&
    !!adminEmail &&
    (user.email ?? "").toLowerCase() === adminEmail.toLowerCase()

  const displayName =
    (user?.user_metadata?.display_name as string | undefined) ?? null

  // Fetch the canonical profile for the signed-in user so we can broadcast
  // their display name + gender to strangers they're matched with.
  // We intentionally read from the `profiles` table (not auth metadata) so
  // the values match what the user edited in their profile page.
  let profileGender: string | null = null
  let profileDisplayName: string | null = displayName
  let profileAvatarUrl: string | null = null
  // `verified` drives the blue tick rendered next to the user's name in
  // the header and broadcast to strangers in video chat. Always falls
  // back to false so guests/legacy profiles render no badge.
  let profileVerified = false
  if (user?.id) {
    const { data: profile } = await supabase
      .from("profiles")
      .select("display_name, gender, avatar_url, verified")
      .eq("id", user.id)
      .maybeSingle()
    if (profile) {
      profileGender = (profile.gender as string | null) ?? null
      profileDisplayName =
        (profile.display_name as string | null) ?? displayName ?? null
      profileAvatarUrl = (profile.avatar_url as string | null) ?? null
      profileVerified = !!(profile as { verified?: boolean }).verified
    }
  }

  return (
    <VideoChat
      userEmail={user?.email ?? null}
      userId={user?.id ?? null}
      displayName={profileDisplayName}
      userGender={profileGender}
      userAvatarUrl={profileAvatarUrl}
      userVerified={profileVerified}
      isAdmin={isAdmin}
    />
  )
}
