// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

///|
/// 23 tree construction insertion modes (WHATWG 13.2.6)
enum InsertionMode {
  Initial
  BeforeHtml
  BeforeHead
  InHead
  InHeadNoscript
  AfterHead
  InBody
  Text
  InTable
  InTableText
  InCaption
  InColumnGroup
  InTableBody
  InRow
  InCell
  InSelect
  InSelectInTable
  InTemplate
  AfterBody
  InFrameset
  AfterFrameset
  AfterAfterBody
  AfterAfterFrameset
}

///|
/// Entry in the stack of open elements
struct StackEntry {
  node_id : Int
  tag_name : String
  ns : Namespace
}

///|
/// Marker or Element entry in the active formatting elements list
enum FormattingEntry {
  Marker
  Element(
    node_id~ : Int,
    tag_name~ : String,
    attributes~ : Array[(String, String)]
  )
}

///|
/// The HTML tree builder (WHATWG 13.2.6)
pub struct TreeBuilder {
  tokenizer : Tokenizer
  document : Document
  // Stack of open elements (WHATWG 13.2.4.2)
  open_elements : Array[StackEntry]
  // Active formatting elements (WHATWG 13.2.4.3)
  active_formatting : Array[FormattingEntry]
  // Current insertion mode
  mut mode : InsertionMode
  // Original insertion mode (for "text" and "in table text" modes)
  mut original_mode : InsertionMode
  // Template insertion modes stack
  template_modes : Array[InsertionMode]
  // Head element pointer
  mut head_element : Int
  // Form element pointer
  mut form_element : Int
  // Scripting flag (for noscript handling)
  scripting : Bool
  // Frameset-ok flag
  mut frameset_ok : Bool
  // Foster parenting mode
  mut foster_parenting : Bool
  // Pending table character tokens
  pending_table_chars : Array[Char]
  // Skip newline flag after 
,