///|
/// Appearance roles have both variants; they do not change model color families.
pub(all) struct NodeAppearance {
  dark : @theme.FamilyColors
  light : @theme.FamilyColors
}

///|
pub(all) struct StatusScheme {
  active : NodeAppearance
  selected : NodeAppearance
  warning : NodeAppearance
  failed : NodeAppearance
}

///|
/// Status roles from existing theme families, with label inks shaded for
/// contrast on the role fill over both the background and the box mask.
pub fn StatusScheme::from_theme(theme : @theme.Theme) -> StatusScheme {
  fn role(family : @theme.Family) -> NodeAppearance {
    fn colors(p : @theme.Palette) -> @theme.FamilyColors {
      let c = p.family(family)
      {
        ..c,
        ink: @theme.text_shade(c.ink, [
          @theme.over(c.fill, p.bg),
          @theme.over(c.fill, p.mask),
        ]),
      }
    }
    { dark: colors(theme.dark), light: colors(theme.light), }
  }
  {
    active: role(Backend),
    selected: role(Frontend),
    warning: role(Cloud),
    failed: role(Security),
  }
}

///|
pub fn StatusScheme::role(
  self : StatusScheme,
  status : @projection.Status,
) -> NodeAppearance {
  match status {
    Active => self.active
    Selected => self.selected
    Warning => self.warning
    Failed => self.failed
  }
}

///|
/// A dark and a light color.
#derive(Eq, Debug)
pub(all) struct ColorPair {
  dark : @theme.Color
  light : @theme.Color
}

///|
pub extend ColorPair with Eq::{equal, not_equal}

///|
pub extend ColorPair with @debug.Debug::{to_repr}

///|
/// Partial colors. An absent property keeps the renderer's baseline.
#derive(Eq, Debug)
pub(all) struct Colors {
  fill : ColorPair?
  stroke : ColorPair?
  ink : ColorPair?
}

///|
pub extend Colors with Eq::{equal, not_equal}

///|
pub extend Colors with @debug.Debug::{to_repr}

///|
pub fn Colors::none() -> Colors {
  { fill: None, stroke: None, ink: None, }
}

///|
pub fn Colors::is_empty(self : Colors) -> Bool {
  self.fill is None && self.stroke is None && self.ink is None
}

///|
fn[T] prefer(earlier : T?, later : T?) -> T? {
  match later {
    Some(_) => later
    None => earlier
  }
}

///|
/// Later properties win.
pub fn Colors::merge(self : Colors, other : Colors) -> Colors {
  {
    fill: prefer(self.fill, other.fill),
    stroke: prefer(self.stroke, other.stroke),
    ink: prefer(self.ink, other.ink),
  }
}

///|
/// The immutable context of themed rendering: the theme, fixed or adaptive
/// mode and the status scheme.
pub struct RenderContext {
  theme : @theme.Theme
  mode : Mode
  status : StatusScheme
}

///|
pub fn RenderContext::new(
  theme~ : @theme.Theme = @theme.Theme::classic(),
  mode~ : Mode = Adaptive,
  status? : StatusScheme,
) -> RenderContext {
  {
    theme,
    mode,
    status: status.unwrap_or_else(() => StatusScheme::from_theme(theme)),
  }
}

///|
/// One visual after theme resolution.
pub struct ResolvedVisual {
  visual : @projection.Visual
  /// The model identifier that the family painter uses, if any.
  id : String?
  /// The semantic family of the element's baseline colors, if it has one.
  family : @theme.Family?
  /// The renderer's baseline colors for the element in both variants.
  baseline : NodeAppearance
  /// The colors that overrides and render policies set, in both variants.
  colors : Colors
  /// The baseline with `colors` applied.
  composed : NodeAppearance
}

///|
/// A theme-aware partial override. A render policy sees the render context,
/// the element's baseline and its semantic appearance; consumer state is
/// captured by the policy function itself.
pub struct RenderPolicy {
  priv apply : (RenderContext, ResolvedVisual) -> Colors?
}

///|
pub fn RenderPolicy::new(
  apply : (RenderContext, ResolvedVisual) -> Colors?,
) -> RenderPolicy {
  { apply, }
}

