/* HealthyApp.jsx — controller for the Healthy tier.
   Top-level routes (HStage slide): result → nextstep → app(tabs) ; with lab &
   booking as forward overlays. Challenge completion is lifted here so the Home
   tab's progress and the Challenges/Profile tabs stay in sync. */

const { ResultScreen, RecommendedNextStep } = window.MunaHealthyResult;
const { PartnerLabs } = window.MunaPartnerLabs;
const { Dashboard } = window.MunaHealthyDashboard;
const { ChallengesTab, CareTab, ProfileTab } = window.MunaHealthySecondary;
const { WellnessBooking, BookingConfirmed } = window.MunaWellnessBooking;

const ROUTE_ORDER = { result: 0, nextstep: 1, app: 2, lab: 3, booking: 3, booked: 4 };

function HealthyApp({ init }) {
  const [route, setRoute] = React.useState((init && init.route) || 'result');
  const [dir, setDir] = React.useState(1);
  const [tab, setTab] = React.useState((init && init.tab) || 'home');
  const [completed, setCompleted] = React.useState({});
  const [slot, setSlot] = React.useState(null);
  const [labReturn, setLabReturn] = React.useState('nextstep');
  const tabScroll = React.useRef(null);

  const go = (next, d) => { setDir(d != null ? d : (ROUTE_ORDER[next] >= ROUTE_ORDER[route] ? 1 : -1)); setRoute(next); };
  const onComplete = (id) => setCompleted(c => ({ ...c, [id]: true }));
  const switchTab = (t) => {
    setTab(t);
    if (tabScroll.current) tabScroll.current.scrollTop = 0;
  };
  const openLab = (from) => { setLabReturn(from); go('lab'); };

  const doneCount = Object.keys(completed).filter(k => completed[k]).length;

  // The tabbed app shell
  const renderApp = () => {
    let content;
    if (tab === 'home') content = <Dashboard todayDone={doneCount} onSchedule={() => go('booking')} onOpenChallenges={() => switchTab('challenges')}/>;
    else if (tab === 'challenges') content = <ChallengesTab completed={completed} onComplete={onComplete}/>;
    else if (tab === 'care') content = <CareTab onSchedule={() => go('booking')} onFindLab={() => openLab('app')}/>;
    else content = <ProfileTab completed={completed}/>;
    return (
      <Screen scrollRef={tabScroll} footer={<HealthyTabBar active={tab} onChange={switchTab}/>}>
        <div key={tab} style={{ paddingBottom: 120 }}>
          {content}
        </div>
      </Screen>
    );
  };

  const render = (key) => {
    switch (key) {
      case 'result': return <ResultScreen onPrimary={() => go('nextstep')}/>;
      case 'nextstep': return <RecommendedNextStep onBack={() => go('result')} onFindLab={() => openLab('nextstep')} onLater={() => { setTab('home'); go('app'); }}/>;
      case 'lab': return <PartnerLabs city="Lagos" onBack={() => go(labReturn, -1)}/>;
      case 'app': return renderApp();
      case 'booking': return <WellnessBooking onBack={() => go('app', -1)} onConfirmed={(s) => { setSlot(s); go('booked'); }}/>;
      case 'booked': return <BookingConfirmed slotId={slot} onDone={() => { setTab('home'); go('app', -1); }}/>;
      default: return null;
    }
  };

  return <HStage activeKey={route} direction={dir} render={render}/>;
}

window.MunaHealthyApp = { HealthyApp };
