<script lang="ts">
  import { Marked, Renderer } from "@ts-stack/markdown";

  interface Props {
    content?: string;
    basePath?: string;
  }

  let { content = "", basePath = "" }: Props = $props();

  const renderer = new Renderer();
  
  // Custom image renderer to proxy through /assets/
  renderer.image = (href, title, text) => {
    let src = href;
    if (href && !href.startsWith('http')) {
      // Ensure basePath starts with / if provided
      const normalizedBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;
      // If href starts with /, it's relative to root. Otherwise, relative to basePath.
      if (!href.startsWith('/')) {
        src = `${normalizedBasePath}/${href}`.replace(/\/+/g, '/');
      }
      src = `/assets${src}`;

      // Generate srcset for optimized images
      const widths = [400, 800, 1200, 1600, 2000];
      const srcset = widths
        .map(w => `${src}?w=${w} ${w}w`)
        .join(', ');
      const sizes = "(max-width: 1024px) 100vw, 1024px";

      return `<img src="${src}" srcset="${srcset}" sizes="${sizes}" alt="${text}" title="${title || ''}" loading="lazy" />`;
    }
    return `<img src="${src}" alt="${text}" title="${title || ''}" loading="lazy" />`;
  };

  let html = $derived(
    Marked.parse(content || "__nothing to see here__", {
      renderer,
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: false,
      smartLists: true,
      smartypants: false,
    })
  );
</script>

<div class="markdown">
  {@html html}
</div>

<style global>
  .markdown {
    color: white;
    text-align: left;

    display: flex;
    flex-direction: column;
  }
  .markdown h1 {
    font-size: 2rem;
  }
  .markdown h2 {
    font-size: 1.75rem;
  }
  .markdown h3 {
    font-size: 1.5rem;
  }
  .markdown h4 {
    font-size: 1.25rem;
  }

  .markdown * {
    margin-bottom: 1rem;
  }

  .markdown img {
    max-height: 90vh;
    display: block;
    margin: 0 auto;
  }

  .markdown table,
  .markdown tr,
  .markdown th,
  .markdown td {
    border-collapse: collapse;
    border: 1px solid;

    padding: 0.3rem 1rem;
  }

  .markdown th {
    font-size: 1.2rem;
  }
</style>
