// Forage & Forests — Root app + screen routing.

/* eslint-disable no-undef */

function App() {
  const [screen, setScreen] = React.useState("intro"); // intro | forage
  const [rulebookOpen, setRulebookOpen] = React.useState(false);
  const [askConsent, setAskConsent] = React.useState(false);

  const openRulebook = () => setRulebookOpen(true);
  const closeRulebook = () => setRulebookOpen(false);

  // "Start the free playtest" → ask for a feedback commitment first. Agreeing
  // opens the game; declining returns the player to the landing page.
  const requestPlay = () => {
    if (window.HHApi) window.HHApi.track("playtest_start_click");
    setAskConsent(true);
  };
  const beginGame = () => {
    if (window.HHApi) {
      window.HHApi.track("playtest_consent", { agreed: true });
      window.HHApi.track("game_start");
    }
    setAskConsent(false);
    setScreen("forage");
  };
  const declinePlay = () => {
    if (window.HHApi) window.HHApi.track("playtest_consent", { agreed: false });
    setAskConsent(false); // stay on the landing page
  };

  return (
    <div className={`hh-app${screen === "forage" ? " in-game" : ""}`}>
      {/* Screens */}
      {screen === "intro" && (
        <IntroScreen
          onPlayCards={requestPlay}
          onOpenRulebook={openRulebook}
        />
      )}

      {screen === "forage" && (
        <ForageScreen
          onExit={() => setScreen("intro")}
          onOpenRulebook={openRulebook}
        />
      )}

      {rulebookOpen && <Rulebook onClose={closeRulebook} />}

      {/* Feedback consent gate before the game opens. */}
      {askConsent && typeof PlaytestConsentModal !== "undefined" && (
        <PlaytestConsentModal onAgree={beginGame} onDecline={declinePlay} />
      )}

      {/* Always-available feedback, context-tagged by screen. */}
      {typeof FeedbackWidget !== "undefined" && <FeedbackWidget context={screen === "forage" ? "online-game" : "site"} />}
    </div>
  );
}

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