// The demo's session flow. Every question screen is DNA's own component (intake/dna_intake.jsx,
// generated from DNA/index.html by build.mjs): Player Profile -> Student Interview -> A Bit More
// -> Goal Setting, exactly as DNA asks them. Then the store's data upload (TPI, TrackMan,
// TrackMan 3D — the static #intake section, run by app.js), then DNA's post-test interviews:
// the golfer's "How did today go?" and the coach's notes with the KPI assignment. Then the report.
//
// This file only ORDERS steps and bridges to app.js (window.SuperstoreDemo). It asks nothing of
// its own: a question changed in DNA reaches the store on the next build.

const DEMO_STEPS = [
  { id: 'profile', short: 'Profile' },
  { id: 'interview', short: 'Interview' },
  { id: 'golferFollowup', short: 'Follow-up' },
  { id: 'goals', short: 'Goals' },
  { id: 'upload', short: 'Data Upload' },
  { id: 'golferReflection', short: 'Today' },
  { id: 'coachInput', short: 'Coach' },
  { id: 'report', short: 'Report' },
];

function DemoApp() {
  const [step, setStep] = useState('profile');
  const [done, setDone] = useState(() => new Set());
  const [interview, setInterview] = useState({});
  // Bumped when the sample golfer loads, so DNA's adaptive steps re-mount and re-ask.
  const [epoch, setEpoch] = useState(0);
  const bridge = window.SuperstoreDemo;

  const update = useCallback((f, v) => setInterview(prev => Object.assign({}, prev, { [f]: v })), []);
  React.useEffect(() => { bridge.setInterview(interview); }, [interview]);

  const go = useCallback((id) => {
    setStep(id);
    window.scrollTo(0, 0);
  }, []);
  const next = useCallback(() => {
    const i = DEMO_STEPS.findIndex(s => s.id === step);
    setDone(prev => new Set([...prev, step]));
    if (i < DEMO_STEPS.length - 1) go(DEMO_STEPS[i + 1].id);
  }, [step, go]);
  const prev = useCallback(() => {
    const i = DEMO_STEPS.findIndex(s => s.id === step);
    if (i > 0) go(DEMO_STEPS[i - 1].id);
  }, [step, go]);

  // The upload screen is static HTML owned by app.js; show it on its step and route its buttons.
  React.useEffect(() => {
    bridge.showUpload(step === 'upload');
    if (step === 'report') bridge.showReport(interview, () => go('coachInput'));
    else bridge.hideReport();
  }, [step]);
  React.useEffect(() => {
    const onNav = (e) => (e.detail === 'next' ? next() : prev());
    window.addEventListener('demo-nav', onNav);
    return () => window.removeEventListener('demo-nav', onNav);
  }, [next, prev]);

  const loadSample = () => {
    setInterview(bridge.loadSample());
    setEpoch(n => n + 1);
    setDone(new Set(['profile', 'interview', 'golferFollowup', 'goals']));
    go('upload');
  };

  // DNA's post-test interviews read the whole session, exactly as they do in DNA.
  const context = Object.assign({ interview }, bridge.domains());
  const name = [interview.firstName, interview.lastName].filter(Boolean).join(' ');

  return (
    <div>
      {step !== 'report' && (
        <nav className="stepper-container">
          <div className="stepper">
            {DEMO_STEPS.map(s => (
              <div key={s.id} className={`step ${step === s.id ? 'active' : ''} ${done.has(s.id) ? 'completed' : ''}`}
                   onClick={() => go(s.id)}>{s.short}</div>
            ))}
            <div className="demo-tools">
              {name && <span className="demo-name">{name}</span>}
              <button type="button" className="demo-sample" onClick={loadSample}>Load sample golfer</button>
            </div>
          </div>
        </nav>
      )}
      {step !== 'upload' && step !== 'report' && (
        <main className="main-content" key={epoch}>
          {step === 'profile' && <ProfileForm data={interview} update={update} onNext={next} onPrev={prev} />}
          {step === 'interview' && <InterviewForm data={interview} update={update} onNext={next} onPrev={prev} />}
          {step === 'golferFollowup' && <AdaptiveInterview role="golfer" data={interview} update={update} contextData={interview} onNext={next} onPrev={prev} />}
          {step === 'goals' && <GoalSetting data={interview} update={update} onNext={next} onPrev={prev} />}
          {step === 'golferReflection' && <AdaptiveInterview role="reflection" data={interview} update={update} contextData={context} onNext={next} onPrev={prev} />}
          {step === 'coachInput' && <AdaptiveInterview role="coach" data={interview} update={update} contextData={context} onNext={next} onPrev={prev} />}
        </main>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('flowRoot')).render(<DemoApp />);
