<template>
    <div class="code-container">
        <div class="copy" v-if="!copied" @click="copyCode">复制</div>
        <div class="copy" v-else><icon-check-circle /> 复制成功！</div>
        <div class="line">
            <span class="line-number" v-for="num in line">{{ num + props.startLine - 1 }}</span>
        </div>
        <highlightjs :code="code" class="code" />
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import hljsVuePlugin from '@highlightjs/vue-plugin'
// import { useThemeStore } from '@/store'
import 'highlight.js/lib/common'
import 'highlight.js/styles/atom-one-light.css'

// const themeStore = useThemeStore()
const props = defineProps({
    code: {
        type: String,
        required: true
    },
    startLine: {
        type: Number,
        default: 1
    }
})
const copied = ref(false)

const highlightjs = hljsVuePlugin.component
const line = computed(() => {
    const lines = props.code.split('\n')
    if (lines[lines.length - 1] == '')
        return lines.length - 1
    return lines.length
})

function copyCode() {
  navigator.clipboard.writeText(props.code).then(() => {
    copied.value = true
    setTimeout(() => {
      copied.value = false
    }, 2000)
  })
}

// function loadThemeCSS(theme) {
//     import(`highlight.js/styles/${theme}.css`) 
// }

// onMounted(() => {
//   loadThemeCSS(themeStore.getTheme())
// })

</script>

<style scoped lang="less">
.code-container {
    position: relative;
    display: flex;
    padding: 0;
    white-space: pre;
    overflow-x: auto;

    .copy {
        position: absolute;
        right: 6px;
        top: 19px;
        background: #eee;
        padding: 4px 10px;
        font-size: 12px;
        border-radius: 4px;
        cursor: pointer;
        display: none;
        user-select: none;
    }

    .code {
        line-height: 1.5em;
        margin-bottom: 10px;
        width: 100%;
        overflow-x: auto;
    }

    .line {
        display: flex;
        flex-direction: column;
        line-height: 1.5em;
        background-color: #f0f0f0;
        margin-bottom: 10px;
        margin-top: 15px;
        padding-top: 15px;

        .line-number {
            user-select: none;
            display: inline-block;
            min-width: 35px;
            color: #888;
            text-align: center;
            font-family: 'Fira Code', 'JetBrains Mono', Menlo, Consolas, 'Courier New', monospace;
        }
    }
}

.code-container:hover {
    .copy {
        display: block;
    }
}

</style>