<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>
<script>
    function add_tooltips(){
        const tips = tippy('[data-term]', {
            content: 'Loading...',
            allowHTML:true,
            interactive:true,
            theme:'light',
            animation: 'scale-subtle',
            onCreate(instance) {
                // Setup our own custom state properties
                // set if was loaded
                instance._fetchInitualized = false;
                instance._error = null;
            },
            onShow(instance) {
                if (instance._fetchInitualized || instance._error) {
                    return;
                }

                instance._fetchInitualized = true;
                fetch(`/api/terms/${instance.reference.dataset.term}/`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.term){
                            instance.setContent(`<h4>${data.term}</h4><p>${data.definition}</p>`);
                        }else{
                            instance.setContent("<p style='color: red'>Could not find definition</p>");
                        }
                    })
                    .catch(error => {
                        instance._error = error;
                        instance.setContent(`Request failed. ${error}`);
                    });
            },
        });
    }
    add_tooltips();
</script>
