"use client";

import { useEffect, useRef, useState } from "react";

export default function LausanneTestimonials() {
    const widgetRef = useRef<HTMLDivElement>(null);
    const [lang, setLang] = useState<"en" | "fr">("fr");
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        if (!widgetRef.current) return;
        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    setIsVisible(true);
                    observer.disconnect();
                }
            },
            { rootMargin: "200px" }
        );

        observer.observe(widgetRef.current);
        return () => observer.disconnect();
    }, []);

    useEffect(() => {
        const getLangFromCookie = (): "en" | "fr" => {
            const matches = document.cookie.match(/(?:^|; )lang=([^;]*)/);
            const value = matches ? matches[1]?.toLowerCase() : "fr";
            return value === "en" ? "en" : "fr";
        };

        // Set initial language state
        setLang(getLangFromCookie());

        // Update language state when cookies change or page is interacted with
        const handleLanguageUpdate = () => {
            setLang(getLangFromCookie());
        };

        window.addEventListener("languageChange", handleLanguageUpdate);
        window.addEventListener("click", handleLanguageUpdate);
        window.addEventListener("touchstart", handleLanguageUpdate);
        window.addEventListener("focus", handleLanguageUpdate);

        return () => {
            window.removeEventListener("languageChange", handleLanguageUpdate);
            window.removeEventListener("click", handleLanguageUpdate);
            window.removeEventListener("touchstart", handleLanguageUpdate);
            window.removeEventListener("focus", handleLanguageUpdate);
        };
    }, []);

    useEffect(() => {
        if (!isVisible || !widgetRef.current) return;

        // Prevent duplicate scripts and clear old widget contents
        widgetRef.current.innerHTML = "";

        const script = document.createElement("script");

        script.defer = true;
        script.src =
            `https://dbwx2z9xa7qt9.cloudfront.net/bundle.js?cachebust=1786649661078&lang=${lang}`;

        script.setAttribute("theme", "light");
        script.setAttribute("footer", "false");
        script.setAttribute("widget-type", "carousel");
        script.setAttribute("token", "6707e37ed60141b3d5459c32");
        script.setAttribute(
            "apiurl",
            "https://server.onlinereviews.tech/api/v0.0.9"
        );
        script.setAttribute("stats", "true");
        script.setAttribute("addReview", "false");
        script.setAttribute("profile-pic", "true");
        script.setAttribute("review-name", "true");
        script.setAttribute("positive-stars", "true");
        script.setAttribute("wl", "true");
        script.setAttribute(
            "wlndig",
            "https://medicalreviews.chokri.ch/oculus"
        );
        script.setAttribute("lang", lang);

        script.setAttribute(
            "brandStyle",
            "%7B%22sidebar_background%22%3A%22%23000000%22%2C%22sidebar_text%22%3A%22%23ffffff%22%2C%22brand_button_text_color%22%3A%22%23ffffff%22%2C%22brand_main_color%22%3A%22%23000000%22%2C%22brand_button_border_radius%22%3A%228px%22%2C%22brand_sidebar_text_color_opacity%22%3A%22%23ffffff1a%22%2C%22brand_button_hover%22%3A%22rgb(0%2C%200%2C%200)%22%2C%22brand_button_active%22%3A%22rgb(0%2C%200%2C%200)%22%2C%22brand_main_color_opacity%22%3A%22%230000001a%22%2C%22brand_font%22%3A%22Montserrat%2CInter%2CHelvetica%2CArial%2Csans-serif%22%2C%22star_color%22%3A%22%23128c7e%22%2C%22brand_main_background%22%3A%22%23F6F8F7%22%2C%22brand_card_background%22%3A%22white%22%2C%22poweredByLink%22%3A%22https%3A%2F%2Fwww.climbo.com%22%2C%22poweredicon%22%3A%22https%3A%2F%2Frecensioni-io-static-folder.s3.eu-central-1.amazonaws.com%2Fpublic_onlinereviews%2Ffreemium%2F66774aff42a32b39f74bde3c%2Fpowered.png%22%7D"
        );

        widgetRef.current.appendChild(script);
    }, [isVisible, lang]);

    return (
        <div
            ref={widgetRef}
            id="wid_1786649661078"
            className="w-full min-h-[150px]"
            lang={lang}
        />
    );
}
