///|
/// Implementation of inlineStyles plugin matching upstream SVGO exactly.

///|
fn includes_attr_selector_in_complex(
  selector : @css.ComplexSelector,
  attr_name : String,
  val : String?,
  traversed : Bool,
) -> Bool {
  fn check_compound(compound : @css.CompoundSelector) -> Bool {
    for s in compound.simples {
      match s {
        Attribute(a, matcher) =>
          if a == attr_name {
            match val {
              None => return true
              Some(v) =>
                match matcher {
                  Equals(target) => if target == v { return true }
                  _ => ()
                }
            }
          }
        Class(cls) =>
          if attr_name == "class" {
            match val {
              None => return true
              Some(v) => if cls == v { return true }
            }
          }
        Id(id) =>
          if attr_name == "id" {
            match val {
              None => return true
              Some(v) => if id == v { return true }
            }
          }
        PseudoClass(_, Some(arg)) => {
          let inner_list = @css.parse_selector_list(arg)
          for sel in inner_list {
            if includes_attr_selector_in_complex(sel, attr_name, val, traversed) {
              return true
            }
          }
        }
        _ => ()
      }
    }
    false
  }

  if traversed {
    if check_compound(selector.head) && selector.tail.length() > 0 {
      return true
    }
    for i = 0; i < selector.tail.length() - 1; i = i + 1 {
      if check_compound(selector.tail[i].1) {
        return true
      }
    }
    false
  } else {
    if check_compound(selector.head) {
      return true
    }
    for pair in selector.tail {
      if check_compound(pair.1) {
        return true
      }
    }
    false
  }
}

///|
fn strip_unsupported_pseudos(
  selector : @css.ComplexSelector,
  use_pseudos : Array[String],
) -> (@css.ComplexSelector, Bool) {
  fn filter_compound(
    compound : @css.CompoundSelector,
  ) -> (@css.CompoundSelector, Bool) {
    let new_simples : Array[@css.SimpleSelector] = []
    for s in compound.simples {
      match s {
        PseudoClass(name, _) =>
          if name == "not" ||
            name == "is" ||
            name == "where" ||
            name == "has" ||
            name == "first-child" ||
            name == "last-child" ||
            name == "only-child" ||
            name == "first-of-type" ||
            name == "last-of-type" ||
            name == "only-of-type" ||
            name == "nth-child" ||
            name == "nth-last-child" ||
            name == "nth-of-type" ||
            name == "nth-last-of-type" ||
            name == "root" ||
            name == "empty" {
            new_simples.push(s)
          } else {
            let colon_name = ":" + name
            if use_pseudos.contains(name) || use_pseudos.contains(colon_name) {
              ()
            } else {
              return ({ simples: [], }, false)
            }
          }
        PseudoElement(name) => {
          let colon_name = "::" + name
          if use_pseudos.contains(name) || use_pseudos.contains(colon_name) {
            ()
          } else {
            return ({ simples: [], }, false)
          }
        }
        _ => new_simples.push(s)
      }
    }
    ({ simples: new_simples, }, true)
  }

  let (new_head, ok1) = filter_compound(selector.head)
  if !ok1 {
    return (selector, false)
  }
  let new_tail : Array[(@css.Combinator, @css.CompoundSelector)] = []
  for pair in selector.tail {
    let (c, ok) = filter_compound(pair.1)
    if !ok {
      return (selector, false)
    }
    new_tail.push((pair.0, c))
  }
  ({ head: new_head, tail: new_tail, raw: selector.raw, }, true)
}

///|
priv struct SelectorEntry {
  raw_selector : @css.ComplexSelector
  matched_selector : @css.ComplexSelector
  declarations : Array[@css.Declaration]
  parent_items : Array[@css.StyleSheetItem]
  item_idx : Int32
  selector_idx : Int32
  order : Int32
  specificity : @css.Specificity
  mut matched_indices : Array[Int32]
}

///|
/// Normalize a media query / at-rule prelude string for comparison against
/// the `useMqs` list. svgo compares against csstree.generate output, which
/// drops whitespace around `:`, `(`, `)`, `,` and collapses runs of spaces.
fn normalize_mq(s : String) -> String {
  let chars = s.code_units()
  let len = chars.length()
  let sb = StringBuilder()
  let mut i = 0
  while i < len {
    let c = chars[i]
    if c == 32 || c == 9 || c == 10 || c == 13 {
      // whitespace: skip if adjacent to punctuation, else emit one space
      let mut j = i
      while j < len &&
            (
              chars[j] == 32 ||
              chars[j] == 9 ||
              chars[j] == 10 ||
              chars[j] == 13
            ) {
        j += 1
      }
      let prev_is_punct = i > 0 &&
        (
          chars[i - 1] == 58 ||
          chars[i - 1] == 40 ||
          chars[i - 1] == 41 ||
          chars[i - 1] == 44 ||
          chars[i - 1] == 59
        )
      let next_is_punct = j < len &&
        (
          chars[j] == 58 ||
          chars[j] == 41 ||
          chars[j] == 44 ||
          chars[j] == 59 ||
          chars[j] == 40
        )
      if !prev_is_punct && !next_is_punct {
        sb.write_char(' ')
      }
      i = j
    } else {
      match c.to_char() {
        Some(ch) => sb.write_char(ch)
        None => ()
      }
      i += 1
    }
  }
  sb.to_string().trim().to_owned()
}

///|
fn collect_style_text(elem : @xml.Element) -> String {
  let sb = StringBuilder()
  for child in elem.children {
    match child {
      Text(t) => sb.write_string(t)
      CData(cd) => sb.write_string(cd)
      _ => ()
    }
  }
  sb.to_string()
}

///|
fn run_inline_styles(doc : @xml.Document, ctx : Context) -> Bool {
  let only_matched_once = ctx.param_bool("onlyMatchedOnce", true)
  let remove_matched_selectors = ctx.param_bool("removeMatchedSelectors", true)
  let use_mqs_param = ctx.param_strings("useMqs")
  let use_mqs = if use_mqs_param.is_empty() {
    ["", "screen"]
  } else {
    use_mqs_param
  }
  let use_pseudos_param = ctx.param_strings("usePseudos")
  let use_pseudos = if use_pseudos_param.is_empty() {
    [""]
  } else {
    use_pseudos_param
  }

  let root = match doc.root() {
    Some(r) => r
    None => return false
  }

  // 1. Collect all style elements not inside foreignObject
  let style_elements : Array[@xml.Element] = []
  fn find_styles(elem : @xml.Element, inside_fo : Bool) {
    let is_fo = inside_fo || elem.name == "foreignObject"
    if !is_fo && elem.name == "style" {
      style_elements.push(elem)
    }
    for child in elem.children {
      match child {
        Element(e) => find_styles(e, is_fo)
        _ => ()
      }
    }
  }
  find_styles(root, false)
  if style_elements.is_empty() {
    return false
  }

  // 2. Parse stylesheets and collect selectors
  let parsed_sheets : Array[(@xml.Element, @css.StyleSheet)] = []
  let all_selectors : Array[SelectorEntry] = []
  let mut order_counter = 0

  for elem in style_elements {
    // svgo skips