<neos:contentElement.wrap node="{node}">
    <!-- WIIF Chat Widget custom element -->
    <wiif-chat-widget
        id="ki-chatbot-widget"
        wl="{wiifChatId}"
    >
    </wiif-chat-widget>
</neos:contentElement.wrap>

<script defer src="https://api.wiif.net/hsw-chatbot/assets/bundle.js">
</script>

<!-- Script for token refresh -->
<script>
    // Function to fetch a new token from the /newtoken endpoint
    async function fetchNewToken() {
        try {
            const response = await fetch('/?type=wiifChatToken');

            if (!response.ok) {
                console.error('Token fetch failed:', response.status, response.statusText);
                return null;
            }

            const data = await response.json();
            return data?.access_token;
        } catch (error) {
            console.error('Error fetching token:', error);
            return null;
        }
    }

    // Wait until the custom element 'wiif-chat-widget' is defined
    customElements.whenDefined('wiif-chat-widget').then(() => {
        const widget = document.getElementById("ki-chatbot-widget");

        // Add event listener for the 'token-needed' event
        widget.addEventListener("token-needed", async (evt) => {
            const newToken = await fetchNewToken();

            if (newToken) {
                widget.setAttribute('token', newToken);
            }
        });
    });
</script>


<style>
    #launcher { visibility: hidden; }
    #ki-chatbot-widget { position: absolute; }
</style>

