<script lang="ts">
    import hljs from 'highlight.js';
    import LanguageSelector from './LanguageSelector.svelte';

    export let code: string | undefined;
    export let language: string | undefined;

    let displayCode: string | undefined;
    let displayLanguage: string | undefined;
    let showAlert = false;

    $: if(code) {
        highlight();
    }

    $: if(language !== displayLanguage) {
        highlight();
    }

    function highlight() {
        if(language) {
            const res = hljs.highlight(code!, {
                language
            });
            if(!res.errorRaised) {
                displayCode = res.value;
            }
        } else {
            const res = hljs.highlightAuto(code!);
            if(!res.errorRaised) {
                displayCode = res.value;
                language = res.language;
            }
        }
        displayLanguage = language;
    }

    async function copy() {
        await navigator.clipboard.writeText(code!);
        showAlert = true;
        setTimeout(() => showAlert = false, 3000);
    }

    async function share() {
        await navigator.clipboard.writeText(window.location.href);
        showAlert = true;
        setTimeout(() => showAlert = false, 3000);
    }
</script>

<div class="flex flex-col m-3 gap-5">
    <div role="alert" class="alert alert-success transition-opacity ease-in-out duration-500 {showAlert ? 'opacity-100' : 'opacity-0'}">
        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
        <span>Copied to your clipboard!</span>
    </div>

    <div class="flex flex-col md:flex-row gap-5">
        <div class="mockup-code flex-1">
            <pre class="p-5"><code>{@html displayCode}</code></pre>
        </div>
        <div class="flex flex-col gap-3">
            <LanguageSelector bind:language />
            <button on:click={copy} class="btn btn-outline btn-primary">Copy</button>
            <button on:click={share} class="btn btn-outline btn-primary">Share link</button>
        </div>
    </div>
</div>

<style>
    :global(.mockup-code pre::before) {
        margin-right: 0 !important;
    }
</style>