"use client";

import { Lock, Sparkles, Unlock } from "lucide-react";
import { useEffect, useState } from "react";

import { cn } from "@/lib/utils";
import type { Locale } from "@/lib/locales";
import type { ProductSlug } from "@/lib/routes";

type LocalText = Record<Locale, string>;

type DashboardUnlockOverlayProps = {
  children: React.ReactNode;
  className?: string;
  locale: Locale;
  productName: string;
  productSlug: ProductSlug;
};

const text = (en: string, hi: string, gu: string): LocalText => ({ en, hi, gu });

const unlockCopy = {
  title: text(
    "Unlock live dashboard preview",
    "लाइव डैशबोर्ड प्रीव्यू अनलॉक करें",
    "લાઇવ ડેશબોર્ડ પ્રીવ્યુ અનલૉક કરો",
  ),
  subtitle: text(
    "Click to explore how this product works",
    "यह प्रोडक्ट कैसे काम करता है, देखने के लिए क्लिक करें",
    "આ પ્રોડક્ટ કેવી રીતે કામ કરે છે તે જોવા ક્લિક કરો",
  ),
  cta: text("Unlock Preview", "प्रीव्यू अनलॉक करें", "પ્રીવ્યુ અનલૉક કરો"),
  aria: text(
    "Unlock dashboard preview",
    "डैशबोर्ड प्रीव्यू अनलॉक करें",
    "ડેશબોર્ડ પ્રીવ્યુ અનલૉક કરો",
  ),
};

const unlockThemes = {
  pureestate: {
    accent: "#3678DC",
    glow: "rgba(54,120,220,0.24)",
    surface: "from-[#EFF6FF]/95 to-white/90",
  },
  buildpro: {
    accent: "#14B88A",
    glow: "rgba(20,184,138,0.22)",
    surface: "from-[#ECFDF5]/95 to-white/90",
  },
  societypro: {
    accent: "#278D61",
    glow: "rgba(20,184,138,0.22)",
    surface: "from-[#ECFDF5]/95 to-white/90",
  },
} satisfies Record<ProductSlug, { accent: string; glow: string; surface: string }>;

type UnlockState = "checking" | "locked" | "unlocked";

export default function DashboardUnlockOverlay({
  children,
  className,
  locale,
  productName,
  productSlug,
}: DashboardUnlockOverlayProps) {
  const [unlockState, setUnlockState] = useState<UnlockState>("checking");
  const [unlocking, setUnlocking] = useState(false);
  const theme = unlockThemes[productSlug];
  const storageKey = `puresaas-dashboard-unlocked-${productSlug}`;
  const isLocked = unlockState === "locked";
  const isChecking = unlockState === "checking";

  useEffect(() => {
    const timeoutId = window.setTimeout(() => {
      try {
        setUnlockState(window.localStorage.getItem(storageKey) === "true" ? "unlocked" : "locked");
      } catch {
        setUnlockState("locked");
      }
    }, 0);

    return () => window.clearTimeout(timeoutId);
  }, [storageKey]);

  const handleUnlock = () => {
    if (unlocking || unlockState === "unlocked") return;
    setUnlocking(true);

    try {
      window.localStorage.setItem(storageKey, "true");
    } catch {
      // The preview still unlocks when storage is unavailable.
    }

    window.setTimeout(() => {
      setUnlockState("unlocked");
      setUnlocking(false);
    }, 520);
  };

  return (
    <div className={cn("relative overflow-hidden", className)}>
      <div
        aria-hidden={isLocked ? true : undefined}
        className={cn(
          "transition-all duration-500 ease-out motion-reduce:transition-none",
          isChecking && "opacity-0",
          isLocked && "pointer-events-none scale-[1.01] select-none blur-[5px] brightness-[0.78]",
          unlocking && "scale-[1.005] blur-[2px] brightness-95",
          unlockState === "unlocked" && "scale-100 blur-0 brightness-100",
        )}
      >
        {children}
      </div>

      {isLocked ? (
        <div
          className={cn(
            "absolute inset-0 z-20 flex items-center justify-center bg-slate-950/24 px-4 backdrop-blur-[2px] transition-opacity duration-500 motion-reduce:transition-none",
            unlocking && "pointer-events-none opacity-0",
          )}
        >
          <div
            className="pointer-events-none absolute inset-0"
            style={{
              background: `radial-gradient(circle at center, ${theme.glow}, transparent 44%)`,
            }}
          />
          <button
            type="button"
            aria-label={`${unlockCopy.aria[locale]} - ${productName}`}
            onClick={handleUnlock}
            className={cn(
              "group relative z-10 w-full max-w-[250px] rounded-2xl border border-white/70 bg-gradient-to-br p-4 text-center shadow-[0_24px_70px_rgba(15,23,42,0.24)] backdrop-blur-xl transition duration-300 hover:-translate-y-1 focus:outline-none focus-visible:ring-4 focus-visible:ring-white/75 active:scale-[0.98] motion-reduce:transition-none",
              theme.surface,
            )}
          >
            <span
              className="mx-auto grid h-14 w-14 place-items-center rounded-2xl text-white shadow-[0_12px_28px_rgba(15,23,42,0.18)] transition duration-300 group-hover:scale-105 motion-reduce:transition-none"
              style={{ backgroundColor: theme.accent }}
            >
              {unlocking ? <Unlock size={24} /> : <Lock size={24} className="motion-safe:animate-pulse" />}
            </span>
            <span className="mt-4 block text-[15px] font-extrabold tracking-[-0.03em] text-[#17214d]">
              {unlockCopy.title[locale]}
            </span>
            <span className="mt-1 block text-[12px] font-semibold leading-5 text-[#65718b]">
              {unlockCopy.subtitle[locale]}
            </span>
            <span
              className="mt-4 inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-[12px] font-extrabold text-white"
              style={{ backgroundColor: theme.accent }}
            >
              <Sparkles size={14} />
              {unlockCopy.cta[locale]}
            </span>
          </button>
        </div>
      ) : null}
    </div>
  );
}
