import TurnstileChallenge from "./TurnstileChallenge"
import { DEV_MODE } from "../utils/constants"
import { isHuman } from "../utils/rigo"
import { toast } from "react-hot-toast"
import useStore from "../utils/store"
import { useTranslation } from "react-i18next"

export default function TurnstileModal({
  onClose,
  onError,
}: {
  onClose: () => void
  onError: () => void
}) {
  const auth = useStore((state) => state.auth)
  const setAuth = useStore((state) => state.setAuth)
  const { t } = useTranslation()

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-1000">
      <div className="bg-white p-4 rounded-lg max-w-md w-full flex flex-col items-center justify-center gap-4">
        <h2 className="text-xl font-semibold text-center">
          {t("turnstileModal.title")}
        </h2>
        <TurnstileChallenge
          siteKey={
            DEV_MODE ? "0x4AAAAAABeKMBYYinMU4Ib0" : "0x4AAAAAABeZ9tjEevGBsJFU"
          }
          onSuccess={async (token) => {
            const { human, message, token: jwtToken } = await isHuman(token)
            if (human) {
              toast.success(t("stepWizard.humanSuccess"))
              setAuth({
                ...auth,
                publicToken: jwtToken,
              })
              onClose()
            } else {
              console.error(message, "turnstileModal error")
              onError()
            }
          }}
          onError={() => {
            console.error("turnstileModal error")
            onError()
          }}
        />
      </div>
    </div>
  )
}
