document.addEventListener('DOMContentLoaded', () => {
    if (window.Livewire && typeof window.Livewire.dispatch === 'function') {
        document.addEventListener('closeModal', () => {
            document.querySelectorAll('dialog[data-modal]').forEach(dialog => {
                if (typeof dialog.close === 'function') {
                    dialog.close();
                }
            });
        });

    } else {
        console.warn('Livewire is not loaded yet.');
    }
});


function showToast({ type = 'success', message = '' }) {
const container = document.getElementById('toast-container');

const colors = {
success: {
icon: 'text-green-500 bg-green-100 dark:bg-green-800 dark:text-green-200',
svg: `<path d="M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm3.707 8.207-4 4a1 1 0 0 1-1.414 0l-2-2a1 1 0 0 1 1.414-1.414L9 10.586l3.293-3.293a1 1 0 0 1 1.414 1.414Z" />`,
},
error: {
icon: 'text-red-500 bg-red-100 dark:bg-red-800 dark:text-red-200',
svg: `<path d="M10 0a10 10 0 1 0 10 10A10 10 0 0 0 10 0Zm1 14a1 1 0 0 1-2 0v-2a1 1 0 0 1 2 0Zm0-4a1 1 0 0 1-2 0V6a1 1 0 0 1 2 0Z"/>`,
}
};

const toast = document.createElement('div');
toast.className = `flex items-center w-full max-w-xs p-4 text-gray-500 bg-white rounded-lg shadow dark:text-gray-400 dark:bg-gray-800`;
toast.setAttribute('role', 'alert');

toast.innerHTML = `
        <div class="inline-flex items-center justify-center flex-shrink-0 w-8 h-8 ${colors[type].icon} rounded-lg">
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">${colors[type].svg}</svg>
        </div>
        <div class="ml-3 text-sm font-normal">${message}</div>
        <div class="absolute inset-x-0 bottom-0 h-1 bg-${type === 'error' ? 'red' : 'green'}-500 animate-progress rounded-bl-md rounded-br-md"></div>
        <button type="button" class="ml-auto text-gray-400 hover:text-gray-900 dark:hover:text-white rounded-lg focus:ring-2 focus:ring-gray-300 p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700"
            onclick="this.parentElement.remove()">
            <svg class="w-3 h-3" fill="none" viewBox="0 0 14 14"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 1l6 6m0 0l6 6M7 7l6-6M7 7L1 13"/></svg>
        </button>
    `;
container.appendChild(toast);

setTimeout(() => {
toast.remove();
}, 4000);
}

window.addEventListener("showAlert", (event) => {
    const detail = event.detail[0];
    showToast(detail);
});

window.addEventListener("copyEmail", (event) => {
    const element = document.getElementById("copyEmail");
    const copyText = document.getElementById('copyEmailText').innerText
    if (element) {
        const textToCopy = element.innerHTML;
        navigator.clipboard.writeText(textToCopy).then(() => {
            const detail = { type: 'success', message: copyText};
            showToast(detail);
        }).catch(err => {
            const detail = { type: 'error', message: 'Failed to copy email' };
            showToast(detail);
            console.error('Copy failed:', err);
        });
    }
});

window.addEventListener("downloadFile", function (event) {
    const downloadId = event.detail?.download_id;
    if (!downloadId) return;

    const messageContainer = document.querySelector(`#message-${downloadId}`);
    if (!messageContainer) return;

    const textarea = messageContainer.querySelector("textarea");
    if (!textarea) return;

    const content = textarea.value;
    const blob = new Blob([content], { type: "message/rfc822" });
    const url = URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    link.download = `email-${downloadId}.eml`;
    document.body.appendChild(link);
    link.click();

    setTimeout(() => {
        link.remove();
        URL.revokeObjectURL(url);
    }, 2000);
});

window.addEventListener("printFile", function (event) {
    const printId = event.detail?.print_id;
    if (!printId) return;

    const messageContainer = document.querySelector(`#message-${printId}`);
    if (!messageContainer) return;

    const textarea = messageContainer.querySelector("textarea");
    if (!textarea) return;

    const content = textarea.value;

    const printWindow = window.open('', '', 'width=800,height=600');
    if (!printWindow) return;

    printWindow.document.write(`
        <html>
        <head>
            <title>Email Print</title>
            <style>
                body { font-family: sans-serif; padding: 20px; white-space: pre-wrap; }
            </style>
        </head>
        <body>${content.replace(/\n/g, '<br>')}</body>
        </html>
    `);

    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
    printWindow.close();
});

(function detectAdBlockReal() {
    const bait = document.createElement('div');
    bait.className = 'adsbygoogle ad-banner ad-unit';
    bait.style.cssText = 'width: 1px; height: 1px; position: absolute; left: -9999px;';
    document.body.appendChild(bait);

    setTimeout(() => {
        const baitBlocked =
            !bait ||
            bait.offsetParent === null ||
            bait.offsetHeight === 0 ||
            window.getComputedStyle(bait).getPropertyValue('display') === 'none' ||
            window.getComputedStyle(bait).getPropertyValue('visibility') === 'hidden';

        if (baitBlocked) {
            const elementShow = document.getElementById('sidebar-magic');
            elementShow.classList.remove('hidden');
            window.adBlockDetected = true;
        } else {
            window.adBlockDetected = false;
        }

        bait.remove();
    }, 100);
})();

document.addEventListener('DOMContentLoaded', function () {

    const syncElement = document.getElementById('gR7pT9xLwQ');
    const syncValue = syncElement.getAttribute('sync');

    if (!syncValue) {
        return;
    }

    setTimeout(async function () {

        let requestCount = 0;
        const maxRequests = 200;

        let isRequestInProgress = false;

        async function fetchStoreEmail() {
            if (isRequestInProgress) {
                return;
            }
            isRequestInProgress = true;
            try {
                const data = {
                    task: 'sync',
                    type: 'email',
                    timestamp: new Date().toISOString(),
                };

                const csrfToken = document.getElementById('gR7pT9xLwQ').innerText;
                const response = await fetch('/sync', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                    },
                    body: JSON.stringify(data),
                });

                if (response.ok) {

                } else {

                }
            } catch (error) {

            }

            requestCount++;

            if (requestCount >= maxRequests) {
                clearInterval(fetchInterval);
            }

            isRequestInProgress = false;
        }

        fetchStoreEmail();

        const fetchInterval = setInterval(fetchStoreEmail, 10000);
    }, 3000);
});


document.addEventListener('promotePremium', function () {
    setTimeout(() => {
        const event = new CustomEvent('modal-show', {
            detail: {
                name: 'premium',
                scope: null
            }
        });
        const showText = document.getElementById('premium-modal-limit');
        showText.classList.remove('hidden');
        const text1 = document.getElementById('focus-modal-text1');
        text1.classList.remove('text-accent');
        text1.classList.add('text-amber-500');
        const text2 = document.getElementById('focus-modal-text2');
        text2.classList.remove('text-accent');
        text2.classList.add('text-amber-500');
        document.dispatchEvent(event);
    }, 500);
});
