import { getSdkData } from "./init.js";
import { logger } from "../index.js";
import { getWebSocketInstance } from "../websocket.js";


let campaign_id: string | null = null;
let timestamp: string | null = null;
var popupDisplayed = false;
function getPopupPositionClass(position: string): string {
    switch (position) {
        case "top-left":
            return "popup-top-left";
        case "top-right":
            return "popup-top-right";
        case "bottom-left":
            return "popup-bottom-left";
        case "bottom-right":
            return "popup-bottom-right";
        case "center-left":
            return "popup-center-left";
        case "center-right":
            return "popup-center-right";
        case "top-center":
            return "popup-top-center";
        case "bottom-center":
            return "popup-bottom-center";
        case "center":
            return "popup-center";
        default:
            return "popup-top-right";
    }
}
function sendCampaignClickData(timestampValue = timestamp, campaign_id_Value = campaign_id, formData = "", socket: any): void {
    const sdkData = getSdkData();
    const data = {
        event_name: formData === "" ? "campaign_clicked" : "form_data",
        campaign_id: campaign_id_Value,
        user_session_id: sdkData.userID,
        website_url: sdkData.website_url,
        url_type: "web",
        timestamp: timestampValue ?? "",
        ...(formData && formData != "" && { formData: formData }),
        send_web_pop: true,
    };
    // var jsonData = JSON.stringify(data);
    // logger.info("JSON Data:", jsonData);
    socket.emit("clickedData", data);
}
function sendFormDataER(form: HTMLFormElement, socket: any): void {
    const formData: any = {};
    const elements = Array.from(form.elements) as HTMLInputElement[];
    elements.forEach((element) => {
        if (element.name) {
            formData[element.name] = element.value;
        }
    });
    // var jsonData = JSON.stringify(formData);
    const popup = document.querySelector('.popup-wrapper') as HTMLElement;
    if (popup) {
        popup.style.display = 'none';
    } else {
        // logger.info('Popup not found!');
    }
    sendCampaignClickData(undefined, undefined, formData, socket);
}
let stylePopup = `
      .popup-wrapper {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
        background-color: rgba(0, 0, 0, 0.5);
      }
        .popup-close-button {
          position: absolute;
          top: -15px;
          right: -15px;
          background: none;
          border: none;
          cursor: pointer;
          padding: 10px;
          font-size: 24px;
          color: #777;
          background-color: beige;
          width: 35px;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 35px;
          z-index: 1001;
        }
          .popup-close-button svg {
          width: 24px;
          height: 24px;
        }
   
        .popup-close-button:hover {
          color: #333;
        }
        .popup-container {
        background-color: #fff;
          max-width: 90%;
          width: auto;
          position: fixed;
          z-index: 1000;
        }
        .popup-top-left { top: 20px; left: 20px; }
        .popup-top-right { top: 20px; right: 20px; }
        .popup-bottom-left { bottom: 20px; left: 20px; }
        .popup-bottom-right { bottom: 20px; right: 20px; }
        .popup-center-left { top: 50%; left: 20px; transform: translateY(-50%); }
        .popup-center-right { top: 50%; right: 20px; transform: translateY(-50%); }
        .popup-top-center { top: 20px; left: 50%; transform: translateX(-50%); }
        .popup-bottom-center { bottom: 20px; left: 50%; transform: translateX(-50%); }
        .popup-center { top: 50%; left: 50%; transform: translate(-50%, -50%); }
          `;
async function showPopup(data: any, socket: any): Promise<void> {
    try {
        campaign_id = data.campaign_id;
        timestamp = data.timestamp;
        let url = data.popupContent + '?t=' + new Date().getTime();
        let response = await fetch(url);
        if (!response.ok) {
            throw new Error("Failed to fetch popup content: " + response.statusText);
        }
        let htmlContent = await response.text();
        // logger.info("html", htmlContent);

        var parser = new DOMParser();
        var doc = parser.parseFromString(htmlContent, "text/html");

        var styleElement = document.createElement("style");
        styleElement.innerHTML = stylePopup;
        document.head.appendChild(styleElement);

        var popupWrapper = document.createElement("div");
        popupWrapper.className = "popup-wrapper";

        var popupContainer = document.createElement("div");
        popupContainer.className = "popup-container " + getPopupPositionClass(data.position);
        popupContainer.innerHTML = doc.body.innerHTML;

        var styleTags = doc.querySelectorAll("style");
        styleTags.forEach((styleTag) => {
            document.head.appendChild(styleTag);
        });

        var scriptTags = doc.querySelectorAll("script");
        scriptTags.forEach((scriptTag) => {
            var newScript = document.createElement("script");
            if (scriptTag.src) {
                newScript.src = scriptTag.src;
            } else {
                newScript.textContent = scriptTag.textContent;
            }
            document.body.appendChild(newScript);
        });

        var closeButton = document.createElement("button");
        closeButton.className = "popup-close-button";
        closeButton.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"></line>
      <line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>
  `;

        closeButton.onclick = function () {
            popupWrapper.style.display = "none";
            document.body.classList.remove("dimmed-background");
            popupDisplayed = false;
        };

        popupContainer.appendChild(closeButton);

        popupWrapper.appendChild(popupContainer);

        document.body.appendChild(popupWrapper);

        var popupElement = popupWrapper.querySelector("#popup") as HTMLElement;
        if (popupElement) {
            popupElement.style.display = "flex";
        }
        const buttons = popupContainer.querySelectorAll("button:not(.popup-close-button)");
        buttons.forEach(button => {
            button.addEventListener("click", function () {
                sendCampaignClickData(data.timestamp, data.campaign_id, undefined, socket);
            });
        });
        var campaignElement = document.getElementById(data.campaign_id) as HTMLFormElement | null;

        if (campaignElement) {
            campaignElement.addEventListener("submit", function (event) {
                event.preventDefault();

                const form = event.target;
                if (form instanceof HTMLFormElement) {
                    sendFormDataER(form, socket);
                    alert("Form submitted successfully!");
                    form.reset();
                } else {
                    logger.error("Submitted element is not a form");
                }
            });
        }
    } catch (error) {
        logger.error("Error", error)
    }
}
async function subscribeUserPop(gaId: string): Promise<void> {
    const sdkData = getSdkData();
    sdkData.userID = gaId;

    if (sdkData.show_web_pop === "1") {
        logger.info("✅ Web Pop is enabled");

        let webSocketInstance = getWebSocketInstance(gaId);
        webSocketInstance.send("reply", {
            gaId: gaId,
            website_url: sdkData.website_url,
        });
    } else {
        logger.info("❌ Web Push is not enabled");
    }
}

const getPopupDisplayed = () => {
    return popupDisplayed;
};

export { showPopup, subscribeUserPop, getPopupDisplayed };
