// quiz-baby-rockets.jsx
// Baby Rockets: preschool helper-card launch play; persists badges under
// planets_baby_rocket_badges.

const BABY_ROCKET_BADGES_KEY = "planets_baby_rocket_badges";
const BABY_ROCKET_SPRITE_ROOT = "data/sprites/baby-rockets";
const BABY_ROCKET_SPRITE_REV = "mode-atlas-hq-v2-20260526";

function babyRocketSpriteUrl(file) {
  return `${BABY_ROCKET_SPRITE_ROOT}/${file}?v=${BABY_ROCKET_SPRITE_REV}`;
}

const BABY_ROCKET_MOMMY_SPRITE = babyRocketSpriteUrl(
  "mommy-rocket-care-atlas.png",
);

const BABY_ROCKETS = [
  {
    id: "tiny-spark",
    name: "Tiny Spark",
    mission: "Sunbeam hop",
    body: "#ff7d66",
    accent: "#ffd66b",
    trim: "#fff4c2",
    trail: "#ffb45f",
    planet: "#ffb17a",
    planetRing: "#ffd9a8",
    face: "•",
    glyph: "1",
    orbit: "Sunbeam Lane",
    reward: "steady fins badge",
    sprite: {
      modes: babyRocketSpriteUrl("tiny-spark-mode-atlas-hq-v2.png"),
      flight: babyRocketSpriteUrl("tiny-spark-flight-sheet.png"),
      bed: babyRocketSpriteUrl("tiny-spark-bed-sheet.png"),
    },
  },
  {
    id: "moon-peep",
    name: "Moon Peep",
    mission: "Moon peek",
    body: "#62f3ff",
    accent: "#b6f4ff",
    trim: "#e8fbff",
    trail: "#7cffce",
    planet: "#8fd0ff",
    planetRing: "#e7f7ff",
    face: "o",
    glyph: "2",
    orbit: "Moon Peek Path",
    reward: "bubble fuel badge",
    sprite: {
      modes: babyRocketSpriteUrl("moon-peep-mode-atlas-hq-v2.png"),
      flight: babyRocketSpriteUrl("moon-peep-flight-sheet.png"),
      bed: babyRocketSpriteUrl("moon-peep-bed-sheet.png"),
    },
  },
  {
    id: "comet-cub",
    name: "Comet Cub",
    mission: "Comet coast",
    body: "#ffd66b",
    accent: "#ff8ee7",
    trim: "#fff7d8",
    trail: "#ff8ee7",
    planet: "#d8b8ff",
    planetRing: "#ffcff4",
    face: "^",
    glyph: "3",
    orbit: "Comet Cub Trail",
    reward: "soft lift-off badge",
    sprite: {
      modes: babyRocketSpriteUrl("comet-cub-mode-atlas-hq-v2.png"),
      flight: babyRocketSpriteUrl("comet-cub-flight-sheet.png"),
      bed: babyRocketSpriteUrl("comet-cub-bed-sheet.png"),
    },
  },
];

const BABY_ROCKET_ACTIONS = {
  window: {
    id: "window",
    label: "Window",
    icon: "○",
    detail: "Peek path",
    stage: "window",
  },
  fins: {
    id: "fins",
    label: "Fins",
    icon: "△",
    detail: "Stay straight",
    stage: "fins",
  },
  fuel: {
    id: "fuel",
    label: "Fuel",
    icon: "🫧",
    detail: "Push power",
    stage: "fuel",
  },
  count: {
    id: "count",
    label: "Count",
    icon: "3",
    detail: "Ready team",
    stage: "count",
  },
  launch: {
    id: "launch",
    label: "Launch",
    icon: "🔥",
    detail: "Push down",
    stage: "launch",
  },
  map: {
    id: "map",
    label: "Map",
    icon: "☆",
    detail: "Pick path",
    stage: "map",
  },
  snack: {
    id: "snack",
    label: "Snack",
    icon: "☾",
    detail: "Tiny rest",
    stage: "snack",
  },
  sleep: {
    id: "sleep",
    label: "Sleep",
    icon: "Zz",
    detail: "Mommy tuck",
    stage: "sleep",
  },
};

