<script lang="ts">
  import { onMount, tick } from 'svelte'
  import { shorten } from '$lib/utils'
  import type { Editor } from 'codemirror'
  import { shareUrl, selectedLang } from '../store'
  import ComboBox from './ComboBox.svelte'
  import Icon from '@iconify/svelte'

  type Language = {
    text: string
    value: string
    data: { mime: string; mode: string }
  }

  export let editor: Editor | null = null
  export let updateShareUrl: () => Promise<void>

  let languages: Language[] = []
  let selectedLanguage: Language | null = null
  let textWrap = false

  let urlInput: HTMLInputElement
  let isUrlInputVisible = false

  $: {
    if (editor) {
      const language = selectedLanguage?.data ?? { mime: null, mode: null }
      // @ts-ignore
      editor.setOption('mode', language.mime)
      CodeMirror.autoLoadMode(editor, language.mode)
      $selectedLang = selectedLanguage?.value ?? null

      // Line wrapping
      editor.setOption('lineWrapping', textWrap)
    }
  }

  onMount(() => {
    languages = CodeMirror.modeInfo
      .map((e: any) => ({
        text: e.name,
        value: shorten(e.name),
        data: { mime: e.mime, mode: e.mode },
      }))
      .filter((l: any) => l.value !== 'gflm') // Remove github flavored markdown, redundant with markdown
      console.log(languages)
  })

  export function setLanguage(lang: string) {
    if (lang === 'mrwn' || lang === 'gflm') {
      // back compatiblity with old links
      lang = 'md'
    }
    const language = languages.find((e) => e.value === lang)!
    selectedLanguage = language
    // Automatic text wrap for plain text or markdown
    if (lang === 'plt' || lang === 'mrwn' || !lang) {
      textWrap = true
    }
  }

  async function showUrlInput() {
    // Make sure the url is up to date
    await updateShareUrl()
    isUrlInputVisible = true
    await tick()
    urlInput.select()
  }

  async function copyUrl() {
    urlInput.select()
    await navigator.clipboard.writeText(urlInput.value)
    closeUrlInput()
  }

  function closeUrlInput() {
    isUrlInputVisible = false
  }
</script>

<div
  class="flex flex-wrap justify-between items-center px-3 py-1 text-sm relative z-10 shadow-md gap-2"
>
  <div class="flex items-center">
    <h1 class="text-xl">Paste</h1>
    <span class="ml-8 text-xs">
      <a
        href="https://paste.scambier.xyz/?l=mrwn#G14EICwPbMc0BJ69xNPoItLoErDRMwMj3+vxE5RxArxajeByk+b0b1Tm2h/5ugGgK6S83AqUCi09HeYmDs+vvzQc0QDZe7v7U2rHnFe6CTWSm2AArNua4tqtXVIEFVQuqG+is15etOm1OZOPPCH4xDX1iDNF2bQcN9ugum0Icnwj51n0nlvNacn/N3OOctSGrQbLoNzG8n5bSoJQXOx+PsxV+MeUl+rkKNPIAXT9c8LoOY/772FiFkLv/5w8rvtCBc38VEE5lzmGFcZ0QtqlzBhvWLV5WPhRkROqeoKoDCtH03/fQVI5Y8HfLkq2/Nuidd1GQTKgmPJQVWbZ4cAiqUdOJG6j6pvu48qWjqamYG3nFPHcdYLHYCRV877U2mBgSHTbLWv6eu/DEA88SE5XEIqiQFyDVS2HLN7jJSloLHQJ+jOE86zb9jrkQ9tXAwkAoovCcnlrW5T/EU4L7imRsDAkZdEySO/ri/NBuHPMpSFnqGItLlPd98/SZSmySbImOLfv4WGbdCxw9TYykGsk56aQaVSa/DB2t5HfD6x28lJVlMm3Hjnkwyx95PxNGH0teCAk6CqtbBYlC3LjhY0IEpJ0WWZWY6MlJB+jEW7lAN3DSJD0QFz2FZOOV/HwA9LbFBU="
        target="_blank"
      >
        About</a
      >
      <a class="ml-4" href="https://git.scambier.xyz/scambier/paste" target="_blank">Source</a>
    </span>
  </div>

  {#if isUrlInputVisible}
    <div class="flex gap-2 grow">
      <input
        bind:this={urlInput}
        type="text"
        class="border border-gray-300 bg-transparent p-1 grow"
        value={$shareUrl}
      />
      <button on:click={copyUrl}>Copy</button>
      <button on:click={closeUrlInput}>Close</button>
    </div>
  {:else}
    <div class="flex justify-end gap-2">
      <div>
        <ComboBox
          items={languages}
          bind:value={selectedLanguage}
          class="bg-gray-700 border border-gray-300 p-1"
        />
      </div>
      <button title="Toggle text wrap" on:click={() => (textWrap = !textWrap)}>
        {#if textWrap}
          <Icon class="text-xl" icon="fluent:text-wrap-24-filled" />
        {:else}
          <Icon class="text-xl" icon="fluent:text-wrap-off-24-filled" />
        {/if}
      </button>
      <div>
        <button on:click={showUrlInput}> Generate Link </button>
      </div>
    </div>
  {/if}
</div>

<style lang="scss">
  button {
    @apply text-sm border border-gray-300 p-1 hover:bg-gray-600/50;
  }
</style>
