<script lang="ts">
  import { onMount } from 'svelte';
  import Monaco from './Monaco.svelte';
  let content_script = $state('');
  let default_value = $state(`// Do not put untrusted content here!
// See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests and https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest for a tutorial on how to handle things.
// Content saves on every keystroke due to laziness.
// Reload (disable & re-enable) extension or restart browser to apply changes.
`);
  let mounted = $state(false);
  onMount(async () => {
    const s = (await browser.storage.local.get('sc')).sc;
    default_value = s && `${s}`.length ? `${s}` : default_value;
    content_script = default_value ?? '';
    setTimeout(() => {
      mounted = true;
      setTimeout(() => {
        content_script = default_value;
      }, 0);
    }, 0);
  });
  $effect(() => {
    (async (cs: string) => {
      if (mounted) {
        await browser.storage.local.set({ sc: cs });
        if (browser.runtime.lastError) {
          console.warn('Last Error is ', browser.runtime.lastError.message);
          browser.runtime.lastError = undefined;
        }
      }
    })(content_script);
  });
</script>

{#if mounted}
  <Monaco
    defaultValue={default_value}
    bind:value={content_script}
  />
{:else}
  Getting Storage
{/if}
