<template>
    <div :class="bem()">
        <pre
            v-if="loaded"
            class="px-code-sample"
            :class="lang"
        ><code v-html="highlightedCode"></code></pre>
        <PxCopyText
            v-if="showCopyButton"
            :class="bem('copy-button')"
            :text="code"
            :showText="false"
        ></PxCopyText>
    </div>
</template>

<script>
// Note: for Nuxt projects, the following nuxt.config.js setting may be necessary:
// vite: {
//     optimizeDeps: {
//         include: ['highlight.js'],
//     }
// }

import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import xml from 'highlight.js/lib/languages/xml';
import css from 'highlight.js/lib/languages/css';
import PxCopyText from './PxCopyText.vue';

export default {
    name: 'px-code-sample',
    components: { PxCopyText },
    // mixins: [ Mixin ],
    props: {
        code: { type: String, default: '' },
        lang: { type: String, default: null },
        showCopyButton: { type: Boolean, default: true },
    },
    data() {
        return { loaded: false };
    },
    computed: {
        highlightedCode() {
            if (this.loaded) {
                // remove trailing newline and spaces

                const code = this.code.replace(/^\s+$/, '').replace(/^[\s\uFEFF\xA0]+/, '');

                if (code) {
                    if (this.lang) {
                        return hljs.highlight(code, { language: this.lang }).value;
                    } else {
                        return hljs.highlightAuto(code).value;
                    }
                }
            }
            return '';
        },
    },
    // watch: {},
    mounted() {
        hljs.registerLanguage('javascript', javascript);
        hljs.registerLanguage('xml', xml);
        hljs.registerLanguage('css', css);

        setTimeout(() => {
            this.loaded = true;
        });
    },
    // methods: {},
};
</script>

<style lang="scss">
@use '../styles/px.scss' as *;
@use '@thinkpixellab-public/px-styles/src/modules/highlightjs.scss' as *;
.px-code-sample {
    position: relative;
    padding: 1em;
    border-radius: 0.5em;

    @include highlightjs();
    pre,
    code {
        padding: 0;
        margin: 0;
    }

    &__copy-button {
        position: absolute;
        top: 1em;
        right: 1em;
        color: white;
    }
}
</style>