const BABY_ROCKET_STEPS = [
  {
    id: "window",
    label: "Window check",
    target: "window",
    prompt: "What helps the pilot peek at the path?",
    fact: "A window helps the pilot see the way.",
    choices: ["window", "map", "fins"],
  },
  {
    id: "fins",
    label: "Steady fins",
    target: "fins",
    prompt: "What keeps the baby rocket pointing straight?",
    fact: "Fins help a rocket stay steady.",
    choices: ["snack", "fins", "fuel"],
  },
  {
    id: "fuel",
    label: "Bubble fuel",
    target: "fuel",
    prompt: "What gives the rocket push power?",
    fact: "Fuel makes hot gas push down.",
    choices: ["fuel", "window", "map"],
  },
  {
    id: "count",
    label: "Countdown",
    target: "count",
    prompt: "What helps the team launch together?",
    fact: "Counting helps the launch team get ready together.",
    choices: ["fins", "count", "snack"],
  },
  {
    id: "launch",
    label: "Lift off",
    target: "launch",
    prompt: "What sends the rocket up?",
    fact: "The engine pushes down, so the rocket moves up.",
    choices: ["map", "launch", "window"],
  },
  {
    id: "sleep",
    label: "Bedtime",
    target: "sleep",
    prompt: "Who tucks the baby rocket into bed?",
    fact: "Mommy Rocket tucks the baby rocket in so it can dream about space.",
    choices: ["sleep", "snack", "map"],
  },
];

const BABY_ROCKET_MODE_COLUMNS = {
  window: 0,
  fins: 1,
  fuel: 2,
  count: 3,
  launch: 4,
  sleep: 5,
};
const BABY_ROCKET_FRAME_COUNT = 4;
const BABY_ROCKET_ATLAS_FRAME = 512;
const BABY_ROCKET_ATLAS_GUTTER = 96;
const BABY_ROCKET_ATLAS_COLS = 6;
const BABY_ROCKET_ATLAS_ROWS = 4;
const BABY_ROCKET_ATLAS_WIDTH =
  BABY_ROCKET_ATLAS_COLS * BABY_ROCKET_ATLAS_FRAME +
  (BABY_ROCKET_ATLAS_COLS + 1) * BABY_ROCKET_ATLAS_GUTTER;
const BABY_ROCKET_ATLAS_HEIGHT =
  BABY_ROCKET_ATLAS_ROWS * BABY_ROCKET_ATLAS_FRAME +
  (BABY_ROCKET_ATLAS_ROWS + 1) * BABY_ROCKET_ATLAS_GUTTER;
const BABY_ROCKET_MOMMY_ATLAS = {
  frameWidth: 360,
  frameHeight: 360,
  frameCount: 4,
  gutter: 48,
  atlasWidth: 1680,
  atlasHeight: 456,
};
const BABY_ROCKET_FRAME_SAFE_INSET = 2;
const BABY_ROCKET_DWELL_ACTIVE = [175, 385, 385, 175];
const BABY_ROCKET_DWELL_SLEEP = [275, 605, 605, 275];

function readBabyRocketBadges() {
  const saved = readStorageJson(BABY_ROCKET_BADGES_KEY, []);
  if (!Array.isArray(saved)) return [];
  const validIds = BABY_ROCKETS.map((rocket) => rocket.id);
  return saved.filter((id) => validIds.includes(id));
}

function babyRocketSceneStyle(rocket) {
  return {
    "--baby-rocket-body": rocket.body,
    "--baby-rocket-accent": rocket.accent,
    "--baby-rocket-trim": rocket.trim,
    "--baby-rocket-trail": rocket.trail,
    "--baby-planet": rocket.planet,
    "--baby-planet-ring": rocket.planetRing,
  };
}

function BabySpriteImage({
  src,
  className,
  context,
  style,
  fallbackClassName,
  dataRocket,
  dataMode,
  dataFrame,
}) {
  const SafeImage = window.SpaceExplorerFoundation?.SafeAssetImage;
  if (SafeImage) {
    return (
      <SafeImage
        src={src}
        alt=""
        className={className}
        fallbackClassName={fallbackClassName || "baby-sprite-fallback"}
        fallbackText="Baby rocket sprite could not load."
        context={context}
        draggable="false"
        style={style}
        data-rocket={dataRocket}
        data-mode={dataMode}
        data-frame={dataFrame}
      />
    );
  }
  return (
    <img
      src={src}
      alt=""
      className={className}
      draggable="false"
      style={style}
      data-rocket={dataRocket}
      data-mode={dataMode}
      data-frame={dataFrame}
    />
  );
}

