"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import type { FeaturedOffer } from "@/components/OfferBanner";

const SHOW_DELAY_MS = 2500;

function seenKey(offerId: string) {
  return `offer-popup-seen-${offerId}`;
}

export default function FlashOfferPopup({ offer }: { offer: FeaturedOffer | null }) {
  const pathname = usePathname();
  const [show, setShow] = useState(false);

  useEffect(() => {
    if (!offer) return;
    if (sessionStorage.getItem(seenKey(offer.id)) === "1") return;
    const timer = setTimeout(() => setShow(true), SHOW_DELAY_MS);
    return () => clearTimeout(timer);
  }, [offer]);

  if (!offer || !show || pathname.startsWith("/iv-manage-84x2")) return null;

  function close() {
    if (offer) sessionStorage.setItem(seenKey(offer.id), "1");
    setShow(false);
  }

  const endsLabel = new Date(offer.endsAt).toLocaleDateString("en-IN", { day: "numeric", month: "short" });

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4 print:hidden" onClick={close}>
      <div onClick={(e) => e.stopPropagation()} className="relative w-full max-w-sm rounded-2xl bg-white p-6 text-center shadow-xl">
        <button onClick={close} aria-label="Close" className="absolute right-3 top-3 rounded-full p-1 text-stone-400 hover:bg-stone-100 hover:text-stone-700">
          <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
          </svg>
        </button>
        <p className="text-3xl">⚡</p>
        <h2 className="mt-2 font-[family-name:var(--font-heading)] text-xl font-bold text-rose-800">{offer.name}</h2>
        <p className="mt-1 text-3xl font-bold text-rose-700">{offer.discountPercent}% off</p>
        <p className="mt-1 text-sm text-stone-500">Ends {endsLabel}</p>
        <Link
          href="/shop"
          onClick={close}
          className="mt-4 inline-block w-full rounded-md bg-rose-700 px-5 py-2.5 text-sm font-semibold text-white hover:bg-rose-800"
        >
          Shop the sale
        </Link>
      </div>
    </div>
  );
}
