---
import { parse } from 'node-html-parser';

// Thank you David Warrington! 
// https://ellodave.dev/blog/article/using-svgs-as-astro-components-and-inline-css/

export interface Props {
  icon: string,
  class: string,
}

function getSVG(name: string) {
  const filepath = `/src/svg/${name}.svg`;
  const files = import.meta.glob<string>('/src/svg/**/*.svg', {
    as: 'raw', eager: true,
  });

  if (!(filepath in files)) {
    throw new Error(`${filepath} not found`);
  }

  const root = parse(files[filepath]);

  const svg = root.querySelector('svg');
  // @ts-ignore
  const { attributes, innerHTML } = svg;

  return {
    attributes,
    innerHTML,
  };
}

const { icon, ...attributes } = Astro.props;
const { attributes: baseAttributes, innerHTML } = getSVG(icon);

const svgAttributes = { ...baseAttributes, ...attributes };
---

<svg
  {...svgAttributes}
  set:html={innerHTML}
></svg>