"use client";

import { BaseModal } from "@/components/modal";
import { useNumberFormatter } from "@/app/[lang]/providers";
import { useTranslations } from "next-intl";
import { Trophy, X } from "lucide-react";
import { useEffect, useState } from "react";

/** Ignore backdrop/outside close briefly after open so the same pointer event that ended the auction cannot dismiss the modal. */
const DISMISS_GUARD_MS = 750;

const CONFETTI_PIECES = [
  { left: "6%", delay: "0s", duration: "3.8s", color: "#f59e0b", size: 12 },
  { left: "14%", delay: "0.25s", duration: "3.2s", color: "#ef4444", size: 10 },
  { left: "23%", delay: "0.1s", duration: "3.6s", color: "#14b8a6", size: 9 },
  { left: "32%", delay: "0.5s", duration: "3.4s", color: "#2563eb", size: 11 },
  { left: "41%", delay: "0.15s", duration: "3.1s", color: "#f97316", size: 8 },
  { left: "50%", delay: "0.4s", duration: "3.7s", color: "#22c55e", size: 12 },
  { left: "59%", delay: "0.2s", duration: "3.3s", color: "#ec4899", size: 10 },
  { left: "68%", delay: "0.6s", duration: "3.8s", color: "#a855f7", size: 9 },
  { left: "77%", delay: "0.05s", duration: "3.25s", color: "#06b6d4", size: 11 },
  { left: "86%", delay: "0.35s", duration: "3.5s", color: "#84cc16", size: 10 },
  { left: "94%", delay: "0.18s", duration: "3.15s", color: "#eab308", size: 8 },
] as const;

const FIREWORKS = [
  { top: "12%", left: "14%", delay: "0s", color: "#f59e0b" },
  { top: "10%", left: "84%", delay: "0.45s", color: "#22c55e" },
  { top: "24%", left: "50%", delay: "0.2s", color: "#2563eb" },
] as const;

interface WinnerOverlayProps {
  open: boolean;
  winnerName: string | null;
  winnerPaddleUniqueId?: string | null;
  winnerPaddleNumber?: string | number | null;
  finalPrice: number;
  reason: string;
  label?: string;
  /** User dismissed the modal (X, backdrop, or Escape). No auto timer. */
  onClose: () => void;
}

