<script lang="ts">
  import { onMount } from 'svelte';
  import Prism from 'prismjs';
  
  // Import the languages we need
  import 'prismjs/components/prism-typescript';
  import 'prismjs/components/prism-javascript';
  import 'prismjs/components/prism-json';
  
  // Import the theme CSS
  import 'prismjs/themes/prism-tomorrow.css';

  export let code: string;
  export let language: string = 'typescript';
  export let class_name: string = '';

  let highlightedCode = '';

  onMount(() => {
    try {
      highlightedCode = Prism.highlight(code, Prism.languages[language] || Prism.languages.typescript, language);
    } catch (error) {
      console.warn('Syntax highlighting failed:', error);
      highlightedCode = code;
    }
  });

  $: if (code) {
    try {
      highlightedCode = Prism.highlight(code, Prism.languages[language] || Prism.languages.typescript, language);
    } catch (error) {
      console.warn('Syntax highlighting failed:', error);
      highlightedCode = code;
    }
  }
</script>

<div class="syntax-highlighter {class_name}">
  <pre class="language-{language}"><code class="language-{language}">{@html highlightedCode}</code></pre>
</div>

<style>
  .syntax-highlighter {
    border-radius: 0.75rem;
    overflow-x: auto;
  }
  
  .syntax-highlighter pre {
    margin: 0;
    padding: 1.5rem;
    font-size: 0.875rem;
    line-height: 1.625;
    background-color: #1e293b;
    border: 1px solid #334155;
    font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  }
  
  .syntax-highlighter code {
    color: #e2e8f0;
    font-family: inherit;
  }

  /* Custom syntax highlighting colors */
  :global(.syntax-highlighter .token.comment) {
    color: #64748b;
  }
  
  :global(.syntax-highlighter .token.string) {
    color: #10b981;
  }
  
  :global(.syntax-highlighter .token.number) {
    color: #f59e0b;
  }
  
  :global(.syntax-highlighter .token.keyword) {
    color: #8b5cf6;
  }
  
  :global(.syntax-highlighter .token.function) {
    color: #06b6d4;
  }
  
  :global(.syntax-highlighter .token.operator) {
    color: #e2e8f0;
  }
  
  :global(.syntax-highlighter .token.punctuation) {
    color: #94a3b8;
  }
  
  :global(.syntax-highlighter .token.property) {
    color: #f472b6;
  }
  
  :global(.syntax-highlighter .token.boolean) {
    color: #f59e0b;
  }
  
  :global(.syntax-highlighter .token.class-name) {
    color: #06b6d4;
  }
  
  :global(.syntax-highlighter .token.tag) {
    color: #8b5cf6;
  }
  
  :global(.syntax-highlighter .token.attr-name) {
    color: #f472b6;
  }
  
  :global(.syntax-highlighter .token.attr-value) {
    color: #10b981;
  }
</style>
