const maxRateScale = 12;

export function residualDiamondsPerUsdToRate(value) {
    const diamonds = Number(String(value ?? "").trim());
    if (!Number.isFinite(diamonds) || diamonds <= 0) {
        return "0";
    }
    return trimDecimal((1 / diamonds).toFixed(maxRateScale));
}

export function residualRateToDiamondsPerUsd(rate) {
    const value = Number(String(rate ?? "").trim());
    if (!Number.isFinite(value) || value <= 0) {
        return "0";
    }
    const diamonds = 1 / value;
    const rounded = Math.round(diamonds);
    // 后端 rate 只保留 12 位小数，1/3 这类配置回显时会有极小误差；贴近整数时按整数展示。
    if (Math.abs(diamonds - rounded) < 0.000001) {
        return String(rounded);
    }
    return trimDecimal(diamonds.toFixed(6));
}

export function residualRateLabel(rate) {
    const diamonds = residualRateToDiamondsPerUsd(rate);
    return diamonds === "0" ? "剩余钻石不折美元" : `剩余钻石 ${diamonds}钻石=1美元`;
}

function trimDecimal(value) {
    const text = String(value || "0");
    if (!text.includes(".")) {
        return text;
    }
    const trimmed = text.replace(/0+$/, "").replace(/\.$/, "");
    return trimmed || "0";
}
