(function() {
    var scripts = document.getElementsByTagName('script');
    var currentScript = null;
    var targetContainerId = null;
    var timelineId = null;

    for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].src.indexOf('widget.js') !== -1) {
            currentScript = scripts[i];
            timelineId = currentScript.getAttribute('data-id');
            targetContainerId = currentScript.getAttribute('data-target'); // Optional explicit target
            break;
        }
    }

    if (!timelineId) {
        console.error('Timeline Widget: Missing data-id attribute on the script tag.');
        return;
    }

    var scriptUrl = new URL(currentScript.src);
    var apiUrl = scriptUrl.origin + '/cdn/widget/' + timelineId;

    function initWidget() {
        var containerId = targetContainerId || 'timeline-widget-container';
        var container = document.getElementById(containerId);

        if (!container) {
            console.error('Timeline Widget: Could not find container div with id "' + containerId + '". Please ensure you have <div id="' + containerId + '"></div> somewhere in your page body.');
            return;
        }

        container.innerHTML = '<p>Loading timeline...</p>';

        fetch(apiUrl)
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.text();
            })
            .then(function(html) {
                container.innerHTML = html;
            })
            .catch(function(error) {
                console.error('Timeline Widget: Error fetching timeline:', error);
                container.innerHTML = '<p>Error loading timeline.</p>';
            });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initWidget);
    } else {
        initWidget();
    }
})();