///|
/// A logical view with resolved appearance. Custom renderers can paint it.
pub struct ResolvedScene {
  view : @projection.View
  context : RenderContext
  visuals : ReadOnlyArray[ResolvedVisual]
  /// Contrast findings for the final composed appearance.
  findings : ReadOnlyArray[@diagrams.Diagnostic]
}

///|
pub fn ResolvedScene::visual(
  self : ResolvedScene,
  key : String,
) -> ResolvedVisual? {
  for visual in self.visuals {
    if visual.visual.key == key {
      return Some(visual)
    }
  }
  None
}

///|
fn baseline_family(
  visual : @projection.Visual,
  layout : @render.Diagram,
) -> @theme.Family? {
  let shape = visual.shape
  match visual.element {
    Flowchart(Node(node)) =>
      Some(@support.shape_family(shape.unwrap_or(node.shape)))
    Swimlane(Node(node)) =>
      Some(@support.shape_family(shape.unwrap_or(node.shape)))
    Bpmn(Node(node)) => Some(@support.bpmn_family(node.kind))
    Architecture(Service(_)) => Some(Backend)
    Architecture(Group(_)) => Some(External)
    Sequence(Participant(participant)) => {
      // The painter cycles plain participants through families in the model
      // order of the diagram that it lays out, not in containment order.
      let mut kind = participant.render_kind()
      let mut cycle = 0
      if layout is Sequence(sequence) {
        for p in sequence.participants {
          if p.id == participant.id {
            kind = p.render_kind()
            break
          }
          if p.render_kind() == Participant {
            cycle += 1
          }
        }
      }
      Some(@support.family_of(kind, cycle))
    }
    _ => None
  }
}

///|
fn baseline_colors(
  family : @theme.Family?,
  theme : @theme.Theme,
) -> NodeAppearance {
  fn colors(p : @theme.Palette) -> @theme.FamilyColors {
    match family {
      Some(f) => p.family(f)
      None => { fill: p.bg, stroke: p.muted, ink: p.text, }
    }
  }
  { dark: colors(theme.dark), light: colors(theme.light), }
}

///|
fn paint_pair(
  paint : @projection.Paint,
  pick : (@theme.FamilyColors) -> @theme.Color,
  scheme : StatusScheme,
) -> Result[ColorPair, String] {
  match paint {
    Status(status) => {
      let role = scheme.role(status)
      Ok(ColorPair::{ dark: pick(role.dark), light: pick(role.light), })
    }
    Literal(css) =>
      match @theme.parse_color(css) {
        Some(color) => Ok(ColorPair::{ dark: color, light: color, })
        None => Err(css)
      }
    Variants(dark~, light~) =>
      match (@theme.parse_color(dark), @theme.parse_color(light)) {
        (Some(d), Some(l)) => Ok(ColorPair::{ dark: d, light: l, })
        (None, _) => Err(dark)
        (_, None) => Err(light)
      }
  }
}

///|
fn apply_colors(base : NodeAppearance, colors : Colors) -> NodeAppearance {
  fn one(
    c : @theme.FamilyColors,
    pick : (ColorPair) -> @theme.Color,
  ) -> @theme.FamilyColors {
    {
      fill: colors.fill.map(pick).unwrap_or(c.fill),
      stroke: colors.stroke.map(pick).unwrap_or(c.stroke),
      ink: colors.ink.map(pick).unwrap_or(c.ink),
    }
  }
  { dark: one(base.dark, p => p.dark), light: one(base.light, p => p.light), }
}

