<script>
  import { marked } from 'marked'
  import DOMPurify from 'dompurify'

  let { src } = $props()
  let html = $state('')
  let loading = $state(true)

  $effect(() => {
    fetch(src)
      .then(r => r.text())
      .then(text => {
        try {
          const raw = marked.parse(text, { async: false })
          html = DOMPurify.sanitize(raw)
        } catch (e) {
          html = '<p class="error">Failed to render markdown.</p>'
        }
        loading = false
      })
      .catch(() => {
        html = '<p class="error">Failed to load markdown.</p>'
        loading = false
      })
  })
</script>

<div class="markdown-renderer">
  {#if loading}
    <p>Loading markdown...</p>
  {:else}
    {@html html}
  {/if}
</div>

<style>
  .markdown-renderer {
    max-width: 800px;
    margin: 24px auto;
    padding: 24px;
    background: var(--retro-panel);
    border: 3px solid var(--retro-border);
    box-shadow: 6px 6px 0px var(--retro-shadow);
    font-size: 1.05rem;
    line-height: 1.6;
  }
  .markdown-renderer :global(h1), .markdown-renderer :global(h2), .markdown-renderer :global(h3) {
    font-family: 'Press Start 2P', cursive;
    color: var(--retro-green);
    margin: 1.2em 0 0.6em;
    font-size: 0.9rem;
  }
  .markdown-renderer :global(pre) {
    background: #1a1a1a;
    color: #e0e0e0;
    padding: 12px;
    overflow-x: auto;
    border: 2px solid var(--retro-border);
    font-family: 'VT323', monospace;
    font-size: 1.1rem;
  }
  .markdown-renderer :global(code) {
    font-family: 'VT323', monospace;
    background: #eee;
    padding: 2px 6px;
  }
  .markdown-renderer :global(pre code) {
    background: transparent;
    padding: 0;
  }
  .markdown-renderer :global(p) { margin: 0.8em 0; }
  .markdown-renderer :global(ul), .markdown-renderer :global(ol) { margin: 0.8em 0 0.8em 1.5em; }
  .markdown-renderer :global(blockquote) {
    border-left: 4px solid var(--retro-green);
    padding-left: 12px;
    color: #444;
    margin: 0.8em 0;
  }
</style>
