// app/[locale]/clearcookies-then-redirect/page.tsx
"use client"

import { useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useTranslation } from "react-i18next"

export default function ClearCookiesThenRedirect({ params }: { params: { locale: string } }) {
  const router = useRouter()
  const { t } = useTranslation()
  const searchParams = useSearchParams()

  useEffect(() => {
    // 🔥 手动清除浏览器端 cookie（服务端清除不够）
    // document.cookie = "sb-67-auth-token=; path=/; max-age=0"
    // document.cookie = "sb-67-auth-token-code-verifier=; path=/; max-age=0"
    // document.cookie = "_ga=; path=/; max-age=0"

    const keysParam = searchParams.get("keys")
    const keys = keysParam ? keysParam.split(",") : []

    keys.forEach((key) => {
      document.cookie = `${key}=; path=/; max-age=0`
    })


    // ✅ 仍然调用服务端 API 处理 HttpOnly cookie（比如 Supabase 设置的）
    fetch("/api/clearcookies", { method: "POST" }).finally(() => {
      router.replace(`/${params.locale}/login?message=sessionExpired&cleaned=true`)
    })
  }, [])

  return (
    <div className="flex items-center justify-center h-screen text-sm text-muted-foreground">
      {t("login.clearing")}
    </div>
  )
}
