/* prices.jsx — OHLC fetcher via the backend /api/ohlc/:symbol proxy.
   The Alpha Vantage key lives in the API env (ALPHA_VANTAGE_KEY) so it
   does not need to be in browser localStorage. Frontend keeps a 12h
   localStorage cache to reduce backend calls.
*/

const PRICES_CACHE_PREFIX = "tw:prices:";

// Cache lives for ~12h
function cacheRead(symbol) {
  try {
    const raw = localStorage.getItem(PRICES_CACHE_PREFIX + symbol);
    if (!raw) return null;
    const { ts, candles, source } = JSON.parse(raw);
    if (Date.now() - ts > 12 * 3600_000) return null;
    return { candles, source };
  } catch { return null; }
}
function cacheWrite(symbol, candles, source) {
  try {
    localStorage.setItem(PRICES_CACHE_PREFIX + symbol,
      JSON.stringify({ ts: Date.now(), candles, source }));
  } catch {}
}

// In-flight de-dup
const _inflight = new Map();

async function fetchOHLC(symbol) {
  const cached = cacheRead(symbol);
  if (cached) return { candles: cached.candles, source: "cache" };

  if (_inflight.has(symbol)) return _inflight.get(symbol);

  const url = apiBase() + "/api/ohlc/" + encodeURIComponent(symbol);

  const promise = (async () => {
    try {
      const ctrl = new AbortController();
      const to = setTimeout(() => ctrl.abort(), 10000);
      const r = await fetch(url, { signal: ctrl.signal, credentials: "include" });
      clearTimeout(to);
      const j = await r.json();
      if (!j.candles) {
        return { candles: null, source: "fallback", error: j.error || "no data" };
      }
      cacheWrite(symbol, j.candles, j.source);
      return { candles: j.candles, source: j.source || "alphavantage" };
    } catch (e) {
      return { candles: null, source: "fallback", error: e.message };
    }
  })();

  _inflight.set(symbol, promise);
  promise.finally(() => _inflight.delete(symbol));
  return promise;
}

// React hook
function useOHLC(symbol) {
  const [state, setState] = useState({ loading: true, candles: null, source: null, error: null });
  useEffect(() => {
    let cancelled = false;
    setState(s => ({ ...s, loading: true }));
    fetchOHLC(symbol).then(res => {
      if (cancelled) return;
      if (res.candles) {
        setState({ loading: false, candles: res.candles, source: res.source, error: null });
      } else {
        // Fall back to deterministic mock if backend or AV returns nothing
        const mock = generateCandles(symbol, 100);
        setState({ loading: false, candles: mock, source: "mock", error: res.error });
      }
    });
    return () => { cancelled = true; };
  }, [symbol]);
  return state;
}

// Legacy shims so settings.jsx still works without ripping it out — these are now no-ops
function getApiKey() { return "managed-by-backend"; }
function setApiKey() {}

Object.assign(window, { fetchOHLC, useOHLC, getApiKey, setApiKey });
