"use client";

import { useEffect, useRef, useState } from "react";
import { UserPlus } from "lucide-react";
import { SecretRegisterDialog } from "@/components/auth/secret-register-dialog";
import { Button } from "@/components/ui/button";
import { subscribeKonamiCode } from "@/lib/konami-code";
import { notify } from "@/lib/notifications/store";

export function KonamiRegisterGate() {
  const [unlocked, setUnlocked] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const skipNotifyRef = useRef(true);

  useEffect(() => {
    return subscribeKonamiCode(() => {
      setUnlocked((prev) => !prev);
    });
  }, []);

  useEffect(() => {
    if (!unlocked) setDialogOpen(false);
  }, [unlocked]);

  useEffect(() => {
    if (skipNotifyRef.current) {
      skipNotifyRef.current = false;
      return;
    }
    notify({
      type: "info",
      title: unlocked ? "秘密選單已解鎖" : "秘密選單已關閉",
    });
  }, [unlocked]);

  if (!unlocked) return null;

  return (
    <>
      <Button
        type="button"
        size="sm"
        variant="outline"
        className="fixed bottom-20 right-4 z-[70] shadow-lg lg:bottom-6 lg:right-6"
        onClick={() => setDialogOpen(true)}
      >
        <UserPlus className="h-4 w-4" />
        註冊新帳號
      </Button>
      <SecretRegisterDialog open={dialogOpen} onOpenChange={setDialogOpen} />
    </>
  );
}