"use client";

import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { MessageCircle, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { LeadForm, type LeadContext } from "./lead-form";
import { track } from "./fb-pixel";
import type { Business } from "./showroom-page";

const KEY = "lj_nudge";
const digitsOf = (s: string) => s.replace(/[^\d]/g, "");

/**
 * One polite "before you go" card per session. Desktop: when the pointer
 * leaves through the top of the window. Phone: after the visitor has read a
 * good part of the page and paused. Never shown twice, never on top of an
 * open sheet, and it goes away with one tap.
 */
export function ExitNudge({ business, ctx, suspended }: { business: Business; ctx: LeadContext; suspended: boolean }) {
  const reduced = useReducedMotion();
  const [show, setShow] = React.useState(false);
  const fired = React.useRef(false);
  const susp = React.useRef(suspended);
  susp.current = suspended;

  React.useEffect(() => {
    try {
      if (sessionStorage.getItem(KEY)) return;
    } catch {}
    const fire = () => {
      if (fired.current || susp.current) return;
      fired.current = true;
      try {
        sessionStorage.setItem(KEY, "1");
      } catch {}
      setShow(true);
    };
    const onLeave = (e: MouseEvent) => {
      if (e.clientY <= 0 && e.relatedTarget === null) fire();
    };    const fine = window.matchMedia("(hover: hover) and (pointer: fine)").matches;
    let idle: ReturnType<typeof setTimeout> | null = null;
    let deep = false;
    const onScroll = () => {
      const p = (window.scrollY + window.innerHeight) / Math.max(1, document.documentElement.scrollHeight);
      if (p > 0.55) deep = true;
      if (idle) clearTimeout(idle);
      if (deep) idle = setTimeout(fire, 25_000);
    };
    const start = setTimeout(() => {
      if (fine) document.addEventListener("mouseleave", onLeave);
      else window.addEventListener("scroll", onScroll, { passive: true });
    }, 12_000);
    return () => {
      clearTimeout(start);
      if (idle) clearTimeout(idle);
      document.removeEventListener("mouseleave", onLeave);
      window.removeEventListener("scroll", onScroll);
    };
  }, []);

  const wa = digitsOf(business.whatsapp);
  return (
    <AnimatePresence>
      {show ? (
        <>
          <motion.div key="bd" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-[60] bg-stone-950/45 backdrop-blur-[3px]" onClick={() => setShow(false)} />
          <motion.div key="card" role="dialog" aria-label="Before you go" initial={reduced ? false : { y: 40, opacity: 0, scale: 0.96 }} animate={{ y: 0, opacity: 1, scale: 1 }} exit={{ y: 30, opacity: 0, scale: 0.96 }} transition={{ type: "spring", stiffness: 380, damping: 32 }} className="fixed inset-x-3 bottom-3 z-[61] mx-auto max-w-md overflow-hidden rounded-3xl bg-surface shadow-2xl sm:inset-x-auto sm:bottom-auto sm:left-1/2 sm:top-1/2 sm:w-full sm:-translate-x-1/2 sm:-translate-y-1/2">
            <button type="button" onClick={() => setShow(false)} className="absolute right-3 top-3 z-10 flex size-8 items-center justify-center rounded-full bg-surface-2 text-fg-muted transition hover:rotate-90 hover:text-fg" aria-label="Close"><X className="size-4" /></button>
            <div className="p-5">
              <p className="eyebrow">Before you go</p>
              <h3 className="font-display text-2xl font-medium leading-tight">Not sure which one? Let us find it for you.</h3>
              <p className="mt-1 text-sm text-fg-muted">Tell us your dates and a real person from {business.name} calls you back — no account, no commitment.</p>
              <div className="mt-4">
                <LeadForm business={business} ctx={ctx} kind="EXIT" compact />
              </div>
              {wa ? (
                <Button variant="ghost" className="mt-2 w-full text-[#128C4B]" asChild onClick={() => track("Contact", { method: "whatsapp", content_name: "exit" })}>
                  <a href={`https://wa.me/${wa}?text=${encodeURIComponent(`Hello ${business.name}, I'm looking for an apartment${ctx.checkIn && ctx.checkOut ? ` from ${ctx.checkIn} to ${ctx.checkOut}` : ""}.`)}`} target="_blank" rel="noreferrer">
                    <MessageCircle /> Or write on WhatsApp
                  </a>
                </Button>
              ) : null}
            </div>
          </motion.div>
        </>
      ) : null}
    </AnimatePresence>
  );
}