///|
/// Resolve semantic appearance against the context. A status sets fill,
/// stroke and ink from its role; explicit paints then win per property, and
/// render policies apply last in caller order. Contrast is checked on the
/// final composed colors of every changed visual.
pub fn resolve(
  view : @projection.View,
  context~ : RenderContext = RenderContext::new(),
  policies~ : ArrayView[RenderPolicy] = [],
) -> ResolvedScene {
  let findings = []
  let resolved = []
  let scheme = context.status
  for visual in view.visuals {
    let family = match visual.role {
      Body => baseline_family(visual, view.layout)
      Decoration(_) => None
    }
    let baseline = baseline_colors(family, context.theme)
    let a = visual.appearance
    let mut colors = match a.status {
      Some(status) => {
        let role = scheme.role(status)
        Colors::{
          fill: Some(ColorPair::{
            dark: role.dark.fill,
            light: role.light.fill,
          }),
          stroke: Some(ColorPair::{
            dark: role.dark.stroke,
            light: role.light.stroke,
          }),
          ink: Some(ColorPair::{ dark: role.dark.ink, light: role.light.ink, }),
        }
      }
      None => Colors::none()
    }
    fn explicit(
      paint : @projection.Paint?,
      pick : (@theme.FamilyColors) -> @theme.Color,
    ) -> ColorPair? {
      match paint {
        None => None
        Some(p) =>
          match paint_pair(p, pick, scheme) {
            Ok(pair) => Some(pair)
            Err(text) => {
              findings.push(
                @diagrams.Diagnostic::warning(
                  "projection/invalid-color",
                  "Invalid color '\{text}' for \{visual.key}",
                ),
              )
              None
            }
          }
      }
    }
    colors = colors.merge(Colors::{
      fill: explicit(a.fill, c => c.fill),
      stroke: explicit(a.stroke, c => c.stroke),
      ink: explicit(a.ink, c => c.ink),
    })
    // A badge on a literal fill gets an ink shaded for that fill.
    if visual.decoration is Some(Badge(_, Literal(_) | Variants(..))) &&
      colors.fill is Some(fill) {
      colors = {
        ..colors,
        ink: Some(ColorPair::{
          dark: @theme.text_shade(context.theme.dark.text, [
            @theme.over(fill.dark, context.theme.dark.bg),
          ]),
          light: @theme.text_shade(context.theme.light.text, [
            @theme.over(fill.light, context.theme.light.bg),
          ]),
        }),
      }
    }
    let partial = {
      visual,
      id: visual.element.id(),
      family,
      baseline,
      colors,
      composed: apply_colors(baseline, colors),
    }
    for policy in policies {
      if (policy.apply)(context, partial) is Some(more) {
        colors = colors.merge(more)
      }
    }
    let item = { ..partial, colors, composed: apply_colors(baseline, colors), }
    let check = match visual.decoration {
      None => !colors.is_empty()
      Some(Badge(_, _)) => true
      Some(Outline(_)) => false
    }
    if check {
      check_contrast(item, context, findings)
    }
    resolved.push(item)
  }
  {
    view,
    context,
    visuals: ReadOnlyArray::from_array(resolved),
    findings: ReadOnlyArray::from_array(findings),
  }
}

///|
fn check_contrast(
  item : ResolvedVisual,
  context : RenderContext,
  findings : Array[@diagrams.Diagnostic],
) -> Unit {
  for
    (variant, colors, palette) in [
      (Dark, item.composed.dark, context.theme.dark),
      (Light, item.composed.light, context.theme.light),
    ] {
    if context.mode == Adaptive || context.mode == Fixed(variant) {
      let ratio = @theme.contrast(
        colors.ink,
        @theme.over(colors.fill, palette.bg),
      ).min(@theme.contrast(colors.ink, @theme.over(colors.fill, palette.mask)))
      if ratio < 4.5 {
        let name = if variant == Dark { "dark" } else { "light" }
        findings.push(
          @diagrams.Diagnostic::warning(
            "projection/contrast",
            "Low contrast for \{item.visual.key} (\{name})",
          ),
        )
      }
    }
  }
}

///|
/// Colors that a painter applies to one element; absent ones keep its baseline.
priv struct ElementPaint {
  fill : String?
  stroke : String?
  ink : String?
}

///|
priv struct DecorationPaint {
  key : String
  badge : String?
  fill : String
  stroke : String
  ink : String
}

///|
/// Painter input derived from a resolved scene. With no overrides it is empty
/// and every painter writes its existing output byte for byte.
priv struct Overrides {
  elements : Map[String, ElementPaint]
  decorations : Map[String, Array[DecorationPaint]]
  /// Adaptive variables: name, dark and light color.
  variables : Array[(String, @theme.Color, @theme.Color)]
}

///|
fn Overrides::none() -> Overrides {
  { elements: Map([]), decorations: Map([]), variables: [], }
}

///|
fn Overrides::is_empty(self : Overrides) -> Bool {
  self.elements.is_empty() && self.decorations.is_empty()
}

///|
fn Overrides::element(self : Overrides, id : String) -> ElementPaint? {
  self.elements.get(id)
}

