"use client"

import { ChangePassword } from "@/components/utility/change-password"
import { supabase } from "@/lib/supabase/browser-client"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"

import { usePathname } from "next/navigation" // 导入 usePathname

import i18nConfig from "@/i18nConfig"

export default function ChangePasswordPage() {
  const [loading, setLoading] = useState(true)

  const router = useRouter()
  const pathname = usePathname() // 获取当前路径

  useEffect(() => {
    ;(async () => {
      //const supabaseClient = await supabase();  // Await the client creation
      const session = (await supabase.auth.getSession()).data.session

      if (!session) {
        // // 提取当前路径中的 locale 部分
        // const locale = pathname.split("/")[1] || "en"  // 获取路径中的 locale 部分，如果没有则默认为 "en"

        const pathSegments = pathname.split("/").filter(Boolean)
        const locales = i18nConfig.locales
        const defaultLocale = i18nConfig.defaultLocale
      
        let locale: (typeof locales)[number] = defaultLocale
      
        const segment = pathSegments[0] as (typeof locales)[number]
      
        if (locales.includes(segment)) {
          locale = segment
        }
        const homePath = locale === defaultLocale ? "/" : `/${locale}`



        console.log("...........[login page.tsx]")
        router.push(`${homePath}/login`)        
        // router.push(`${locale}/login`)
      } else {
        setLoading(false)
      }
    })()
  }, [])

  if (loading) {
    return null
  }

  return <ChangePassword />
}
