// ----- App shell: one app; the chosen trial shapes Home + Check-in -----
(() => {
const { Landing, Designer, CheckIn } = window.Screens1;
const { Home, PastResults, Explore, Profile } = window.Screens2;
const { Icon } = window.UI;

function readRoute() {
  const h = (window.location.hash || "").replace(/^#\/?/, "");
  if (h.startsWith("past/")) return { r: "past", id: h.slice(5) };
  if (h.startsWith("designer/")) return { r: "designer", id: h.slice(9) };
  const known = ["home", "landing", "designer", "checkin", "explore", "profile"];
  return { r: known.includes(h) ? h : "landing", id: null };
}

function App() {
  const [route, setRoute] = useState(readRoute());
  const [activeId, setActiveId] = useState("curfew");
  const [logged, setLogged] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [toastMsg, setToastMsg] = useState(null);
  const toastTimer = useRef(null);
  const cfg = window.TRIALS[activeId];

  useEffect(() => {
    const onHash = () => setRoute(readRoute());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const nav = (r) => { window.location.hash = "/" + r; setMenuOpen(false); };
  const toast = (msg) => {
    setToastMsg(msg);
    if (toastTimer.current) clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToastMsg(null), 2600);
  };
  const startTrial = (id) => { setActiveId(id); setLogged(false); };

  const screens = {
    landing: <Landing nav={nav} toast={toast} />,
    designer: <Designer key={route.id || "free"} nav={nav} toast={toast} exampleId={route.id} onStartTrial={startTrial} />,
    checkin: <CheckIn nav={nav} toast={toast} onLogged={() => setLogged(true)} cfg={cfg.checkin} />,
    home: <Home nav={nav} toast={toast} logged={logged} cfg={cfg} />,
    explore: <Explore nav={nav} toast={toast} />,
    profile: <Profile nav={nav} toast={toast} cfg={cfg} />,
    past: <PastResults id={route.id} nav={nav} />,
  };

  const tabs = [
    { r: "home", label: "Home", icon: "home" },
    { r: "explore", label: "Explore", icon: "compass" },
    { r: "plus" },
    { r: "profile", label: "Profile", icon: "user" },
  ];

  const menuItems = [
    { r: "landing", t: "Landing / onboarding" },
    { r: "designer", t: "Trial designer" },
    { r: "home", t: "Home · active + past" },
    { r: "checkin", t: "Daily check-in" },
    { r: "past/" + cfg.pastIds[0], t: "Past trial results" },
    { r: "explore", t: "Explore / community" },
    { r: "profile", t: "Profile & consents" },
  ];

  return (
    <div className="frame">
      {route.r !== "designer" && (
        <button className="menu-fab" onClick={() => setMenuOpen(!menuOpen)}>
          <Icon name="menu" size={13} /> screens
        </button>
      )}
      {menuOpen && (
        <div className="menu-panel">
          <div className="cap">Jump to screen</div>
          {menuItems.map((m) => (
            <button key={m.r} className={`mi ${route.r === m.r.split("/")[0] ? "on" : ""}`} onClick={() => nav(m.r)}>
              {m.t}
            </button>
          ))}
          <div className="divider" />
          <div className="cap">Active trial</div>
          {Object.keys(window.TRIALS).map((id) => (
            <button key={id} className={`mi ${activeId === id ? "on" : ""}`} onClick={() => { startTrial(id); setMenuOpen(false); }}>
              {window.TRIALS[id].trial.title} {activeId === id && <Icon name="check" size={13} />}
            </button>
          ))}
        </div>
      )}

      <div className="screen" key={route.r + (route.id || "") + activeId} onClick={() => menuOpen && setMenuOpen(false)}>
        {screens[route.r]}
      </div>

      <div className="tabbar">
        {tabs.map((t) =>
          t.r === "plus" ? (
            <button key="plus" className="tab-plus" onClick={() => nav("designer")} aria-label="New trial">
              <Icon name="plus" size={24} />
            </button>
          ) : (
            <button key={t.r} className={`tab ${route.r === t.r ? "on" : ""}`} onClick={() => nav(t.r)}>
              <Icon name={t.icon} size={23} />
              {t.label}
            </button>
          )
        )}
      </div>

      {toastMsg && <div className="toast">{toastMsg}</div>}
    </div>
  );
}

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