// Chart utilities shared across variants.
// Provides number formatting and React helpers.
(function () {
  function fmt(value, digits = 2) {
    if (value == null || isNaN(value)) return '—';
    const n = typeof value === 'string' ? parseFloat(value) : value;
    return n.toLocaleString('en-US', {
      minimumFractionDigits: digits,
      maximumFractionDigits: digits,
    });
  }

  function fmtSigned(value, digits = 2, suffix = '') {
    if (value == null || isNaN(value)) return '—';
    const n = typeof value === 'string' ? parseFloat(value) : value;
    const sign = n >= 0 ? '+' : '';
    return sign + fmt(n, digits) + suffix;
  }

  // Normalize trade side strings — both "long"/"buy" (entry) are treated as long.
  // Dedupes the `side === 'long' || side === 'buy'` pattern across files.
  function isLongSide(rawSide) {
    return rawSide === 'long' || rawSide === 'buy';
  }

  // React helper: run `effect` when `deps` change, but only after `delayMs`
  // of quiet time. Prevents request storms when sliders move.
  function useDebouncedEffect(effect, deps, delayMs) {
    React.useEffect(() => {
      const handle = setTimeout(() => {
        effect();
      }, delayMs);
      return () => clearTimeout(handle);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, deps);
  }

  window.ChartUtils = {
    fmt,
    fmtSigned,
    isLongSide,
    useDebouncedEffect,
  };
})();
