// indicators.jsx — thin wrappers around technicalindicators library
// Handles missing OHLC gracefully (returns null when data unavailable)

(function () {
  const TI = window;

  function computeRSI(closes, period = 14) {
    if (!closes || closes.length < period + 1) return null;
    try {
      return TI.RSI.calculate({ period, values: closes });
    } catch { return null; }
  }

  function computeEMA(closes, period) {
    if (!closes || closes.length < period) return null;
    try {
      return TI.EMA.calculate({ period, values: closes });
    } catch { return null; }
  }

  function computeSMA(closes, period) {
    if (!closes || closes.length < period) return null;
    try {
      return TI.SMA.calculate({ period, values: closes });
    } catch { return null; }
  }

  function computeADX(high, low, close, period = 14) {
    if (!high || !low || !close) return null;
    if (high.length < period * 2 || high.length !== low.length || high.length !== close.length) return null;
    try {
      return TI.ADX.calculate({ period, high, low, close });
    } catch { return null; }
  }

  function computeATR(high, low, close, period = 14) {
    if (!high || !low || !close) return null;
    if (high.length < period + 1 || high.length !== low.length || high.length !== close.length) return null;
    try {
      return TI.ATR.calculate({ period, high, low, close });
    } catch { return null; }
  }

  function lastValue(arr) {
    if (!arr || arr.length === 0) return null;
    return arr[arr.length - 1];
  }

  function valueAt(arr, seriesIndex, seriesLen) {
    if (!arr || arr.length === 0) return null;
    const offset = seriesLen - arr.length;
    const idx = seriesIndex - offset;
    if (idx < 0 || idx >= arr.length) return null;
    return arr[idx];
  }

  window.indicators = {
    computeRSI,
    computeEMA,
    computeSMA,
    computeADX,
    computeATR,
    lastValue,
    valueAt,
  };
})();