function clampBabyRocketFrame(frameIndex, frameCount) {
  return Math.max(0, Math.min(frameCount - 1, frameIndex || 0));
}

function babyRocketSafeFrameMeta(frameMeta) {
  if (!frameMeta) return frameMeta;
  const inset = Math.min(
    BABY_ROCKET_FRAME_SAFE_INSET,
    Math.floor(Math.min(frameMeta.frameWidth, frameMeta.frameHeight) / 4),
  );
  if (!inset) return frameMeta;
  return {
    ...frameMeta,
    x: frameMeta.x + inset,
    y: frameMeta.y + inset,
    frameWidth: frameMeta.frameWidth - inset * 2,
    frameHeight: frameMeta.frameHeight - inset * 2,
  };
}

function babyRocketModeFrameMeta(col, row) {
  const x =
    BABY_ROCKET_ATLAS_GUTTER +
    col * (BABY_ROCKET_ATLAS_FRAME + BABY_ROCKET_ATLAS_GUTTER);
  const y =
    BABY_ROCKET_ATLAS_GUTTER +
    row * (BABY_ROCKET_ATLAS_FRAME + BABY_ROCKET_ATLAS_GUTTER);
  return babyRocketSafeFrameMeta({
    x,
    y,
    frameWidth: BABY_ROCKET_ATLAS_FRAME,
    frameHeight: BABY_ROCKET_ATLAS_FRAME,
    atlasWidth: BABY_ROCKET_ATLAS_WIDTH,
    atlasHeight: BABY_ROCKET_ATLAS_HEIGHT,
  });
}

function babyRocketLinearFrameMeta(atlas, frameIndex) {
  const frame = clampBabyRocketFrame(frameIndex, atlas.frameCount);
  return babyRocketSafeFrameMeta({
    x: atlas.gutter + frame * (atlas.frameWidth + atlas.gutter),
    y: atlas.gutter,
    frameWidth: atlas.frameWidth,
    frameHeight: atlas.frameHeight,
    atlasWidth: atlas.atlasWidth,
    atlasHeight: atlas.atlasHeight,
  });
}

function babyRocketAtlasPosition(value, span, size) {
  const travel = span - size;
  if (!travel) return "0%";
  return `${(value / travel) * 100}%`;
}

function babyRocketAtlasClipStyle(src, frameMeta) {
  if (!frameMeta) return undefined;
  return {
    backgroundImage: `url("${src}")`,
    backgroundRepeat: "no-repeat",
    backgroundSize: `${(frameMeta.atlasWidth / frameMeta.frameWidth) * 100}% ${(frameMeta.atlasHeight / frameMeta.frameHeight) * 100}%`,
    backgroundPosition: `${babyRocketAtlasPosition(frameMeta.x, frameMeta.atlasWidth, frameMeta.frameWidth)} ${babyRocketAtlasPosition(frameMeta.y, frameMeta.atlasHeight, frameMeta.frameHeight)}`,
  };
}

function babyRocketAtlasViewportStyle(frameMeta) {
  if (!frameMeta) return undefined;
  return {
    aspectRatio: `${frameMeta.frameWidth} / ${frameMeta.frameHeight}`,
  };
}

function BabyRocketAtlasSprite({
  src,
  frameMeta,
  className,
  context,
  dataRocket,
  dataMode,
  dataFrame,
}) {
  return (
    <span
      className={`baby-sprite-viewport ${className || ""}`.trim()}
      style={babyRocketAtlasViewportStyle(frameMeta)}
      aria-hidden="true"
    >
      <span
        className="baby-sprite-atlas-clip"
        style={babyRocketAtlasClipStyle(src, frameMeta)}
      >
        <BabySpriteImage
          src={src}
          className="baby-sprite-atlas-preload"
          fallbackClassName="baby-sprite-fallback baby-sprite-atlas-fallback"
          context={context}
          dataRocket={dataRocket}
          dataMode={dataMode}
          dataFrame={dataFrame}
        />
      </span>
    </span>
  );
}

