/* HighApp.jsx — controller for the high-risk tier.
   Routes (HStage slide): result → nextstep → app(3 tabs) ; with lab, consult,
   summary, rx, clinic as forward overlays. The video consult → summary flips
   `prescribed` ON, so the Care tab's prescriptions section + Profile meds update. */

const { ResultScreen, RecommendedNextStep } = window.MunaHealthyResult;
const { PartnerLabs } = window.MunaPartnerLabs;
const { TIER_HIGH, NEXTSTEP_HIGH, HighTabBar, HighComingSoonSheet } = window.MunaHighConfig;
const { HighDashboard } = window.MunaHighDashboard;
const { HighCare } = window.MunaHighCare;
const { VideoConsult, ConsultSummary } = window.MunaVideoConsult;
const { Prescription } = window.MunaPrescription;
const { ClinicBooking } = window.MunaClinicBooking;
const { HighProfile } = window.MunaHighProfile;

const H_ROUTE_ORDER = { result: 0, nextstep: 1, app: 2, lab: 3, consult: 3, summary: 4, rx: 5, clinic: 3 };

function HighApp({ 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 [prescribed, setPrescribed] = React.useState(!!(init && init.prescribed));
  const [booking, setBooking] = React.useState(null);
  const [clinicInit, setClinicInit] = React.useState((init && init.clinicStep) || 0);
  const [labReturn, setLabReturn] = React.useState('nextstep');
  const [rxReturn, setRxReturn] = React.useState('app');
  const [sheet, setSheet] = React.useState(null);
  const tabScroll = React.useRef(null);

  const go = (next, d) => { setDir(d != null ? d : (H_ROUTE_ORDER[next] >= H_ROUTE_ORDER[route] ? 1 : -1)); setRoute(next); };
  const switchTab = (t) => { setTab(t); if (tabScroll.current) tabScroll.current.scrollTop = 0; };
  const openLab = (from) => { setLabReturn(from); go('lab'); };
  const openRx = (from) => { setRxReturn(from); go('rx'); };
  const clinicianSoon = () => setSheet({ title: 'Clinician profile', body: 'Full clinician profiles aren’t built in the prototype yet. In the full app, this opens their bio, credentials, and availability.' });
  const calendarSoon = () => setSheet({ title: 'Calendar integration coming soon', body: 'In the full app, this adds your appointment to your phone’s calendar with a reminder. Not built in the prototype yet.' });

  const renderApp = () => {
    let content;
    if (tab === 'home') content = <HighDashboard booking={booking} onViewCarePlan={() => switchTab('care')} onJoinCall={() => go('consult')} onBookClinic={() => go('clinic')}/>;
    else if (tab === 'care') content = <HighCare prescribed={prescribed} booking={booking} onJoin={() => go('consult')} onBookClinic={() => go('clinic')} onFindLab={() => openLab('app')} onTrackRx={() => openRx('app')} onRemind={() => {}}/>;
    else content = <HighProfile onClinician={clinicianSoon} onTrackRx={() => openRx('app')}/>;
    return (
      <Screen scrollRef={tabScroll} footer={<HighTabBar active={tab} onChange={switchTab}/>}>
        <div key={tab} style={{ paddingBottom: 116 }}>{content}</div>
      </Screen>
    );
  };

  const render = (key) => {
    switch (key) {
      case 'result': return <ResultScreen tier={TIER_HIGH} onPrimary={() => go('nextstep')}/>;
      case 'nextstep': return <RecommendedNextStep copy={NEXTSTEP_HIGH} onBack={() => go('result')} onFindLab={() => openLab('nextstep')} onLater={() => { setTab('home'); go('app'); }}/>;
      case 'lab': return <PartnerLabs city="Kano" onBack={() => go(labReturn, -1)}/>;
      case 'consult': return <VideoConsult onEnd={() => { setPrescribed(true); go('summary'); }}/>;
      case 'summary': return <ConsultSummary onTrackRx={() => openRx('summary')} onBackToCare={() => { setTab('care'); go('app', -1); }}/>;
      case 'rx': return <Prescription onBack={() => { if (rxReturn === 'summary') go('summary', -1); else go('app', -1); }}/>;
      case 'clinic': return <ClinicBooking initStep={clinicInit} onExit={() => go('app', -1)} onComplete={setBooking} onCalendarSoon={calendarSoon} onDone={() => { setTab('care'); go('app', -1); }}/>;
      case 'app': return renderApp();
      default: return null;
    }
  };

  return (
    <React.Fragment>
      <HStage activeKey={route} direction={dir} render={render}/>
      <HighComingSoonSheet open={!!sheet} title={sheet ? sheet.title : ''} body={sheet ? sheet.body : ''} onClose={() => setSheet(null)}/>
    </React.Fragment>
  );
}

window.MunaHighApp = { HighApp };
