///|
fn chart_bounds(analysis : Analysis) -> (Double, Double) {
  let mut low = 0.0
  let mut high = maximum(0.0, analysis.filtration.cutoff)
  for cell in analysis.filtration.cells {
    if cell.value < low {
      low = cell.value
    }
    if cell.value > high {
      high = cell.value
    }
  }
  if high <= low {
    high = low + maximum(1.0, low.abs() * 0.1)
  }
  (low, high)
}

///|
fn color(dimension : Int) -> String {
  if dimension == 0 {
    "#38bdf8"
  } else {
    "#fb923c"
  }
}

///|
/// Standalone SVG barcode. Drawing is capped at 80 rows; JSON retains all bars.
/// Essential bars have a dashed ending, indicating the input cutoff.
pub fn barcode_svg(analysis : Analysis) -> String {
  let (low, high) = chart_bounds(analysis)
  let count = if analysis.intervals.length() > 80 {
    80
  } else {
    analysis.intervals.length()
  }
  let height = 120 + count * 22
  let mut svg = "MoonTopoLens | Persistence barcodeH0: components (blue) / H1: loops (orange) / dashed: alive at cutoff"
  for tick = 0; tick <= 4; tick = tick + 1 {
    let x = 100 + tick * 185
    let value = low + (high - low) * tick.to_double() / 4.0
    svg += "\{value}"
  }
  for i = 0; i < count; i = i + 1 {
    let interval = analysis.intervals[i]
    let x1 = 100.0 + (interval.birth - low) / (high - low) * 740.0
    let end = match interval.death {
      None => analysis.filtration.cutoff
      Some(d) => d
    }
    let x2 = 100.0 + (end - low) / (high - low) * 740.0
    let y = 85 + i * 22
    let dash = if interval.death is None {
      " stroke-dasharray=\"7 4\""
    } else {
      ""
    }
    svg += "H\{interval.dimension} #\{i}"
  }
  if count < analysis.intervals.length() {
    svg += "Showing first 80 intervals; full data is in report.json."
  }
  svg + ""
}

///|
/// Standalone birth/death scatter plot with essential classes shown at the top.
pub fn diagram_svg(analysis : Analysis) -> String {
  let (low, high) = chart_bounds(analysis)
  let mut svg = "MoonTopoLens | Persistence diagramH0 blue / H1 orange / top row: alive at cutoffBirthDeath"
  for tick = 0; tick <= 4; tick = tick + 1 {
    let offset = tick.to_double() * 122.5
    let value = low + (high - low) * tick.to_double() / 4.0
    svg += "\{value}\{value}"
  }
  for interval in analysis.intervals {
    let x = 80.0 + (interval.birth - low) / (high - low) * 490.0
    let y = match interval.death {
      None => 68.0
      Some(d) => 570.0 - (d - low) / (high - low) * 490.0
    }
    svg += "H\{interval.dimension} birth=\{interval.birth}"
  }
  svg + ""
}