/*
 * Copyright 2025 Palantir Technologies, Inc. All rights reserved.
 *
 * 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.
 */

export const HISTOGRAM_BUCKETS = 20;
/**
 * Returns "nice" tick positions covering the [0, max] range — values that
 * round to 1/2/5 × 10^n so the tick labels read cleanly. Used for
 * y-axis axis lines on the histogram.
 *
 * Edge cases:
 *  - max ≤ 0          → returns [0]
 *  - max ≤ 1/2/3      → returns [0, ..., max] without rounding to 5/10
 *  - otherwise        → between 3 and 6 ticks aligned on a nice step
 */
export function niceTicks(max, desiredCount = 5) {
  if (!Number.isFinite(max) || max <= 0) return [0];
  if (max <= 3) {
    const out = [];
    for (let i = 0; i <= Math.ceil(max); i++) out.push(i);
    return out;
  }
  const rough = max / desiredCount;
  const exponent = Math.floor(Math.log10(rough));
  const fraction = rough / Math.pow(10, exponent);
  const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
  const step = niceFraction * Math.pow(10, exponent);
  const ticks = [];
  for (let v = 0; v <= max + step / 2; v += step) {
    ticks.push(Math.round(v / step) * step);
  }
  return ticks;
}
export function createHistogramBuckets(pairs, range, toNumber, fromNumber) {
  if (pairs.length === 0) {
    return [];
  }
  const minNum = toNumber(range.min);
  const maxNum = toNumber(range.max);
  const rangeSize = maxNum - minNum;

  // Handle single-value case
  if (rangeSize === 0) {
    const totalCount = pairs.reduce((sum, p) => sum + p.count, 0);
    return [{
      min: range.min,
      max: range.max,
      count: totalCount
    }];
  }

  // Create buckets
  const bucketSize = rangeSize / HISTOGRAM_BUCKETS;
  const bucketCounts = new Array(HISTOGRAM_BUCKETS).fill(0);
  for (const {
    value,
    count
  } of pairs) {
    const bucketIndex = Math.min(Math.floor((toNumber(value) - minNum) / bucketSize), HISTOGRAM_BUCKETS - 1);
    bucketCounts[bucketIndex] += count;
  }
  return bucketCounts.map((count, i) => ({
    min: fromNumber(minNum + i * bucketSize),
    max: fromNumber(minNum + (i + 1) * bucketSize),
    count
  }));
}
export function getMaxBucketCount(buckets) {
  return Math.max(...buckets.map(b => b.count), 1);
}
//# sourceMappingURL=createHistogramBuckets.js.map