///|
fn Overrides::decorations_of(
  self : Overrides,
  id : String,
) -> Array[DecorationPaint] {
  self.decorations.get(id).unwrap_or([])
}

///|
/// The adaptive stylesheet for override variables, scoped to `selector`. It
/// follows the root stylesheet's dark default, light media query and explicit
/// `data-theme` overrides.
fn Overrides::css(self : Overrides, selector~ : String = "svg") -> String {
  if self.variables.is_empty() {
    return ""
  }
  let dark = StringBuilder()
  let light = StringBuilder()
  for item in self.variables {
    let (name, d, l) = item
    dark.write_string("--\{name}:\{d.to_css()};")
    light.write_string("--\{name}:\{l.to_css()};")
  }
  let dark = dark.to_string()
  let light = light.to_string()
  "\{selector} {\{dark}} @media (prefers-color-scheme: light) { \{selector} {\{light}} } \{selector}[data-theme=\"dark\"] {\{dark}} \{selector}[data-theme=\"light\"] {\{light}}"
}

///|
/// The number of selector occurrences that `css` writes.
fn Overrides::selectors(self : Overrides) -> Int32 {
  if self.variables.is_empty() {
    0
  } else {
    4
  }
}

///|
/// Painter overrides for the visuals that change appearance. Hidden visuals
/// and visuals without a painter identifier are skipped.
fn ResolvedScene::overrides(self : ResolvedScene) -> Overrides {
  let out = Overrides::none()
  fn color(pair : ColorPair) -> String {
    match self.context.mode {
      Fixed(Dark) => pair.dark.to_css()
      Fixed(Light) => pair.light.to_css()
      Adaptive => {
        let name = "projection-\{out.variables.length()}"
        out.variables.push((name, pair.dark, pair.light))
        "var(--\{name})"
      }
    }
  }
  for item in self.visuals {
    guard item.id is Some(id) && !item.visual.hidden else { continue }
    match item.visual.decoration {
      None =>
        if !item.colors.is_empty() && !out.elements.contains(id) {
          out.elements[id] = {
            fill: item.colors.fill.map(color),
            stroke: item.colors.stroke.map(color),
            ink: item.colors.ink.map(color),
          }
        }
      Some(decoration) => {
        let c = item.composed
        let pair = fn(pick : (@theme.FamilyColors) -> @theme.Color) {
          ColorPair::{ dark: pick(c.dark), light: pick(c.light), }
        }
        let paint = {
          key: item.visual.key,
          badge: match decoration {
            Badge(text, _) => Some(text)
            Outline(_) => None
          },
          fill: color(pair(f => f.fill)),
          stroke: color(pair(f => f.stroke)),
          ink: color(pair(f => f.ink)),
        }
        match out.decorations.get(id) {
          Some(items) => items.push(paint)
          None => out.decorations[id] = [paint]
        }
      }
    }
  }
  out
}

///|
/// Draw decorations around a box: outlines first, then badges at the top
/// right corner. Coordinates are in the painter's user space.
fn decoration_nodes(
  decorations : ArrayView[DecorationPaint],
  x : Double,
  y : Double,
  width : Double,
  height : Double,
) -> Array[@writer.Node] {
  let out = []
  fn number(v : Double) -> String {
    let rounded = (v * 100.0).round() / 100.0
    if rounded == rounded.floor() {
      rounded.to_int().to_string()
    } else {
      rounded.to_string()
    }
  }
  let mut badges = 0
  for d in decorations {
    match d.badge {
      None =>
        out.push(
          @writer.element("rect", attrs=[
            ("class", "projection-outline"),
            ("data-projection-key", d.key),
            ("x", number(x - 4.0)),
            ("y", number(y - 4.0)),
            ("width", number(width + 8.0)),
            ("height", number(height + 8.0)),
            ("rx", "6"),
            ("fill", "none"),
            ("stroke", d.stroke),
            ("stroke-width", "2"),
          ]),
        )
      Some(text) => {
        let cx = x + width - badges.to_double() * 20.0
        badges += 1
        out.push(
          @writer.element(
            "g",
            attrs=[
              ("class", "projection-badge"),
              ("data-projection-key", d.key),
            ],
            children=[
              @writer.element("circle", attrs=[
                ("cx", number(cx)),
                ("cy", number(y)),
                ("r", "9"),
                ("fill", d.fill),
                ("stroke", d.stroke),
              ]),
              @writer.element(
                "text",
                attrs=[
                  ("x", number(cx)),
                  ("y", number(y + 3.5)),
                  ("text-anchor", "middle"),
                  ("font-size", "10"),
                  ("font-weight", "700"),
                  ("fill", d.ink),
                ],
                children=[@writer.text(text)],
              ),
            ],
          ),
        )
      }
    }
  }
  out
}

