"use client";

import { useState, useEffect } from "react";
import Image from "next/image";

export default function PromoPopupComponent() {
    const [popup, setPopup] = useState<any>(null);
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const fetchPopup = async () => {
            try {
                const res = await fetch("/api/popups/active");
                if (!res.ok) return;

                const data = await res.json();
                if (!data) return;

                // Check active dates
                const now = new Date();
                if (data.startDate && new Date(data.startDate) > now) return;
                if (data.endDate && new Date(data.endDate) < now) return;

                // Check local storage limits
                const storageKey = `sfmspto_popup_${data.id}_views`;
                const views = parseInt(localStorage.getItem(storageKey) || "0");

                if (views < data.maxDisplaysPerUser) {
                    setPopup(data);
                    // Small delay before showing ensures the fade-in animation plays smoothly 
                    setTimeout(() => setIsVisible(true), 1500);
                    localStorage.setItem(storageKey, (views + 1).toString());
                }
            } catch (err) {
                console.error("Failed to load promo popup", err);
            }
        };

        fetchPopup();
    }, []);

    const handleClose = () => {
        setIsVisible(false);
    };

    if (!popup) return null;

    return (
        <>
            <div
                style={{
                    position: "fixed",
                    top: 0, left: 0, right: 0, bottom: 0,
                    backgroundColor: "rgba(0, 0, 0, 0.5)",
                    backdropFilter: "blur(4px)",
                    zIndex: 9998,
                    opacity: isVisible ? 1 : 0,
                    pointerEvents: isVisible ? "auto" : "none",
                    transition: "opacity 0.4s ease",
                }}
                onClick={handleClose}
            />

            <div
                style={{
                    position: "fixed",
                    top: "50%", left: "50%",
                    transform: `translate(-50%, -50%) scale(${isVisible ? 1 : 0.9})`,
                    opacity: isVisible ? 1 : 0,
                    pointerEvents: isVisible ? "auto" : "none",
                    zIndex: 9999,
                    background: "var(--surface)",
                    borderRadius: "16px",
                    boxShadow: "0 20px 40px rgba(0,0,0,0.2)",
                    width: "90%",
                    maxWidth: "480px",
                    overflow: "hidden",
                    transition: "all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275)",
                }}
            >
                {/* Close Button */}
                <button
                    onClick={handleClose}
                    style={{
                        position: "absolute", top: "12px", right: "12px",
                        background: "rgba(0,0,0,0.5)", color: "white",
                        border: "none", borderRadius: "50%",
                        width: "32px", height: "32px",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        cursor: "pointer", zIndex: 10,
                        fontSize: "1.2rem", fontWeight: "bold"
                    }}
                >
                    ×
                </button>

                {popup.imageUrl && (
                    <div style={{ position: "relative", width: "100%", height: "200px" }}>
                        <img
                            src={popup.imageUrl}
                            alt={popup.title}
                            style={{ width: "100%", height: "100%", objectFit: "cover" }}
                        />
                    </div>
                )}

                <div style={{ padding: "2rem", textAlign: "center" }}>
                    <h2 style={{ fontSize: "1.75rem", marginBottom: "1rem", color: "var(--primary)" }}>
                        {popup.title}
                    </h2>
                    <p style={{ color: "var(--text-muted)", fontSize: "1.1rem", marginBottom: "2rem", lineHeight: 1.5 }}>
                        {popup.message}
                    </p>

                    {(popup.ctaText || popup.ctaLink) && (
                        <a
                            href={popup.ctaLink || "#"}
                            className="btn-primary"
                            style={{ width: "100%", padding: "1rem", fontSize: "1.1rem" }}
                            onClick={() => {
                                if (!popup.ctaLink) handleClose();
                            }}
                        >
                            {popup.ctaText || "Learn More"}
                        </a>
                    )}
                </div>
            </div>
        </>
    );
}
