require('./bootstrap');

// Function to convert PDF_LINK format to clickable links in notifications
window.convertNotificationLinks = function() {
    // Find all notification descriptions that contain PDF_LINK format
    const notificationDescriptions = document.querySelectorAll('.notification-description, .text-body');
    
    notificationDescriptions.forEach(function(element) {
        const text = element.innerHTML;
        // Convert [PDF_LINK:URL] format to clickable links
        const convertedText = text.replace(/\[PDF_LINK:(.*?)\]/g, '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>');
        element.innerHTML = convertedText;
    });
};

// Function to convert HTML text to actual clickable links
window.convertHtmlTextToLinks = function() {
    // Find all notification descriptions that might contain HTML text
    const notificationElements = document.querySelectorAll('.notification-description, .text-body, [class*="notification"], [class*="message"]');
    
    notificationElements.forEach(function(element) {
        const text = element.textContent || element.innerText;
        
        // Check if the text contains HTML anchor tags as plain text
        if (text.includes('<a href=') && text.includes('</a>')) {
            // Extract the URL from the HTML text
            const urlMatch = text.match(/<a href="([^"]+)"[^>]*>/);
            if (urlMatch) {
                const url = urlMatch[1];
                // Replace the entire HTML text with a proper clickable link
                const linkText = text.replace(/.*📄 View Report: <a href="[^"]+"[^>]*>📄 View Report<\/a>.*/, '');
                const cleanText = linkText.replace(/📄 View Report: <a href="[^"]+"[^>]*>📄 View Report<\/a>/, '');
                
                // Create the new HTML content
                element.innerHTML = cleanText + '<br><a href="' + url + '" target="_blank" class="text-primary fw-bold" style="color: #007bff; font-weight: bold; text-decoration: none;">📄 View Report</a>';
            }
        }
    });
};

// Auto-convert links when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    window.convertNotificationLinks();
    window.convertHtmlTextToLinks();
});

// Also convert links when new notifications are loaded dynamically
window.addEventListener('load', function() {
    window.convertNotificationLinks();
    window.convertHtmlTextToLinks();
});

// Convert links when content changes (for dynamic content)
const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type === 'childList') {
            window.convertNotificationLinks();
            window.convertHtmlTextToLinks();
        }
    });
});

// Start observing when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});
