const symbols = /[\r\n%#()<>?[\\\]^`{|}]/g

export function addNameSpaceXML(data: string): string {
  if (data.indexOf(`http://www.w3.org/2000/svg`) < 0) {
    data = data.replace(/<svg/g, `<svg xmlns='http://www.w3.org/2000/svg'`)
  }
  return data
}

/**
 * Adds a mask element to an SVG string. The mask is inserted immediately after the opening <svg> tag
 * and wraps the existing SVG content, ending before the closing </svg> tag.
 *
 * @param {string} svg - The SVG string to which the mask will be added. Must contain valid <svg> tags.
 * @param {string} maskId - The ID to assign to the <mask> element.
 * @returns {string} - The modified SVG string with the mask element added.
 */
export function addMask(svg: string, maskId: string): string {
  // Insert <mask id="..."> right after <svg ...>
  const openingSvgTagMatch = svg.match(/<svg[^>]*>/)
  if (!openingSvgTagMatch) return svg

  const openingSvgTag = openingSvgTagMatch[0]
  const maskOpen = `<mask id="${maskId}">`
  const maskClose = `</mask>`

  // Find positions
  const start = svg.indexOf(openingSvgTag) + openingSvgTag.length
  const end = svg.lastIndexOf('</svg>')

  // Insert mask tags
  return (
    svg.slice(0, start) +
    maskOpen +
    svg.slice(start, end) +
    maskClose +
    svg.slice(end)
  )
}

export function encodeSVG(data: string): string {
  data = data.replace(/"/g, `'`)
  data = data.replace(/>\s{1,}</g, `><`)
  data = data.replace(/\s{2,}/g, ` `)
  return data.replace(symbols, encodeURIComponent)
}
