// Show MoreMenuItems directly under MoreButton on click
document.addEventListener('DOMContentLoaded', function() {
    var moreButton = document.getElementById('MoreButton');
    var moreMenu = document.getElementById('MoreMenuItems');
    if (moreButton && moreMenu) {
        moreMenu.style.position = 'absolute';
        moreMenu.style.display = 'none';
        moreButton.addEventListener('click', function(e) {
            e.stopPropagation();
            var rect = moreButton.getBoundingClientRect();
            // Temporarily show menu to measure its width
            moreMenu.style.visibility = 'hidden';
            moreMenu.style.display = 'block';
            var menuRect = moreMenu.getBoundingClientRect();
            var menuWidth = Math.max(menuRect.width, rect.width);
            // Hide again if it was hidden
            moreMenu.style.display = 'none';
            moreMenu.style.visibility = '';
            // Position menu so its right edge is flush with the button's right edge
            moreMenu.style.left = '';
            moreMenu.style.right = (window.innerWidth - rect.right - window.scrollX) + 'px';
            // Do not set top property; let CSS/default placement handle vertical position
            moreMenu.style.marginTop = '0';
            moreMenu.style.minWidth = rect.width + 'px';
            moreMenu.style.display = (moreMenu.style.display === 'none' ? 'block' : 'none');
        });
        // Hide menu when clicking outside
        document.addEventListener('click', function(e) {
            if (!moreMenu.contains(e.target) && e.target !== moreButton) {
                moreMenu.style.display = 'none';
            }
        });
    }
});
// Provide a global function to clear cache and hard reload
window.clearCacheAndReload = function() {
    // Try to clear cache using Cache API (for service workers, if any)
    if ('caches' in window) {
        caches.keys().then(function(names) {
            return Promise.all(names.map(function(name) { return caches.delete(name); }));
        }).catch(function(){}).finally(function() {
            // Force a hard reload
            window.location.reload(true);
        });
    } else {
        // Fallback: force a hard reload
        window.location.reload(true);
    }
};
// lp_dynamic_loader.js
// Loads product data from JSON and logs the matched productName based on current URL

