import { useState } from 'react';
import { AppProvider, useAppState } from './context/AppContext.jsx';
import Toast from './components/Toast.jsx';
import Step1Setup from './pages/Step1Setup.jsx';
import Step2Variables from './pages/Step2Variables.jsx';
import Step3Contributions from './pages/Step3Contributions.jsx';
import Step4Mapping from './pages/Step4Mapping.jsx';
import Step5FixedVars from './pages/Step5FixedVars.jsx';
import Step6Params from './pages/Step6Params.jsx';
import Step7Config from './pages/Step7Config.jsx';
import { showWarnToast } from './components/Toast.jsx';

function AppInner() {
  const [step, setStep] = useState(1);
  const state = useAppState();

  function canLeave(from) {
    if (from === 1) {
      if (!state.files.d || !state.files.p) { showWarnToast('Upload both CSV files first.'); return false; }
      if (!state.selectedPanels.size) { showWarnToast('Select at least 1 panel.'); return false; }
    }
    if (from === 2) {
      const selCount = state.allRows.filter(r => r._sel).length;
      if (!selCount) { showWarnToast('Select at least 1 variable.'); return false; }
    }
    if (from === 3) {
      const hasActs = state.allRows.some(r => r._sel);
      if (!hasActs) { showWarnToast('No variables selected — go back to Page 2.'); return false; }
    }
    if (from === 4) {
      const anyMapped = Object.values(state.panelMap).some(row => Object.values(row).some(v => v === true));
      if (!anyMapped) { showWarnToast('Map at least 1 variable before proceeding.'); return false; }
    }
    return true;
  }

  function goTo(n) {
    if (n > step && !canLeave(step)) return;
    setStep(n);
  }

  function next() { goTo(step + 1); }
  function back() { setStep(s => Math.max(1, s - 1)); }

  const pageProps = { onNext: next, onBack: back, onNav: n => { if (n < step) setStep(n); } };

  return (
    <>
      {step === 1 && <Step1Setup {...pageProps} />}
      {step === 2 && <Step2Variables {...pageProps} />}
      {step === 3 && <Step3Contributions {...pageProps} />}
      {step === 4 && <Step4Mapping {...pageProps} />}
      {step === 5 && <Step5FixedVars {...pageProps} />}
      {step === 6 && <Step6Params {...pageProps} />}
      {step === 7 && <Step7Config {...pageProps} />}
      <Toast />
    </>
  );
}

export default function App() {
  return (
    <AppProvider>
      <AppInner />
    </AppProvider>
  );
}