function BabyRocketModeFrame({ rocket, mode, frameIndex }) {
  const safeMode = Object.prototype.hasOwnProperty.call(
    BABY_ROCKET_MODE_COLUMNS,
    mode,
  )
    ? mode
    : "window";
  const col = BABY_ROCKET_MODE_COLUMNS[safeMode];
  const row = clampBabyRocketFrame(frameIndex, BABY_ROCKET_FRAME_COUNT);
  const frameMeta = babyRocketModeFrameMeta(col, row);
  return (
    <BabyRocketAtlasSprite
      src={rocket?.sprite?.modes}
      frameMeta={frameMeta}
      className={`mode mode-${safeMode}`}
      context={`BabyRockets:${rocket?.id}:${safeMode}`}
      dataRocket={rocket?.id}
      dataMode={safeMode}
      dataFrame={row}
    />
  );
}

function BabyMommyRocketSprite({ active, frameIndex }) {
  const frameMeta = babyRocketLinearFrameMeta(
    BABY_ROCKET_MOMMY_ATLAS,
    frameIndex,
  );
  return (
    <span
      className={`baby-mommy-sprite ${active ? "active" : ""}`}
      aria-hidden="true"
    >
      <BabyRocketAtlasSprite
        src={BABY_ROCKET_MOMMY_SPRITE}
        frameMeta={frameMeta}
        className="mommy"
        context="BabyRockets:mommy"
        dataFrame={clampBabyRocketFrame(
          frameIndex,
          BABY_ROCKET_MOMMY_ATLAS.frameCount,
        )}
      />
    </span>
  );
}

function firstOpenBabyRocketIndex(badges, startIndex = -1) {
  const afterCurrent = BABY_ROCKETS.findIndex(
    (item, index) => index > startIndex && !badges.includes(item.id),
  );
  if (afterCurrent !== -1) return afterCurrent;
  const firstOpen = BABY_ROCKETS.findIndex((item) => !badges.includes(item.id));
  return firstOpen === -1 ? Math.max(0, startIndex) : firstOpen;
}

