<script>
    var injectScript = (src) => {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = src;
            script.async = true;
            script.onload = resolve;
            script.onerror = reject;
            document.head.appendChild(script);
        });
    }

    (async () => {
        if (window.navigator.onLine) {
            if (typeof HanziWriter === "undefined") {
                await injectScript('https://cdn.jsdelivr.net/npm/hanzi-writer@3.5/dist/hanzi-writer.min.js');
            }

            var writer = HanziWriter.create('diagram', '{{Hanzi}}', {
                width: 300,
                height: 300,
                radicalColor: '#337ab7',
                showCharacter: false,
                showOutline: false,
                showHintAfterMisses: 3,
                highlightOnComplete: true,
                padding: 5
            });

            writer.quiz();
        }
        else {
            document.querySelector('#diagram').style.display = 'none'
        }
    })();

    let hintNum = 0
    let hints = []

    function parseHint() {
        let examples = document.querySelector('#hint-container').innerHTML
        hints = examples.split('<')
        for (let i = 0; i < hints.length; i++) {
            parts = hints[i].split('[')[1].split(']')
            hints[i] = '<span style="font-weight:bold">' + parts[0] + '</span>' + parts[1].replace(']', '');
        }
    }

    function hintNumIndicator() {
        return '(' + (hintNum + 1) + '/' + hints.length + ')'
    }

    function revealHint() {
        element = document.querySelector('#hint');
        button = document.querySelector('#hint-button');

        if (button.innerText == 'Show hint') {
            hintNum = 0;
            parseHint();
        }

        if (hintNum < hints.length) {
            element.innerHTML += hints[hintNum] + '<br>';
            button.innerText = 'Next hint (' + (hintNum + 1) + '/' + hints.length + ')';
            hintNum++;
        }

        if (hintNum >= hints.length) {
            button.innerText = 'Out of hints!';
        }
    }
</script>

<div>
    <div>{{Audio}}</div>
    <h1 class="pinyin">{{Pinyin}}</h1>
    <p class="pinyin2">{{Pinyin 2}}</p>
    <p class="definition">{{Definition}}</p>
</div>

<hr>

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300" id="diagram">
    <line x1="0" y1="0" x2="300" y2="300" stroke="#DDD" />
    <line x1="300" y1="0" x2="0" y2="300" stroke="#DDD" />
    <line x1="150" y1="0" x2="150" y2="300" stroke="#DDD" />
    <line x1="0" y1="150" x2="300" y2="150" stroke="#DDD" />
</svg>

<div>
    <button id="hint-button" onclick="revealHint()">Show hint</button>
    <p id="hint" class="notes"></p>
    <p id="hint-container" style="display: none;">{{Examples}}</p>
</div>