import { useEffect, useState } from 'react';
import { listScreenerRuns, getScreenerRun } from '../../../../api';

export function useScreenerHistory() {
  const [runs, setRuns] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedRun, setSelectedRun] = useState(null);

  useEffect(() => {
    listScreenerRuns(30).then((r) => { setRuns(r); setLoading(false); });
  }, []);

  async function selectRun(id) {
    if (!id) { setSelectedRun(null); return; }
    const detail = await getScreenerRun(id);
    setSelectedRun({
      asof: detail.meta.asof,
      mode: detail.meta.mode,
      status: detail.meta.status,
      run_id: detail.meta.id,
      survivors_count: detail.meta.survivors_count,
      weights: detail.meta.weights,
      top_n: detail.meta.top_n,
      results: detail.results,
      telegram_payload: null,
      warnings: [],
      meta: detail.meta,
    });
  }

  return { runs, runs_loading: loading, selectedRun, selectRun };
}
