<script lang="ts">
  import { onDestroy, onMount } from 'svelte'
  import {
    createGlyph,
    type JoanGlyphEngine,
    type SpriteName
  } from '@joan/procedural-glyph-engine'
  import { getTheme } from '$lib/stores/theme.svelte'

  let {
    sprite,
    seed = 'oikos',
    size = 96,
    opacity = 1
  }: {
    sprite: string
    seed?: string
    /** Display max-width in px (the engine's internal grid stays 96; CSS
     *  upscales pixelated for larger backdrops). */
    size?: number
    /** Canvas opacity — <1 for a faint watermark backdrop. */
    opacity?: number
  } = $props()

  let canvas = $state<HTMLCanvasElement | null>(null)
  let glyph = $state<JoanGlyphEngine | null>(null)

  function palette(t: 'light' | 'dark') {
    return {
      background: 'transparent',
      off: t === 'dark' ? '#1a1a1a' : '#e6dcc0',
      ink: t === 'dark' ? '#efe5c0' : '#000000',
      accent: t === 'dark' ? '#a89984' : '#3a3a3a',
      glow: 'transparent'
    }
  }

  onMount(() => {
    const g = createGlyph(canvas!, {
      sprite: sprite as SpriteName,
      seed,
      gridSize: 96,
      palette: palette(getTheme()),
      background: false,
      orbBackgroundColor: 'transparent',
      orbBackgroundMode: 'none'
    })
    glyph = g

    const obs = new MutationObserver(() => {
      g.configure({ palette: palette(getTheme()) })
    })
    obs.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class']
    })

    return () => obs.disconnect()
  })

  onDestroy(() => {
    glyph?.destroy()
  })

  $effect(() => {
    if (glyph && sprite) {
      glyph.transitionTo(sprite as SpriteName)
    }
  })
</script>

<canvas
  bind:this={canvas}
  width="96"
  height="96"
  class="glyph"
  style="max-width:{size}px;opacity:{opacity}"
  aria-hidden="true"
></canvas>

<style>
  .glyph {
    display: block;
    width: 100%;
    aspect-ratio: 1;
    margin: 0 auto;
    image-rendering: pixelated;
  }
</style>