function BabyRocketsLevel({ onExit }) {
  const [rocketIndex, setRocketIndex] = useState(0);
  const [stepIndex, setStepIndex] = useState(0);
  const [sceneStage, setSceneStage] = useState("window");
  const [pickedAction, setPickedAction] = useState(null);
  const [modeFrame, setModeFrame] = useState(0);
  const [sparkleStep, setSparkleStep] = useState(null);
  const [badges, setBadges] = useState(() => readBabyRocketBadges());
  const [message, setMessage] = useState(
    "Pick a helper card. Then Mommy Rocket tucks each baby into bed.",
  );
  const sparkleTimerRef = useRef(null);
  const celebrationShownRef = useRef(false);
  const rocket = BABY_ROCKETS[rocketIndex];
  const currentStep = BABY_ROCKET_STEPS[stepIndex];
  const rocketDone = badges.includes(rocket.id);
  const complete = badges.length === BABY_ROCKETS.length;
  const progressCount = rocketDone ? BABY_ROCKET_STEPS.length : stepIndex;
  const sleepyScene = complete || rocketDone || sceneStage === "sleep";
  const displayStage = sleepyScene ? "sleep" : sceneStage;
  const mommyActive = sleepyScene || currentStep?.id === "sleep";
  const currentChoices = currentStep
    ? currentStep.choices
        .map((actionId) => BABY_ROCKET_ACTIONS[actionId])
        .filter(Boolean)
    : [];
  const targetAction = currentStep ? BABY_ROCKET_ACTIONS[currentStep.target] : null;
  const picked = pickedAction ? BABY_ROCKET_ACTIONS[pickedAction] : null;
  const sceneLabel = sleepyScene
    ? "Sleepy tuck"
    : picked
      ? picked.label
      : currentStep?.label || "Ready";
  const spriteTempo = displayStage === "sleep" ? "sleep" : "active";

  useEffect(() => {
    writeStorageValue(BABY_ROCKET_BADGES_KEY, JSON.stringify(badges));
  }, [badges]);

  useEffect(() => {
    window.scrollTo({ top: 0, left: 0 });
    return () => window.clearTimeout(sparkleTimerRef.current);
  }, []);

  useEffect(() => {
    setModeFrame(0);
    const dwells =
      spriteTempo === "sleep"
        ? BABY_ROCKET_DWELL_SLEEP
        : BABY_ROCKET_DWELL_ACTIVE;
    let cancelled = false;
    let frame = 0;
    let nextFrameAt = window.performance.now() + dwells[0];
    let animationFrame = 0;
    const tick = (now) => {
      if (cancelled) return;
      if (now >= nextFrameAt) {
        frame = (frame + 1) % BABY_ROCKET_FRAME_COUNT;
        setModeFrame(frame);
        nextFrameAt = now + dwells[frame];
      }
      animationFrame = window.requestAnimationFrame(tick);
    };
    animationFrame = window.requestAnimationFrame(tick);
    return () => {
      cancelled = true;
      window.cancelAnimationFrame(animationFrame);
    };
  }, [rocket.id, spriteTempo]);

  useEffect(() => {
    if (!complete || celebrationShownRef.current) return;
    celebrationShownRef.current = true;
    window.SpaceExplorerFoundation?.celebrateGameFinish?.({
      gameId: "baby-rockets",
      emoji: "🚀",
      title: "Sleepy fleet!",
      message: "Every baby rocket flew, got tucked in, and earned a badge.",
    });
  }, [complete]);

  const flashAction = (actionId) => {
    window.clearTimeout(sparkleTimerRef.current);
    setSparkleStep(actionId);
    sparkleTimerRef.current = window.setTimeout(() => {
      setSparkleStep(null);
    }, 560);
  };

  const playAction = (actionId) => {
    if (complete || rocketDone || !currentStep) return;
    const action = BABY_ROCKET_ACTIONS[actionId];
    if (!action) return;
    setPickedAction(actionId);
    setSceneStage(action.stage);
    flashAction(actionId);

    if (actionId !== currentStep.target) {
      playKidSound("boop");
      const target = BABY_ROCKET_ACTIONS[currentStep.target];
      setMessage(`${action.label} can help later. Try ${target.label} now.`);
      return;
    }

    playKidSound("chime");
    const nextStep = stepIndex + 1;
    if (nextStep < BABY_ROCKET_STEPS.length) {
      setStepIndex(nextStep);
      setMessage(`${currentStep.fact} Next: ${BABY_ROCKET_STEPS[nextStep].prompt}`);
      return;
    }

    setBadges((items) =>
      items.includes(rocket.id) ? items : [...items, rocket.id],
    );
    setMessage(
      `${currentStep.fact} ${rocket.name} is tucked in after ${rocket.orbit}. You earned a ${rocket.reward}.`,
    );
  };

  const chooseRocket = (nextIndex) => {
    const nextRocket = BABY_ROCKETS[nextIndex];
    if (!nextRocket) return;
    setRocketIndex(nextIndex);
    setStepIndex(0);
    setSceneStage("window");
    setPickedAction(null);
    setModeFrame(0);
    setSparkleStep(null);
    setMessage(
      badges.includes(nextRocket.id)
        ? `${nextRocket.name} is already sleepy with a badge. Pick another rocket or play again.`
        : `Help ${nextRocket.name}. Pick the helper card that matches the clue.`,
    );
    window.scrollTo({ top: 0, left: 0 });
  };

  const nextRocket = () => {
    chooseRocket(firstOpenBabyRocketIndex(badges, rocketIndex));
  };

  const reset = () => {
    window.clearTimeout(sparkleTimerRef.current);
    setRocketIndex(0);
    setStepIndex(0);
    setSceneStage("window");
    setPickedAction(null);
    setModeFrame(0);
    setSparkleStep(null);
    setBadges([]);
    celebrationShownRef.current = false;
    setMessage("Pick a helper card. Then Mommy Rocket tucks each baby into bed.");
    window.requestAnimationFrame(() => window.scrollTo({ top: 0, left: 0 }));
  };

  return (
    <section className="baby-rockets-level" aria-label="Baby Rockets game">
      <Starfield count={230} />
      <button className="planet-sort-back" onClick={onExit}>
        ← Back to planets
      </button>
      <div className="baby-rockets-shell">
        <div
          className={`baby-rockets-art-panel stage-${displayStage}`}
          style={babyRocketSceneStyle(rocket)}
        >
          <div
            className={`baby-rocket-scene ${sleepyScene ? "is-sleeping" : "is-flying"} ${mommyActive ? "has-mommy" : ""}`}
            aria-hidden="true"
          >
            <div className="baby-scene-stars">
              <i />
              <i />
              <i />
            </div>
            <div className="baby-flight-space">
              <div className={`baby-sprite-path path-${rocket.id}`}>
                <BabyRocketModeFrame
                  rocket={rocket}
                  mode={displayStage}
                  frameIndex={modeFrame}
                />
              </div>
            </div>
            <BabyMommyRocketSprite active={mommyActive} frameIndex={modeFrame} />
            <div className="baby-action-echo">
              <span>{sleepyScene ? "Zz" : picked ? picked.icon : "↗"}</span>
              <strong>{sceneLabel}</strong>
            </div>
          </div>
          <div className="baby-rocket-flightline" aria-hidden="true">
            {BABY_ROCKET_STEPS.map((step, index) => (
              <span
                key={step.id}
                className={
                  index < progressCount
                    ? "done"
                    : index === progressCount && !rocketDone && !complete
                      ? "now"
                      : ""
                }
              />
            ))}
          </div>
        </div>
        <div className="baby-rockets-play-panel">
          <div className="baby-rockets-kicker">Baby Rockets</div>
          <h1>{complete ? "Sleepy fleet!" : rocket.name}</h1>
          <p>
            Pick helper cards, watch each baby rocket loop around, then let
            Mommy Rocket tuck it into bed.
          </p>

          <div className="baby-rocket-picker" aria-label="Choose a baby rocket">
            {BABY_ROCKETS.map((item, index) => {
              const earned = badges.includes(item.id);
              return (
                <button
                  key={item.id}
                  className={`${index === rocketIndex ? "selected" : ""} ${earned ? "earned" : ""}`}
                  onClick={() => chooseRocket(index)}
                  aria-pressed={index === rocketIndex}
                  style={{
                    "--baby-picker-body": item.body,
                    "--baby-picker-accent": item.accent,
                  }}
                >
                  <span>{earned ? "★" : item.glyph}</span>
                  <strong>{item.name}</strong>
                </button>
              );
            })}
          </div>

          <div className="baby-rockets-question">
            <span>
              {complete
                ? "Fleet complete"
                : rocketDone
                  ? "Badge earned"
                  : `${rocket.mission} - Step ${stepIndex + 1} of ${BABY_ROCKET_STEPS.length}`}
            </span>
            <strong>
              {complete
                ? "All baby rockets are tucked in."
                : rocketDone
                  ? `${rocket.name} is sleeping after a tiny trip.`
                  : currentStep.prompt}
            </strong>
          </div>

          {!complete && !rocketDone && currentStep ? (
            <div className="baby-physics-clue" aria-label="Rocket science clue">
              <strong>Science clue</strong>
              <span>{currentStep.fact}</span>
              {targetAction ? <small>Look for: {targetAction.detail}</small> : null}
            </div>
          ) : null}

          <div className="baby-rockets-options" aria-label="Helper cards">
            {currentChoices.map((action) => (
              <button
                key={action.id}
                className={`baby-action-card ${sparkleStep === action.id ? "sparkle" : ""}`}
                onClick={() => playAction(action.id)}
                disabled={rocketDone || complete}
              >
                <span>{action.icon}</span>
                <strong>{action.label}</strong>
                <small>{action.detail}</small>
              </button>
            ))}
          </div>

          <div className="baby-step-strip" aria-label="Launch steps">
            {BABY_ROCKET_STEPS.map((step, index) => (
              <span
                key={step.id}
                className={
                  index < progressCount
                    ? "done"
                    : index === progressCount && !rocketDone && !complete
                      ? "now"
                      : ""
                }
              >
                {step.label}
              </span>
            ))}
          </div>

          <div className="baby-rockets-message" role="status" aria-live="polite">
            {message}
          </div>
          <div className="baby-rockets-actions">
            <div className="baby-rockets-badges" aria-label="Baby rocket badges">
              {BABY_ROCKETS.map((item) => (
                <span
                  key={item.id}
                  className={badges.includes(item.id) ? "on" : ""}
                  title={item.reward}
                >
                  🚀
                </span>
              ))}
            </div>
            {complete ? (
              <>
                <button onClick={reset}>Play again</button>
                <button onClick={onExit}>Done</button>
              </>
            ) : rocketDone ? (
              <>
                <button onClick={nextRocket}>Next rocket</button>
                <button onClick={reset}>Start over</button>
              </>
            ) : (
              <>
                <button
                  onClick={() => playAction(currentStep.target)}
                  disabled={!currentStep}
                >
                  Help now
                </button>
                {badges.length ? <button onClick={reset}>Start over</button> : null}
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
