import { createContext, useContext, useState, useEffect } from 'react';
import { fetchBenchmarks, fetchResults, fetchEval, fetchNlg } from '../api';

const AppContext = createContext();

export function AppProvider({ children }) {
  const [benchmarks, setBenchmarks] = useState([]);
  const [currentBM, setCurrentBM] = useState('WTI');
  const [months, setMonths] = useState([]);
  const [currentMonth, setCurrentMonth] = useState(0);
  const [evalData, setEvalData] = useState({});
  const [nlgData, setNlgData] = useState({});
  const [loading, setLoading] = useState(true);

  // Load benchmarks on mount
  useEffect(() => {
    fetchBenchmarks().then(bms => {
      setBenchmarks(bms);
      if (bms.length > 0) setCurrentBM(bms[0]);
    }).catch(() => setBenchmarks(['WTI']));
  }, []);

  // Load data when benchmark changes
  useEffect(() => {
    if (!currentBM) return;
    setLoading(true);
    Promise.all([
      fetchResults(currentBM),
      fetchEval(currentBM),
      fetchNlg(currentBM),
    ]).then(([results, ev, nlg]) => {
      setMonths(results);
      setCurrentMonth(results.length - 1);
      setEvalData(ev);
      setNlgData(nlg);
      setLoading(false);
    }).catch(err => {
      console.error('Failed to load data:', err);
      setLoading(false);
    });
  }, [currentBM]);

  const current = months[currentMonth] || {};
  const prev = months[currentMonth - 1] || current;

  return (
    <AppContext.Provider value={{
      benchmarks, currentBM, setCurrentBM,
      months, currentMonth, setCurrentMonth,
      current, prev, evalData, nlgData, loading,
    }}>
      {children}
    </AppContext.Provider>
  );
}

export function useApp() {
  return useContext(AppContext);
}
