///|
/// High-level managed app that owns the parent dispatcher and child webview
/// process lifecycle.
pub struct Window {
  label : String
  title : String
  width : Int?
  height : Int?
  size_hint : SizeHint
  debug : Int?
  devtools : Bool?
  child_arg : String
  mut options : WindowOptions
  mut traffic_light_position : (Int, Int)?
  position : (Int, Int)?
  hidden : Bool?
  focused : Bool?
  enable_window_controls_plugin : Bool
  mut url : String
  mut html : String
  pending_custom_protocols : Array[(String, String)]
  mut runtime_window_id : Int
  plugins : Array[Plugin]
}

///|
/// Creates a managed app. The library handles the parent dispatcher and child
/// webview process automatically.
///
/// All window options are optional; omitting one leaves it to the native
/// platform (see [`WindowOptions`]).
#alias(new, deprecated="Use `Window()` instead")
pub fn Window::Window(
  label? : String = "",
  title? : String = "MoonBit WebView",
  url? : String = "",
  width? : Int,
  height? : Int,
  size_hint? : SizeHint = None,
  debug? : Int,
  devtools? : Bool,
  child_arg? : String = "--moonbit-webview-child",
  decorations? : Bool,
  resizable? : Bool,
  closeable? : Bool,
  minimizable? : Bool,
  maximizable? : Bool,
  always_on_top? : Bool,
  always_on_bottom? : Bool,
  transparent? : Bool,
  shadow? : Bool,
  skip_taskbar? : Bool,
  visible_on_all_workspaces? : Bool,
  title_bar_style? : TitleBarStyle,
  title_bar_overlay? : Bool,
  hidden_title? : Bool,
  frameless? : Bool = false,
  traffic_light_position? : (Int, Int),
  position? : (Int, Int),
  hidden? : Bool,
  focused? : Bool,
  enable_window_controls_plugin? : Bool = true,
) -> Window {
  {
    label,
    title,
    url,
    width,
    height,
    debug,
    devtools,
    child_arg,
    options: {
      decorations: if frameless {
        Some(false)
      } else {
        decorations
      },
      resizable,
      closeable,
      minimizable,
      maximizable,
      always_on_top,
      always_on_bottom,
      transparent,
      shadow,
      skip_taskbar,
      visible_on_all_workspaces,
      title_bar_style,
      title_bar_overlay,
      hidden_title,
    },
    traffic_light_position,
    position,
    hidden,
    focused,
    enable_window_controls_plugin,
    html: "",
    pending_custom_protocols: [],
    runtime_window_id: -1,
    plugins: [],
    size_hint,
  }
}

///|
/// Returns the stable label used for cross-window addressing.
/// Falls back to the `title` when no explicit label was provided.
pub fn Window::label(self : Window) -> String {
  if self.label.is_empty() {
    self.title
  } else {
    self.label
  }
}

///|
/// Applies the native window style described by `options`.
///
/// `options` is a *patch*: only the fields set to `Some(_)` are applied, and an
/// all-unset patch performs no native work. Unset fields keep whatever value
/// the window already has, so successive calls are incremental rather than
/// wholesale resets.
pub fn Window::set_window_customization(
  self : Window,
  options : WindowOptions,
) -> Unit {
  // Remember the merge so options set by earlier calls are not forgotten when
  // the child process later re-creates this window, but only push the incoming
  // patch to the native side — applying the whole merged set would re-issue
  // native calls for properties that did not change.
  self.options = self.options.merge(options)
  if self.runtime_window_id > 0 {
    ignore(wm_apply_window_options(self.runtime_window_id, options))
  }
}

///|
/// Set macOS traffic-light buttons position.
pub fn Window::set_traffic_light_position(
  self : Window,
  x : Int,
  y : Int,
) -> Unit {
  self.traffic_light_position = Some((x, y))
  if self.runtime_window_id > 0 {
    ignore(
      @window_manager.wm_set_traffic_light_position(
        self.runtime_window_id,
        x,
        y,
      ),
    )
  }
}

///|
/// Installs a managed plugin into the app.
pub fn Window::install(self : Window, plugin : Plugin) -> Unit {
  self.plugins.push(plugin)
}

///|
/// Sets inline HTML content for the child webview.
pub fn Window::set_html(self : Window, html : String) -> Unit {
  self.html = html
  if self.runtime_window_id > 0 {
    ignore(
      @window_manager.wm_set_html(
        self.runtime_window_id,
        @encoding/utf8.encode(html),
      ),
    )
  }
}

///|
pub fn Window::navigate(self : Window, url : String) -> Unit {
  self.url = url
  if self.runtime_window_id > 0 {
    ignore(
      @window_manager.wm_navigate(
        self.runtime_window_id,
        @encoding/utf8.encode(url),
      ),
    )
  }
}

///|
/// Register a custom scheme for the child webview before it navigates.
pub fn Window::set_custom_protocol(
  self : Window,
  scheme : String,
  root_dir : String,
) -> Unit {
  self.pending_custom_protocols.push((scheme, root_dir))
}

///|
/// Runs the managed app end-to-end.
pub async fn Window::run(self : Window) -> Unit {
  let args = @env.args()
  if args.length() > 1 && args[1] == self.child_arg {
    guard WindowManager::connect_child_process() == 0 else {
      abort("ManagedApp::run: connect child process failed")
    }
    self.run_child_async()
    return
  }
  let wm = WindowManager::init()
  guard args.length() > 0 else { abort("ManagedApp::run: missing argv[0]") }
  let child_pid = wm.spawn_process(args[0], self.child_arg)
  guard child_pid > 0 else {
    abort("ManagedApp::run: spawn webview process failed")
  }
  self.build_router().serve(wm, child_pid)
}

///|
/// Encodes a unique child-process marker used to carry a globally-unique
/// window-id `base` and a stable `label` across a re-exec`ed child process.
pub fn child_arg_for(base : Int, label : String) -> String {
  "--lepus-child:" + base.to_string() + ":" + label
}

///|
/// Detects whether the current process was spawned as a Lepus multi-window
/// child.
///
/// Returns `(window_id_base, label)` when argv carries a
/// `--lepus-child::