const {useEffect, useState, useRef} = React;

export default function ProModal({
                                     text = wp.i18n.__("Get access to Reading Mode, Dark Mode, and all premium customization tools.", "dracula-dark-mode"),
                                     isDismissable = true,
                                     watchVideo = false,
                                 }) {
    const [isOpen, setIsOpen] = useState(true);
    const modalRef = useRef(null);

    // -----------------------------
    // Countdown Timer Logic
    // -----------------------------
    const [timeLeft, setTimeLeft] = useState({days: 0, hours: 0, minutes: 0, seconds: 0});

    useEffect(() => {
        // Initialize or restore timer
        let saved = localStorage.getItem("dracula_offer_time");

        function setNewTime() {
            const newTime = Date.now() + 2.3 * 24 * 60 * 60 * 1000;
            localStorage.setItem("dracula_offer_time", newTime);
            saved = newTime;
        }

        if (!saved || isNaN(saved)) setNewTime();

        const interval = setInterval(() => {
            const now = Date.now();
            let diff = saved - now;

            if (diff <= 0) {
                setNewTime();
                diff = saved - now;
            }

            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
            const minutes = Math.floor((diff / (1000 * 60)) % 60);
            const seconds = Math.floor((diff / 1000) % 60);

            setTimeLeft({days, hours, minutes, seconds});
        }, 1000);

        return () => clearInterval(interval);
    }, []);

    // -----------------------------
    // Click Outside to Close
    // -----------------------------
    useEffect(() => {
        function handleClickOutside(e) {
            if (!isDismissable) return;
            if (modalRef.current && !modalRef.current.contains(e.target)) {
                setIsOpen(false);
            }
        }

        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, [isDismissable]);

    // -----------------------------
    // Destroy Modal on Close
    // -----------------------------
    useEffect(() => {
        if (!isOpen) {
            ReactDOM.unmountComponentAtNode(document.getElementById("dracula-pro-modal"));
        }
    }, [isOpen]);

    if (!isOpen) return null;

    return (
        <div className="dm-pro-overlay dracula-pro-modal-wrap">

            <div className="dm-pro-modal" ref={modalRef}>
                {isDismissable && (
                    <button className="dm-pro-close" onClick={() => setIsOpen(false)}>
                        &times;
                    </button>
                )}

                <div className="dm-pro-badge">
                    <img src={`${dracula.pluginUrl}/assets/images/offer.svg`} alt="PRO Badge"/>
                </div>

                <h3 className="dm-pro-title">
                    {wp.i18n.__("Unlock PRO Features", "dracula-dark-mode")}
                </h3>

                <p className="dm-pro-text">{text}</p>

                <div className="dm-pro-offer">
                    <span className="label">{wp.i18n.__("SPECIAL 30% OFF", "dracula-dark-mode")}</span>
                </div>

                <div className="dm-pro-timer">
                    {["days", "hours", "minutes", "seconds"].map((unit) => (
                        <div key={unit} className="timer-block">
                            <div className="num">{String(timeLeft[unit]).padStart(2, "0")}</div>
                            <div className="label">{unit.toUpperCase()}</div>
                        </div>
                    ))}
                </div>

                <ul className="dm-pro-features">
                    <li><i className={`dashicons dashicons-saved`}></i> Reading Mode</li>
                    <li><i className={`dashicons dashicons-saved`}></i> Advanced Toggle & Custom Colors</li>
                    <li><i className={`dashicons dashicons-saved`}></i> Image & Video Replacement</li>
                    <li><i className={`dashicons dashicons-saved`}></i> Page-Specific Dark Mode</li>
                    <li><i className={`dashicons dashicons-saved`}></i> Priority Support</li>
                </ul>

                <div className="dm-pro-actions">
                    {watchVideo && (
                        <button
                            className="dm-btn video"
                            onClick={() => {
                                const videoSrc = `https://www.youtube.com/embed/${watchVideo.id}?autoplay=1&rel=0`;
                                Swal.fire({
                                    title: watchVideo.title,
                                    html: `
                                        <div style="position:relative; padding-bottom:56.25%; height:0; overflow:hidden;">
                                            <iframe 
                                                src="${videoSrc}"
                                                frameborder="0"
                                                allow="autoplay; encrypted-media"
                                                allowfullscreen
                                                style="position:absolute; top:0; left:0; width:100%; height:100%;"
                                            ></iframe>
                                        </div>`,
                                    showCloseButton: true,
                                    showConfirmButton: false,
                                    width: "70%",
                                    customClass: {container: "dracula-swal dracula-pro-video-swal"},
                                });
                            }}
                        >
                            <i className={`dashicons dashicons-video-alt3`}></i>
                            {wp.i18n.__("Explore PRO", "dracula-dark-mode")}
                        </button>
                    )}

                    <a href="https://softlabbd.com/dracula-dark-mode-pricing" className="dm-btn primary">
                        <i className={`dracula-icon icon-pro`}></i>
                        {wp.i18n.__("Unlock PRO", "dracula-dark-mode")}
                    </a>
                </div>
            </div>
        </div>
    );
}

export function showProModal(text = wp.i18n.__('Upgrade to PRO to unlock the feature.', 'dracula-dark-mode'), watchVideo) {
    let element = document.getElementById('dracula-pro-modal');
    if (!element) {
        element = document.createElement('div');
        element.id = 'dracula-pro-modal';
        document.body.appendChild(element);
    }
    ReactDOM.render(<ProModal text={text} watchVideo={watchVideo}/>, element);
}