(function() {
    // --- Theme Button Group Logic ---
    function applyTheme(theme) {
        const html = document.documentElement;
        if (theme === 'system') {
            const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
            html.setAttribute('data-theme', systemTheme);
        } else {
            html.setAttribute('data-theme', theme);
        }
    }

    function setTheme(theme) {
        localStorage.setItem('theme', theme);
        applyTheme(theme);
        highlightThemeButton(theme);
    }

    function getSavedTheme() {
        return localStorage.getItem('theme') || 'system';
    }

    function highlightThemeButton(theme) {
        ['light','dark','system'].forEach(function(t) {
            var btn = document.getElementById('theme-btn-' + t);
            if (btn) {
                if (t === theme) {
                    btn.classList.add('active');
                    btn.classList.remove('btn-outline-secondary');
                    btn.classList.add('btn-primary');
                } else {
                    btn.classList.remove('active');
                    btn.classList.remove('btn-primary');
                    btn.classList.add('btn-outline-secondary');
                }
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Attach event listeners for theme buttons if present
        var btnLight = document.getElementById('theme-btn-light');
        var btnDark = document.getElementById('theme-btn-dark');
        var btnSystem = document.getElementById('theme-btn-system');
        if (btnLight && btnDark && btnSystem) {
            btnLight.onclick = function() { setTheme('light'); };
            btnDark.onclick = function() { setTheme('dark'); };
            btnSystem.onclick = function() { setTheme('system'); };
            // Initial theme application
            var savedTheme = getSavedTheme();
            applyTheme(savedTheme);
            highlightThemeButton(savedTheme);
            // Listen for system theme changes
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function() {
                if (getSavedTheme() === 'system') {
                    applyTheme('system');
                }
            });
        }
    });
    // Utility: Fetch JSON file
    function fetchJSON(url) {
        return fetch(url, {cache: 'no-store'})
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok');
                return response.json();
            });
    }

    // Utility: Get current path (excluding query/hash)
    function getCurrentPath() {
        return window.location.pathname.replace(/\/index\.html$/, '');
    }

    // Utility: Find product by path
    function findProductByPath(productsObj, path) {
        // productsObj is a dictionary, not an array
        const pathLower = path.toLowerCase();
        for (const key in productsObj) {
            if (Object.hasOwnProperty.call(productsObj, key)) {
                const product = productsObj[key];
                if (typeof product.pathname === 'string' && pathLower.startsWith(product.pathname.toLowerCase())) {
                    return product;
                }
            }
        }
        return null;
    }

    // Main loader
    function loadProductData() {
        fetchJSON('/resources/landingpages/json/lp_products.json')
            .then(data => {
                var path = getCurrentPath();
                var product = findProductByPath(data, path);
                if (product) {
                    // Inject productName into all .productname spans immediately
                    var productNameSpans = document.querySelectorAll('.productname');
                    for (var i = 0; i < productNameSpans.length; i++) {
                        productNameSpans[i].textContent = product.productName || '';
                    }
                    // Update the document title to include the product name
                    if (product.productName) {
                        document.title = product.productName + ' Documentation';
                    }
                    var messageCardsContainer = document.getElementById('messageCards');
                    if (messageCardsContainer) {
                        messageCardsContainer.innerHTML = '';
                        var cardRenderers = {
                            releaseNotesCard: function(card) {
                                if (card && card.enabled && Array.isArray(card.items) && card.items.length > 0) {
                                    var rnCard = document.createElement('div');
                                    rnCard.className = 'panel panel-primary releaseNotesCard';
                                    rnCard.innerHTML = '<div class="panel-heading" style="background-color: #337ab7; color: #fff;"><span class="bi bi-card-list"></span> &nbsp;&nbsp;Release Notes</div>';
                                    var rnBody = document.createElement('div');
                                    rnBody.className = 'panel-body';
                                    var rnList = document.createElement('ul');
                                    rnList.className = 'no_bullets';
                                    card.items.filter(function(item){return item.enabled;}).sort(function(a,b){return (a.position||0)-(b.position||0);}).forEach(function(item){
                                        var li = document.createElement('li');
                                        var a = document.createElement('a');
                                        a.href = item.link;
                                        a.textContent = item.title;
                                        a.target = '_blank';
                                        if (item.info) {
                                            var infoIcon = document.createElement('span');
                                            infoIcon.className = 'bi bi-info-circle custom-tooltip';
                                            infoIcon.setAttribute('data-bs-toggle', 'tooltip');
                                            infoIcon.setAttribute('data-bs-placement', 'top');
                                            infoIcon.setAttribute('aria-label', item.info);
                                            infoIcon.style.marginLeft = '5px';
                                            li.appendChild(a);
                                            li.appendChild(infoIcon);
                                        } else {
                                            li.appendChild(a);
                                        }
                                        rnList.appendChild(li);
                                    });
                                    rnBody.appendChild(rnList);
                                    rnCard.appendChild(rnBody);
                                    messageCardsContainer.appendChild(rnCard);
                                }
                            },
                            announcementCard: function(card) {
                                if (card && card.enabled) {
                                    var annCard = document.createElement('div');
                                    annCard.className = 'panel panel-primary announcementCard';
                                    annCard.style.borderColor = '#85bc20';
                                    annCard.innerHTML = '<div class="panel-heading" style="background-color: #85bc20; color: #fff;"><span class="bi bi-megaphone"></span> &nbsp;&nbsp;Announcements</div>';
                                    var annBody = document.createElement('div');
                                    annBody.className = 'panel-body';
                                    annBody.innerHTML = card.content ? card.content : '<p>There are no announcements at this time.</p>';
                                    annCard.appendChild(annBody);
                                    messageCardsContainer.appendChild(annCard);
                                }
                            },
                            feedbackCard: function(card) {
                                if (card && card.enabled) {
                                    var feedbackCard = document.createElement('div');
                                    feedbackCard.className = 'panel panel-primary messageCard';
                                    feedbackCard.innerHTML = '<div class="panel-heading" style="background-color: #337ab7; color: #fff;"><span class="bi bi-envelope"></span> &nbsp;&nbsp;We value your feedback!</div>';
                                    var feedbackBody = document.createElement('div');
                                    feedbackBody.className = 'panel-body';
                                    if (card.content && card.content.trim()) {
                                        feedbackBody.innerHTML = card.content;
                                    } // else leave feedbackBody empty
                                    feedbackCard.appendChild(feedbackBody);
                                    messageCardsContainer.appendChild(feedbackCard);
                                }
                            },
                            contactCard: function(card) {
                                if (card && card.enabled) {
                                    var contactCard = document.createElement('div');
                                    contactCard.className = 'panel panel-primary messageCard';
                                    contactCard.innerHTML = '<div class="panel-heading" style="background-color: #337ab7; color: #fff;"><span class="bi bi-telephone"></span> &nbsp;&nbsp;Contact us!</div>';
                                    var contactBody = document.createElement('div');
                                    contactBody.className = 'panel-body';
                                    if (card.content && card.content.trim()) {
                                        contactBody.innerHTML = card.content;
                                    } else {
                                        var email = (card.email || '').trim();
                                        var html = '';
                                        html += '<p>If you have any questions regarding this product, contact the Wolters Kluwer support team by phone or e-mail. Support staff is available Monday through Friday, 7 A.M. to 7 P.M. Central. Voice mail is available after hours and on weekends.</p>';
                                        html += '<p>You can contact us directly through either of the following:</p>';
                                        html += '<ul>';
                                        html += '<li>Tel: 1-800-274-2711, ext. 1126618</li>';
                                        if (email) {
                                            html += '<li>Email: <a href="mailto:' + email + '" target="_blank">' + email + '</a></li>';
                                        }
                                        html += '</ul>';
                                        contactBody.innerHTML = html;
                                    }
                                    contactCard.appendChild(contactBody);
                                    messageCardsContainer.appendChild(contactCard);
                                }
                            }
                        };
                        // Render cards in the order they appear in the product JSON
                        Object.keys(product).forEach(function(key) {
                            if (cardRenderers[key]) {
                                cardRenderers[key](product[key]);
                            }
                        });
                    }
                    console.log('Loaded product:', product.productName);
                    // Hide search feature if enableSearch is false
                    if (product.enableSearch === false) {
                        var searchForm = document.getElementById('searchForm');
                        if (searchForm) searchForm.style.display = 'none';
                        var searchResultsDiv = document.getElementById('searchResultsDiv');
                        if (searchResultsDiv) searchResultsDiv.style.display = 'none';
                    }
                    // Inject productSummary into all .productSummary spans
                    if (product.productSummary) {
                        document.querySelectorAll('.productSummary').forEach(function(el) {
                            el.textContent = product.productSummary;
                        });
                    }
                    // Inject showcase image if enabled
                    if (product.displayShowcaseImage && product.showcaseImageType) {
                        var showcaseDiv = document.getElementById('showcase_image');
                        if (showcaseDiv) {
                            showcaseDiv.innerHTML = '';
                            var img = document.createElement('img');
                            img.src = '/resources/landingpages/images/' + product.showcaseImageType;
                            img.alt = product.productName + ' showcase image';
                            img.className = 'img-fluid rounded';
                            showcaseDiv.appendChild(img);
                        }
                    }
                    // Dynamically render all enabled document sections from JSON
                    var container = document.getElementById('documentSectionsContainer');
                    if (container && Array.isArray(product.documentSections)) {
                        container.innerHTML = '';
                        product.documentSections
                            .filter(function(section) { return section.enabled; })
                            .sort(function(a, b) { return (a.position || 0) - (b.position || 0); })
                            .forEach(function(section) {
                                var sectionDiv = document.createElement('div');
                                sectionDiv.className = 'doc-section';
                                // Section title with icon
                                var h3 = document.createElement('h3');
                                var icon = document.createElement('span');
                                icon.className = 'bi bi-file-earmark';
                                icon.style.marginRight = '8px';
                                h3.appendChild(icon);
                                h3.appendChild(document.createTextNode(section.name));
                                sectionDiv.appendChild(h3);
                                // Section list
                                var ul = document.createElement('ul');
                                ul.className = 'force-standard-bullets';
                                ul.style.listStyleType = 'disc';
                                ul.style.listStylePosition = 'outside';
                                (section.documents || [])
                                    .filter(function(doc) { return doc.enabled; })
                                    .sort(function(a, b) { return (a.position || 0) - (b.position || 0); })
                                    .forEach(function(doc) {
                                        var li = document.createElement('li');
                                        var a = document.createElement('a');
                                        a.href = doc.url;
                                        a.textContent = doc.title;
                                        if (doc.tooltip) a.title = doc.tooltip;
                                        a.target = '_blank';
                                        li.appendChild(a);
                                        // If notes field is present, render it below the link
                                        if (doc.notes) {
                                            var notesDiv = document.createElement('div');
                                            notesDiv.className = 'doc-notes';
                                            notesDiv.innerHTML = doc.notes;
                                            li.appendChild(notesDiv);
                                        }
                                        ul.appendChild(li);
                                    });
                                sectionDiv.appendChild(ul);
                                container.appendChild(sectionDiv);
                            });
                    }
                } else {
                    console.log('No matching product found for this path:', path);
                }
            })
            .catch(err => {
                console.error('Error loading product data:', err);
            });
    }

    document.addEventListener('DOMContentLoaded', loadProductData);
})();
