const SVG_NS = 'http://www.w3.org/2000/svg'

type SvgAttributeValue = string | number | boolean

export interface SvgNodeConfig {
  tag: 'circle' | 'line' | 'path' | 'rect' | 'svg'
  attrs: Record<string, SvgAttributeValue>
  children: SvgNodeConfig[]
}

function applySvgAttributes(element: SVGElement, attrs: Record<string, SvgAttributeValue>): void {
  for (const [name, value] of Object.entries(attrs)) {
    element.setAttribute(name, String(value))
  }
}

export function createSvgNode(config: SvgNodeConfig): SVGElement {
  const element = document.createElementNS(SVG_NS, config.tag)
  applySvgAttributes(element, config.attrs)

  for (const child of config.children) {
    element.appendChild(createSvgNode(child))
  }

  return element
}

export function createSvgIcon(
  attrs: Record<string, SvgAttributeValue>,
  children: SvgNodeConfig[]
): SVGSVGElement {
  const svg = createSvgNode({ tag: 'svg', attrs: { ...attrs, xmlns: SVG_NS }, children })
  return svg as SVGSVGElement
}

export function replaceWithSvgIcon(
  element: Element,
  attrs: Record<string, SvgAttributeValue>,
  children: SvgNodeConfig[]
): void {
  element.replaceChildren(createSvgIcon(attrs, children))
}
