import type { OHLCVBar } from './types';

export function calcAutoFib(bars: OHLCVBar[], lookback = 50): {
  high: number; low: number; highTime: number; lowTime: number;
  levels: Array<{ ratio: number; price: number; label: string }>;
} {
  const slice = bars.slice(-lookback);
  let high = -Infinity, low = Infinity, highTime = 0, lowTime = 0;
  for (const b of slice) {
    if (b.high > high)  { high = b.high; highTime = b.time; }
    if (b.low  < low)   { low  = b.low;  lowTime  = b.time; }
  }
  const range = high - low;
  const LEVELS = [
    { ratio: 0,     label: '0%' },
    { ratio: 0.236, label: '23.6%' },
    { ratio: 0.382, label: '38.2%' },
    { ratio: 0.5,   label: '50%' },
    { ratio: 0.618, label: '61.8%' },
    { ratio: 0.786, label: '78.6%' },
    { ratio: 1,     label: '100%' },
    { ratio: 1.272, label: '127.2%' },
    { ratio: 1.618, label: '161.8%' },
  ];
  return {
    high, low, highTime, lowTime,
    levels: LEVELS.map(l => ({ ...l, price: high - range * l.ratio })),
  };
}
