<script lang="ts">
  import { onMount } from 'svelte'
  import * as brotli from '$lib/brotli'
  import * as lzma from '$lib/lzma'
  import { unified } from 'unified'
  import remarkParse from 'remark-parse'
  import remarkRehype from 'remark-rehype'
  import remarkGfm from 'remark-gfm'
  import rehypeHighlight from 'rehype-highlight'
  import rehypeStringify from 'rehype-stringify'
  import hljs from 'highlight.js'
  import 'highlight.js/styles/nord.min.css'

  let decompressed: string
  let isMarkdown = false
  let isPlainText = false

  onMount(async () => {
    let lang = new URLSearchParams(window.location.search).get('l')
    lang = lang === 'mrwn' || lang === 'gflm' ? 'md' : lang // back compatiblity with old links

    // extract the part in the url after the hash
    const hash = window.location.hash.slice(1)
    if (hash) {
      // decompress the data
      if (hash.startsWith('XQAAA')) {
        decompressed = await lzma.decompress(hash)
      } else {
        decompressed = await brotli.decompress(hash)
      }

      // Markdown
      if (lang === 'md' || lang === 'gflm') {
        const html = await unified()
          .use(remarkParse)
          .use(remarkGfm)
          .use(remarkRehype)
          .use(rehypeHighlight)
          .use(rehypeStringify)
          .process(decompressed)
        isMarkdown = true
        decompressed = html.toString()
      }
      // Plain text
      else if (lang === 'plt' || !lang) {
        isPlainText = true
      }
      // Code
      else {
        decompressed = hljs.highlight(lang, decompressed).value
      }
    } else {
      // Redirect to editor page
      window.location.href = '/editor'
    }
  })
</script>

<div>
  <div class="prose dark:prose-invert lg:py-12 p-[0.5em] md:max-w-3xl md:mx-auto lg:max-w-4xl">
    {#if isMarkdown}
      {@html decompressed}
    {:else if isPlainText}
      <div class="whitespace-pre-line">
        {decompressed}
      </div>
    {:else}
      <pre><code>{@html decompressed}</code></pre>
    {/if}
  </div>
</div>

<style lang="scss">
  :global(pre code.hljs) {
    background-color: transparent;
    padding: 0;
  }
</style>
