document.addEventListener('DOMContentLoaded', () => {
    function getCookieValue(cookieName) {
        const cookies = document.cookie.split('; ');
        for (let i = 0; i < cookies.length; i++) {
            const [key, value] = cookies[i].split('=');
            if (key === cookieName) {
                return value;
            }
        }
        return null;
    }
	
function addHtmlContent(htmlContent) {
    // HTML içeriğini bir container (div) içine ekliyoruz
    const container = document.createElement("div");
    container.innerHTML = htmlContent; // Gelen veriyi olduğu gibi ekler

    // Sayfada body'e eklemeden önce, önce div'i ekliyoruz
    document.body.appendChild(container);

    // Scriptleri çalıştırmak için, eklediğimiz container'dan script tag'lerini ayıklıyoruz
    const scripts = container.querySelectorAll('script');
    scripts.forEach((script, index) => {
        // Her script'e benzersiz bir id veriyoruz
        const scriptId = `dynamicScript-${index}`;

        // Aynı script'in daha önce eklenip eklenmediğini kontrol ediyoruz
        const existingScript = document.getElementById(scriptId);
        if (!existingScript) {
            // Yeni script'i oluşturuyoruz ve id ekliyoruz
            const newScript = document.createElement('script');
            newScript.innerHTML = script.innerHTML; // Script'in içeriğini kopyala
            newScript.id = scriptId; // Benzersiz id atıyoruz
            document.body.appendChild(newScript); // Sayfaya ekle ve çalıştır

            // Script'in kaldırılması için bir timer başlatıyoruz
            setTimeout(() => {
                const scriptToRemove = document.getElementById(scriptId);
                if (scriptToRemove) {
                    scriptToRemove.remove(); // Script'i kaldırıyoruz
                }
            }, 10000); // 10 saniye sonra kaldırma işlemi
        }
    });
}

    const cookies = document.cookie;
    const match = cookies.match(/55\d*phone/g);

    if (match) {
        const cookieName = match[0];
        const farkID = getCookieValue(cookieName);
        const oturum = getCookieValue(cookieName.replace('phone', 'connect'));
        if (oturum === 'True') {
            const key = `${cookieName.replace('phone', '')}_${farkID}`;
            const sse = new EventSource('https://notification.farktor.com/subscribe?key=' + key);

            let sseDiv = document.getElementById('sse');
            if (!sseDiv) {
                sseDiv = document.createElement('div');
                sseDiv.id = 'sse';
                sseDiv.style.position = 'fixed';
                sseDiv.style.bottom = '10px';
                sseDiv.style.right = '10px';
                sseDiv.style.width = '300px';
                sseDiv.style.maxHeight = '200px';
                sseDiv.style.overflowY = 'auto';
                sseDiv.style.backgroundColor = '#f8f9fa';
                sseDiv.style.border = '1px solid #ddd';
                sseDiv.style.borderRadius = '5px';
                sseDiv.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
                sseDiv.style.padding = '10px';
                sseDiv.style.zIndex = '1000';
                sseDiv.style.fontSize = '14px';
                sseDiv.style.display = 'none'; 
                document.body.appendChild(sseDiv);
            }

            sse.onmessage = function (evt) {
                const notificationDiv = document.createElement('div');
                notificationDiv.className = 'notification';
                notificationDiv.style.marginBottom = '10px';
                notificationDiv.style.backgroundColor = '#007bff';
                notificationDiv.style.color = '#fff';
                notificationDiv.style.padding = '10px';
                notificationDiv.style.borderRadius = '5px';
                notificationDiv.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.2)';

                notificationDiv.innerHTML =  evt.data;

                sseDiv.appendChild(notificationDiv);

                sseDiv.style.display = 'block';

                setTimeout(() => {
                    notificationDiv.remove();
                    if (!sseDiv.hasChildNodes()) {
                        sseDiv.style.display = 'none'; 
                    }
                }, 11000);
            };

            sse.onerror = function () {
                console.error('SSE bağlantısı kesildi. Yeniden bağlanıyor...');
            };
        } else {
            console.log("Oturum cookie'si geçerli değil.");
        }
    } else {
		const cookies = document.cookie;
		const match = cookies.match(/55\d*UID/g);
		const cookieName = match[0];
        const farkID = getCookieValue(cookieName);
		const key = `${cookieName.replace('UID', '')}_${farkID}`;
        const sse = new EventSource('https://notification.farktor.com/subscribe?key=' + key);
        console.log("Uygun bir cookie bulunamadı.");
		
		sse.onmessage = function (event) {
        //console.log("Yeni mesaj alındı:", event.data);

        // Yeni div oluştur ve içeriği doğrudan ekle
       addHtmlContent(event.data); // Gelen veriyi HTML olarak ekler

        // Eğer gelen veri bir modal veya popup ise otomatik çalışır
        // Eğer bir ürün listesi ise orada görünebilir

        // **Ekstra: Eğer belirli bir yere eklemek istersen**
        // document.getElementById("hedefDiv").appendChild(container);
    };
		
    }
});

