"use client";

import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import Cookies from "js-cookie";
import Callback2 from "@/components/sections/Callback2";

export default function Popup() {
    const [showPopup, setShowPopup] = useState(false);
    const pathname = usePathname();

    useEffect(() => {
        const prospectClient = Cookies.get("prospectClient");
        const popupShown = sessionStorage.getItem("popupShown");
        const lastPopupTime = localStorage.getItem("lastPopupTime");
        const firstVisit = sessionStorage.getItem("firstVisit");

        if (
            prospectClient === "true" ||
            pathname === "/contact" ||
            pathname === "/schedule" ||
            pathname === "/login" ||
            pathname === "/register" ||
            pathname === "/terms-of-use" ||
            pathname === "/forgot-password" ||
            pathname === "/client-area" ||
            pathname === "/reset-password"
        ) {
            return;
        }

        if (!popupShown) {
            if (!firstVisit) {
                const handleScroll = () => {
                    if (window.scrollY > document.documentElement.scrollHeight / 2) {
                        setShowPopup(true);
                        window.removeEventListener("scroll", handleScroll);
                        sessionStorage.setItem("popupShown", "true");
                        localStorage.setItem("lastPopupTime", Date.now().toString());
                        sessionStorage.removeItem("firstVisit");
                    }
                };

                window.addEventListener("scroll", handleScroll);
                return () => window.removeEventListener("scroll", handleScroll);
            } else if (firstVisit) {
                setShowPopup(true);
                sessionStorage.setItem("popupShown", "true");
                localStorage.setItem("lastPopupTime", Date.now().toString());
                sessionStorage.removeItem("firstVisit");
            }
        } else if (!lastPopupTime || Date.now() - parseInt(lastPopupTime) > 12 * 60 * 60 * 1000) {
            setShowPopup(true);
            localStorage.setItem("lastPopupTime", Date.now().toString());
        }
    }, [pathname]);

    const handleContainerClick = (e) => {
        if (e.target === e.currentTarget) {
            setShowPopup(false);
        }
    };

    if (!showPopup) return null;

    return (
        <div className="popup">
            <div className="container" onClick={handleContainerClick}>
                <section className="call-back-area-custom call-back-area rounded-5">
                    <div className="popup-close-btn" onClick={() => setShowPopup(false)}>
                        <i className="fas fa-times" />
                    </div>
                    <Callback2 />
                </section>
            </div>
        </div>
    );
}