export default function WinnerOverlay({
  open,
  winnerName,
  winnerPaddleUniqueId,
  winnerPaddleNumber,
  finalPrice,
  reason,
  label,
  onClose,
}: WinnerOverlayProps) {
  const t = useTranslations("WINNER_OVERLAY");
  const { toLatinDigits } = useNumberFormatter();
  const [blockOutsideDismiss, setBlockOutsideDismiss] = useState(false);

  useEffect(() => {
    if (!open) {
      setBlockOutsideDismiss(false);
      return;
    }
    setBlockOutsideDismiss(true);
    const timer = window.setTimeout(
      () => setBlockOutsideDismiss(false),
      DISMISS_GUARD_MS,
    );
    return () => window.clearTimeout(timer);
  }, [open]);
  const winnerPaddleDisplay =
    winnerPaddleNumber != null && String(winnerPaddleNumber).trim() !== ""
      ? /^\d+$/.test(String(winnerPaddleNumber).trim())
        ? `#${winnerPaddleNumber}`
        : String(winnerPaddleNumber)
      : null;

  const reasonLabels: Record<string, string> = {
    time: t("reason_time"),
    reserve_timeout: t("reason_reserve_timeout"),
    withdraw: t("reason_withdraw"),
    withdrawn: t("reason_withdraw"),
    market: t("reason_market"),
    reached_price: t("reason_reached_price"),
    owner_close_below_reserve: t("reason_owner_close_below_reserve"),
    unsold: t("reason_unsold"),
    skipped: t("reason_skipped"),
    admin_sold_immediate: t("reason_admin_sold_immediate"),
  };

  const reasonKey = String(reason || "")
    .toLowerCase()
    .trim()
    .replace(/-/g, "_");

  return (
    <BaseModal
      isOpen={open}
      onOpenChange={(nextOpen) => {
        if (!nextOpen) onClose();
      }}
      isDismissable
      isKeyboardDismissDisabled={blockOutsideDismiss}
      shouldCloseOnInteractOutside={() => !blockOutsideDismiss}
      bodyClassName="p-0"
      contentClassName="w-[min(92vw,600px)]"
    >
      <div className="relative overflow-hidden text-center space-y-6 px-5 pb-6 pt-3 sm:px-6 sm:pb-8 sm:pt-4">
        <button
          type="button"
          onClick={onClose}
          className="absolute left-2 top-2 z-30 rounded-full p-2 text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-[#0F5132]/40"
          aria-label={t("close_aria")}
        >
          <X className="h-5 w-5" strokeWidth={2.25} />
        </button>

        <h2 className="relative mx-auto max-w-[85%] text-center text-lg font-semibold leading-snug text-primary px-2">
          {t("title")}
        </h2>

        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 overflow-hidden"
        >
          <div className="absolute inset-x-8 top-4 h-24 rounded-full bg-gradient-to-r from-amber-200/50 via-white/80 to-emerald-200/50 blur-2xl" />

          {FIREWORKS.map((firework, index) => (
            <div
              key={`firework-${index}`}
              className="winner-firework"
              style={{
                top: firework.top,
                left: firework.left,
                color: firework.color,
                animationDelay: firework.delay,
              }}
            >
              <span />
              <span />
              <span />
              <span />
            </div>
          ))}

          {CONFETTI_PIECES.map((piece, index) => (
            <span
              key={`confetti-${index}`}
              className="winner-confetti"
              style={{
                left: piece.left,
                width: `${piece.size}px`,
                height: `${piece.size * 1.8}px`,
                backgroundColor: piece.color,
                animationDelay: piece.delay,
                animationDuration: piece.duration,
              }}
            />
          ))}
        </div>

        <div className="relative mx-auto flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-amber-400 via-orange-400 to-emerald-500 shadow-[0_18px_45px_rgba(245,158,11,0.35)]">
          <div className="absolute inset-[-10px] rounded-full border-2 border-amber-300/60 winner-medal-ring" />
          <div className="absolute inset-[-20px] rounded-full border border-emerald-300/40 winner-medal-ring-delayed" />
          <Trophy className="h-9 w-9 text-white drop-shadow-sm" />
        </div>

        {label && (
          <div className="relative text-sm text-slate-600 font-semibold">
            {label}
          </div>
        )}

        <div className="relative space-y-2">
          <div className="text-4xl font-extrabold text-[#0F5132]">
            {winnerName ||
              winnerPaddleUniqueId ||
              winnerPaddleDisplay ||
              t("no_winner")}
          </div>
          {(winnerName || winnerPaddleUniqueId || winnerPaddleDisplay) && (
            <div className="text-2xl font-bold text-slate-700">
              {toLatinDigits(finalPrice.toLocaleString())} {t("currency")}
            </div>
          )}
        </div>

        <div className="relative text-sm text-slate-600">
          {reasonLabels[reasonKey] || reason}
        </div>

        <p className="relative text-xs text-slate-500 px-2">{t("dismiss_hint")}</p>
      </div>

      <style jsx>{`
        .winner-confetti {
          position: absolute;
          top: -12%;
          border-radius: 999px;
          opacity: 0;
          transform: translateY(0) rotate(0deg);
          animation-name: winner-confetti-fall;
          animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1);
          animation-iteration-count: infinite;
        }

        .winner-firework {
          position: absolute;
          width: 14px;
          height: 14px;
          transform: translate(-50%, -50%);
        }

        .winner-firework span {
          position: absolute;
          inset: 0;
          border-radius: 999px;
          border: 2px solid currentColor;
          opacity: 0;
          animation: winner-firework-burst 1.8s ease-out infinite;
        }

        .winner-firework span:nth-child(2) {
          animation-delay: 0.18s;
        }

        .winner-firework span:nth-child(3) {
          animation-delay: 0.36s;
        }

        .winner-firework span:nth-child(4) {
          animation-delay: 0.54s;
        }

        .winner-medal-ring {
          animation: winner-ring 1.8s ease-out infinite;
        }

        .winner-medal-ring-delayed {
          animation: winner-ring 1.8s ease-out infinite;
          animation-delay: 0.45s;
        }

        @keyframes winner-confetti-fall {
          0% {
            opacity: 0;
            transform: translate3d(0, -10px, 0) rotate(0deg) scale(0.9);
          }
          10% {
            opacity: 1;
          }
          100% {
            opacity: 0;
            transform: translate3d(-14px, 340px, 0) rotate(540deg) scale(1.05);
          }
        }

        @keyframes winner-firework-burst {
          0% {
            opacity: 0;
            transform: scale(0.2);
          }
          18% {
            opacity: 0.95;
          }
          100% {
            opacity: 0;
            transform: scale(5.2);
          }
        }

        @keyframes winner-ring {
          0% {
            opacity: 0.9;
            transform: scale(0.82);
          }
          100% {
            opacity: 0;
            transform: scale(1.25);
          }
        }

        @media (prefers-reduced-motion: reduce) {
          .winner-confetti,
          .winner-firework span,
          .winner-medal-ring,
          .winner-medal-ring-delayed {
            animation: none !important;
          }
        }
      `}</style>
    </BaseModal>
  );
}
