import { useEffect, useState } from "react";
import { Link } from "@tanstack/react-router";
import { X, Gift } from "lucide-react";

export function ExitPopup() {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;
    if (sessionStorage.getItem("fixwp-exit-shown")) return;

    const onLeave = (e: MouseEvent) => {
      if (e.clientY <= 0) {
        setOpen(true);
        sessionStorage.setItem("fixwp-exit-shown", "1");
        document.removeEventListener("mouseout", onLeave);
      }
    };
    const t = window.setTimeout(() => {
      document.addEventListener("mouseout", onLeave);
    }, 8000);
    return () => {
      window.clearTimeout(t);
      document.removeEventListener("mouseout", onLeave);
    };
  }, []);

  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 grid place-items-center bg-navy-deep/70 backdrop-blur-sm p-4 animate-in fade-in">
      <div className="relative max-w-md w-full rounded-2xl bg-card p-8 shadow-elegant border border-border">
        <button
          onClick={() => setOpen(false)}
          aria-label="Close"
          className="absolute top-3 right-3 p-1.5 rounded-full text-muted-foreground hover:bg-muted"
        >
          <X className="h-5 w-5" />
        </button>
        <div className="grid place-items-center h-14 w-14 rounded-xl bg-gradient-emerald shadow-emerald">
          <Gift className="h-7 w-7 text-navy-deep" />
        </div>
        <h3 className="mt-5 text-2xl font-display font-bold">Wait — get a free site audit</h3>
        <p className="mt-2 text-muted-foreground">
          Before you go: we'll audit your WordPress site for security, speed and SEO issues at zero cost. Plus 10% off your first fix.
        </p>
        <Link
          to="/contact"
          onClick={() => setOpen(false)}
          className="mt-6 w-full inline-flex items-center justify-center rounded-lg bg-gradient-emerald px-5 py-3 font-semibold text-navy-deep shadow-emerald"
        >
          Claim Free Audit
        </Link>
      </div>
    </div>
  );
}