///|
/// Render a projected view with this renderer's theme, mode and limits.
/// Layout uses the view's layout input, so changed labels, shapes, collapsed
/// containers and hidden elements reach geometry and routes. With a view that
/// has no overrides the output equals `render` of the same diagram.
pub fn SvgRenderer::render_view(
  self : SvgRenderer,
  view : @projection.View,
  status? : StatusScheme,
  policies~ : ArrayView[RenderPolicy] = [],
) -> @render.Rendered {
  let scene = resolve(
    view,
    context=RenderContext::new(theme=self.theme, mode=self.mode, status?),
    policies~,
  )
  self.render_scene(scene)
}

///|
/// Paint an already resolved scene.
pub fn SvgRenderer::render_scene(
  self : SvgRenderer,
  scene : ResolvedScene,
) -> @render.Rendered {
  let overrides = scene.overrides()
  let rendered = self.paint_with(scene.view.layout, overrides)
  let findings = scene.view.findings.iter().to_array()
  findings.append(scene.findings.iter().to_array())
  if findings.is_empty() {
    return rendered
  }
  findings.append(rendered.diagnostics.iter().to_array())
  match rendered.output {
    Some(output) =>
      @render.Rendered::ok(output, "image/svg+xml", diagnostics=findings[:])
    None => @render.Rendered::failed("image/svg+xml", findings[:])
  }
}

///|
/// An explicit themed session: a projection session plus the renderer and
/// render policies. Theme changes replace the renderer and repaint without
/// rerunning decisions or projection policies.
pub struct ThemedSession[A, V] {
  priv projection : @projection.Session[A, V]
  priv mut renderer : SvgRenderer
  priv mut status : StatusScheme?
  priv mut policies : ReadOnlyArray[RenderPolicy]
  priv mut rendered : @render.Rendered
}

///|
pub fn[A, V] ThemedSession::new(
  projection : @projection.Session[A, V],
  renderer~ : SvgRenderer = SvgRenderer::new(),
  status? : StatusScheme,
  policies~ : ArrayView[RenderPolicy] = [],
) -> ThemedSession[A, V] {
  {
    projection,
    renderer,
    status,
    policies: ReadOnlyArray::from_array(policies),
    rendered: renderer.render_view(projection.view(), status?, policies~),
  }
}

///|
/// The output of the last successful update.
pub fn[A, V] ThemedSession::rendered(
  self : ThemedSession[A, V],
) -> @render.Rendered {
  self.rendered
}

///|
pub fn[A, V] ThemedSession::projection(
  self : ThemedSession[A, V],
) -> @projection.Session[A, V] {
  self.projection
}

///|
/// Replace inputs at once. Projection inputs go to the projection session; a
/// failed projection keeps the previous output.
pub fn[A, V] ThemedSession::update(
  self : ThemedSession[A, V],
  model? : @projection.Model,
  state? : A,
  view? : V,
  policies? : ArrayView[@projection.Policy[A, V]],
  renderer? : SvgRenderer,
  status? : StatusScheme,
  render_policies? : ArrayView[RenderPolicy],
) -> Result[@render.Rendered, @projection.ProjectionError] {
  let projected = if model is None &&
    state is None &&
    view is None &&
    policies is None {
    self.projection.view()
  } else {
    match self.projection.update(model?, state?, view?, policies?) {
      Ok(value) => value
      Err(error) => return Err(error)
    }
  }
  let next_renderer = renderer.unwrap_or(self.renderer)
  let next_status = prefer(self.status, status)
  let next_policies = match render_policies {
    Some(values) => ReadOnlyArray::from_array(values)
    None => self.policies
  }
  let rendered = next_renderer.render_view(
    projected,
    status?=next_status,
    policies=next_policies[:],
  )
  self.renderer = next_renderer
  self.status = next_status
  self.policies = next_policies
  self.rendered = rendered
  Ok(rendered)
}