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

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

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

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

  let urlInput: HTMLInputElement
  let isUrlInputVisible = false

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

  onMount(() => {
    languages = CodeMirror.modeInfo.map((e) => ({
      text: e.name,
      value: shorten(e.name),
      data: { mime: e.mime, mode: e.mode },
    }))
  })

  export function setLanguage(lang: string) {
    const language = languages.find((e) => e.value === lang)!
    selectedLanguage = language
  }

  function setDefaultLanguage(languages: Language[]) {
    setLanguage('plt')
  }

  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 justify-between p-2 text-sm relative">
  <div>NoPaste</div>
  <div class="flex justify-end gap-2">
    <div>
      <Select
        items={languages}
        bind:value={selectedLanguage}
        class="bg-gray-700 border border-gray-300 p-1"
      />
    </div>
    <div>
      <button on:click={showUrlInput}> Generate Link </button>
    </div>
  </div>

  {#if isUrlInputVisible}
    <div class="absolute w-full h-full bg-gray-700 top-0 left-0 p-2">
      <div class="flex gap-2">
        <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>
    </div>
  {/if}
</div>

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