"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";

export type FeaturedOffer = {
  id: string;
  name: string;
  discountPercent: number;
  endsAt: string;
};

function dismissKey(offerId: string) {
  return `offer-banner-dismissed-${offerId}`;
}

export default function OfferBanner({ offer }: { offer: FeaturedOffer | null }) {
  const pathname = usePathname();
  // Starts hidden even for a live offer — the sessionStorage check only resolves after mount, and rendering
  // it open on the server would mismatch a client that already dismissed it this session.
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (!offer) return;
    setVisible(sessionStorage.getItem(dismissKey(offer.id)) !== "1");
  }, [offer]);

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

  function dismiss() {
    if (offer) sessionStorage.setItem(dismissKey(offer.id), "1");
    setVisible(false);
  }

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

  return (
    <div className="relative bg-gradient-to-r from-rose-700 to-rose-600 px-8 py-2 text-center text-sm text-white print:hidden">
      <Link href="/shop" className="font-medium hover:underline">
        ⚡ {offer.name} — {offer.discountPercent}% off, ends {endsLabel}
      </Link>
      <button
        onClick={dismiss}
        aria-label="Dismiss offer banner"
        className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full p-1 text-white/80 hover:bg-white/10 hover:text-white"
      >
        <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" 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>
    </div>
  );
}
