/* ModerateApp.jsx — controller for the moderate tier.
   Routes (HStage slide): result → nextstep → app(tabs) ; with lab, reversal,
   booking, booked as forward overlays. Reversal action completion is lifted
   here so the dashboard, reversal screen, and "today's actions" stay in sync.
   Reuses the shared result template + WellnessBooking (with moderate title). */

const { ResultScreen, RecommendedNextStep } = window.MunaHealthyResult;
const { PartnerLabs } = window.MunaPartnerLabs;
const { TIER_MODERATE, NEXTSTEP_MODERATE, ModerateTabBar, ComingSoonSheet } = window.MunaModerateConfig;
const { ModerateDashboard } = window.MunaModerateDashboard;
const { ReversalProgram } = window.MunaReversalProgram;
const { LearnTab, CareTabM, ProfileTabM } = window.MunaModerateSecondary;
const { WellnessBooking, BookingConfirmed } = window.MunaWellnessBooking;

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

function ModerateApp({ 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 [sheet, setSheet] = React.useState(null); // {title, body} | null
  const tabScroll = React.useRef(null);

  const go = (next, d) => { setDir(d != null ? d : (M_ROUTE_ORDER[next] >= M_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 openModule = (m) => setSheet({ title: m.title, body: 'This module isn’t built in the prototype yet. In the full app, this opens a ' + m.mins + ' guided video.' });

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

  const renderApp = () => {
    let content;
    if (tab === 'home') content = <ModerateDashboard todayDone={doneCount} onOpenReversal={() => go('reversal')} onSchedule={() => go('booking')} onOpenLearn={() => switchTab('learn')} onOpenActions={() => go('reversal')}/>;
    else if (tab === 'learn') content = <LearnTab onOpenModule={openModule}/>;
    else if (tab === 'care') content = <CareTabM onSchedule={() => go('booking')} onFindLab={() => openLab('app')}/>;
    else content = <ProfileTabM/>;
    return (
      <Screen scrollRef={tabScroll} footer={<ModerateTabBar active={tab} onChange={switchTab}/>}>
        <div key={tab} style={{ paddingBottom: 120 }}>{content}</div>
      </Screen>
    );
  };

  const render = (key) => {
    switch (key) {
      case 'result': return <ResultScreen tier={TIER_MODERATE} onPrimary={() => go('nextstep')}/>;
      case 'nextstep': return <RecommendedNextStep copy={NEXTSTEP_MODERATE} onBack={() => go('result')} onFindLab={() => openLab('nextstep')} onLater={() => { setTab('home'); go('app'); }}/>;
      case 'lab': return <PartnerLabs city="Abuja" onBack={() => go(labReturn, -1)}/>;
      case 'reversal': return <ReversalProgram onBack={() => go('app', -1)} completed={completed} onComplete={onComplete} onWhy={() => { go('app', -1); setTimeout(() => switchTab('learn'), 0); }}/>;
      case 'app': return renderApp();
      case 'booking': return <WellnessBooking title="Consultation 1" heading="Schedule consultation 1 — bloodwork review" 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 (
    <React.Fragment>
      <HStage activeKey={route} direction={dir} render={render}/>
      <ComingSoonSheet open={!!sheet} title={sheet ? sheet.title : ''} body={sheet ? sheet.body : ''} onClose={() => setSheet(null)}/>
    </React.Fragment>
  );
}

window.MunaModerateApp = { ModerateApp };
