type ProcessSvgOptions = {
  color: string
  textColor: string
  withText: boolean
}

function findGroupBounds(
  svg: string,
  groupId: string,
): { start: number; end: number } | null {
  const pattern = new RegExp(`<g[^>]*\\bid="${groupId}"[^>]*>`)
  const match = svg.match(pattern)
  if (!match || match.index === undefined) return null

  let depth = 1
  let pos = match.index + match[0].length

  while (depth > 0 && pos < svg.length) {
    const nextOpen = svg.indexOf('<g', pos)
    const nextClose = svg.indexOf('</g>', pos)

    if (nextClose === -1) break

    if (nextOpen !== -1 && nextOpen < nextClose) {
      depth++
      pos = nextOpen + 2
    } else {
      depth--
      if (depth === 0) {
        return { start: match.index, end: nextClose + 4 }
      }
      pos = nextClose + 4
    }
  }
  return null
}

function replaceGroupFills(section: string, color: string): string {
  return section
    .replace(/fill:#[0-9a-fA-F]{3,8}/g, `fill:${color}`)
    .replace(/fill="[^"]*#[0-9a-fA-F]{3,8}[^"]*"/g, `fill="${color}"`)
}

function extractSvgInner(svg: string): string {
  const openMatch = svg.match(/<svg[^>]*>/)
  if (!openMatch || openMatch.index === undefined) return svg
  const innerStart = openMatch.index + openMatch[0].length
  const innerEnd = svg.lastIndexOf('</svg>')
  if (innerEnd === -1) return svg
  return svg.substring(innerStart, innerEnd)
}

export function processSvg(
  rawSvg: string,
  { color, textColor, withText }: ProcessSvgOptions,
): string {
  let inner = extractSvgInner(rawSvg)

  const logoBounds = findGroupBounds(inner, 'logo')
  const textBounds = findGroupBounds(inner, 'text')

  if (logoBounds) {
    const logoSection = inner.substring(logoBounds.start, logoBounds.end)
    const processedLogo = replaceGroupFills(logoSection, color)
    inner = inner.replace(logoSection, processedLogo)
  }

  if (textBounds) {
    // Re-find text bounds after logo replacement may have shifted positions
    const updatedTextBounds = findGroupBounds(inner, 'text')
    if (updatedTextBounds) {
      if (!withText) {
        inner =
          inner.substring(0, updatedTextBounds.start) +
          inner.substring(updatedTextBounds.end)
      } else {
        const textSection = inner.substring(
          updatedTextBounds.start,
          updatedTextBounds.end,
        )
        const processedText = replaceGroupFills(textSection, textColor)
        inner = inner.replace(textSection, processedText)
      }
    }
  }

  return inner
}
