const AXIS_DECIMALS = 2

export function roundAxisValue(val: number, decimals = AXIS_DECIMALS): number {
    if (!Number.isFinite(val)) return 0
    const factor = 10 ** decimals
    return Math.round(val * factor) / factor
}

/** Y 轴刻度：最多 2 位小数，末尾 0 去掉（如 1.00 → 1，0.10 → 0.1） */
export function formatAxisLabel(value: number): string {
    if (!Number.isFinite(value)) return '0'
    return String(Number(roundAxisValue(value).toFixed(AXIS_DECIMALS)))
}

/** 瞬间波形 Y 轴范围 */
export function calcShuYAxisRange(dataMin: number, dataMax: number): { min: number; max: number } {
    const min = Number(dataMin)
    const max = Number(dataMax)
    if (!Number.isFinite(min) || !Number.isFinite(max)) {
        return { min: 0, max: 1 }
    }

    let axisMax = max * 1.1
    let axisMin = min > 0 ? min - min * 0.1 : min * 1.1

    if (axisMax <= axisMin) {
        const pad = Math.abs(max) * 0.1 || 0.01
        axisMax = max + pad
        axisMin = min - pad
    }

    return {
        min: roundAxisValue(axisMin),
        max: roundAxisValue(axisMax)
    }
}

/** RMS 波形 Y 轴范围 */
export function calcRmsYAxisRange(dataMin: number, dataMax: number): { min: number; max: number } {
    const min = Number(dataMin)
    const max = Number(dataMax)
    if (!Number.isFinite(min) || !Number.isFinite(max)) {
        return { min: 0, max: 1 }
    }

    let axisMax = max * 1.06 * 1.1
    let axisMin = min - min * 0.2

    if (axisMax <= axisMin) {
        const pad = Math.abs(max - min) * 0.1 || Math.abs(max) * 0.1 || 0.01
        axisMax = max + pad
        axisMin = min - pad
    }

    return {
        min: roundAxisValue(axisMin),
        max: roundAxisValue(axisMax)
    }
}
