// Nine services' p99 latency, one panel each. The grid answers "which
// service is misbehaving" (checkout is); CLICKING THAT HEADER answers "what
// exactly happened": the panel expands to the grid's full width with both
// axes readable, and the "All panels" breadcrumb puts the grid back. Zoom
// and legend state survive the round trip.
//
// Deterministic latencies so the e2e snapshot is stable.
function mulberry32(seed) {
  return function () {
    seed |= 0
    seed = (seed + 0x6d2b79f5) | 0
    var t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
  }
}

var SERVICES = [
  { name: 'gateway', seed: 3, base: 120 },
  { name: 'auth', seed: 11, base: 85 },
  { name: 'catalog', seed: 19, base: 140 },
  { name: 'search', seed: 27, base: 210 },
  { name: 'cart', seed: 35, base: 95 },
  { name: 'checkout', seed: 43, base: 150 },
  { name: 'payments', seed: 51, base: 180 },
  { name: 'shipping', seed: 59, base: 110 },
  { name: 'notifications', seed: 67, base: 70 },
]

function latency(seed, base, degradeFrom) {
  var rand = mulberry32(seed)
  var out = []
  var ts = new Date('01 Jan 2025').getTime()
  var val = base
  for (var i = 0; i < 72; i++) {
    val = Math.max(40, val + (rand() - 0.5) * base * 0.1)
    var v = val
    // checkout degrades in steps after hour 40: the shape you promote to see.
    if (degradeFrom && i >= degradeFrom) {
      v = val + Math.min(320, (i - degradeFrom) * 14)
    }
    out.push([ts, Math.round(v)])
    ts += 3600000 // hourly
  }
  return out
}

var latencySeries = SERVICES.map(function (s) {
  return {
    name: 'p99 latency',
    service: s.name,
    data: latency(s.seed, s.base, s.name === 'checkout' ? 40 : 0),
  }
})

var options = {
  series: latencySeries,
  chart: {
    id: 'latencyTrellis',
    type: 'line',
    animations: {
      enabled: false,
    },
  },
  trellis: {
    by: 'service',
    minPanelWidth: 250,
    panelHeight: 140,
    gap: 12,
  },
  colors: ['#0891B2'],
  stroke: {
    width: 2,
    curve: 'straight',
  },
  xaxis: {
    type: 'datetime',
  },
  yaxis: {
    labels: {
      formatter: function (val) {
        return Math.round(val) + ' ms'
      },
    },
  },
  dataLabels: {
    enabled: false,
  },
  tooltip: {
    x: {
      format: 'dd MMM HH:mm',
    },
  },
}

var chart = new ApexCharts(document.querySelector('#chart'), options)
chart.render()