import { useEffect, useRef, useState } from "react"
import { Link, useLocation } from "wouter"
import { Button } from "@workspace/ui/components/button"
import { useRoomStore } from "@/store/room"
import { useI18n } from "@/i18n/context"
import { errorMessage } from "@/i18n/error"

/** Lien d'invitation /join/:code → rejoint la room puis redirige vers le lobby. */
export function JoinPage({ code }: { code: string }) {
  const [, navigate] = useLocation()
  const { t } = useI18n()
  const joinRoom = useRoomStore((s) => s.joinRoom)
  const connected = useRoomStore((s) => s.connected)
  const [error, setError] = useState<string | null>(null)
  const tried = useRef(false)

  useEffect(() => {
    if (!connected || tried.current) {
      return
    }
    tried.current = true
    joinRoom(code)
      .then(({ roomCode }) => navigate(`/room/${roomCode}`, { replace: true }))
      .catch((err) => setError(errorMessage(t, err)))
  }, [connected, code, joinRoom, navigate, t])

  return (
    <div className="flex min-h-svh flex-col items-center justify-center gap-4 p-6 text-center">
      {error ? (
        <>
          <p className="text-muted-foreground text-sm">{error}</p>
          <Link href="/">
            <Button variant="secondary">{t.common.back}</Button>
          </Link>
        </>
      ) : (
        <p className="text-muted-foreground text-sm">
          {t.joinPage.connecting(code)}
        </p>
      )}
    </div>
  )
}
