/* App entry — Phase 3.
 *
 * Hash routes:
 *   /                     → Capture
 *   /hub/{members|recent|attention|search}
 *   /hub/member/{row_id}  → Member detail
 *   /design               → DesignSystem showcase
 *   /events,/workouts,/meetings → "Coming next phase" placeholder
 *
 * AppShell renders the navigation chrome around the active view.
 */

(function () {
  const { useState, useEffect } = React;
  const { createRoot } = ReactDOM;
  const {
    ToastHost,
    DesignSystem,
    Capture,
    KnowledgeHub,
    Settings,
    Events,
    Workouts,
    Meetings,
    AppShell,
    CoachGate,
    EmptyState,
    Icons,
    members,
  } = window.CC;

  // Boot the live members + workouts subscriptions once for the whole app.
  members.start();
  window.CC.workouts.start();
  window.CC.shortcuts.start();

  function useHashRoute() {
    const get = () => window.location.hash.replace(/^#/, "") || "/";
    const [route, setRoute] = useState(get());
    useEffect(() => {
      const onChange = () => setRoute(get());
      window.addEventListener("hashchange", onChange);
      return () => window.removeEventListener("hashchange", onChange);
    }, []);
    return route;
  }

  function ComingNext({ phase, label }) {
    return (
      <div style={{ padding: 64 }}>
        <EmptyState
          icon={Icons.calendar(40)}
          title={`${label} lands in Phase ${phase}`}
          subtitle="The shell knows where this is going — the view is being built."
        />
      </div>
    );
  }

  function App() {
    const route = useHashRoute();

    if (route.startsWith("/design")) {
      return (
        <CoachGate>
          <DesignSystem onBack={() => (window.location.hash = "/")} />
          <ToastHost />
        </CoachGate>
      );
    }

    let view;
    if (route.startsWith("/hub")) view = <KnowledgeHub route={route} />;
    else if (route.startsWith("/events")) view = <Events />;
    else if (route.startsWith("/workouts")) view = <Workouts route={route} />;
    else if (route.startsWith("/meetings")) view = <Meetings />;
    else if (route.startsWith("/settings")) view = <Settings />;
    else view = <Capture />;

    return (
      <CoachGate>
        <AppShell route={route}>{view}</AppShell>
        <ToastHost />
      </CoachGate>
    );
  }

  const root = createRoot(document.getElementById("root"));
  root.render(<App />);
})();
