function PilotControlLevel({ onExit }) {
  const [systems, setSystems] = useState({
    battery: false,
    fuelPump: false,
    sparkPlug: false,
    engineBell: false,
    stabilizer: false,
    radar: false,
  });
  const [throttle, setThrottle] = useState(0);
  const [steer, setSteer] = useState(0);
  const [ship, setShip] = useState({ x: 38, y: 58, vx: 0, vy: 0, angle: -4 });
  const [docked, setDocked] = useState(false);
  const [autoDocking, setAutoDocking] = useState(false);
  const [lesson, setLesson] = useState({
    title: "Build the engine",
    text: "Tap the glowing part. Power flows from the battery to fuel, spark, and engine.",
  });
  const [readoutVisible, setReadoutVisible] = useState(true);
  const throttleStickRef = useRef(null);
  const frameRef = useRef({ raf: 0, last: 0 });
  const dockedRef = useRef(false);
  const steerSpoken = useRef({ left: false, right: false });
  const [pilotSoundOn, setPilotSoundOn] = useSoundToggle();
  const speakSteer = (dir) => {
    if (steerSpoken.current[dir]) return;
    steerSpoken.current[dir] = true;
    if (window.__narration) {
      window.__narration.play("game_pilot_steer_" + dir + ".mp3");
    }
  };

  const engineParts = [
    {
      id: "battery",
      label: "Battery",
      short: "1",
      part: "electricity",
      hint: "The battery sends electricity through the control board.",
    },
    {
      id: "fuelPump",
      label: "Fuel pump",
      short: "2",
      part: "fuel",
      hint: "The fuel pump pushes fuel toward the engine.",
    },
    {
      id: "sparkPlug",
      label: "Spark plug",
      short: "3",
      part: "spark",
      hint: "The spark plug lights the fuel so it can burn.",
    },
    {
      id: "engineBell",
      label: "Engine bell",
      short: "4",
      part: "thrust",
      hint: "The engine bell points hot gas backward to push the rocket forward.",
    },
  ];
  const supportParts = [
    {
      id: "stabilizer",
      label: "Stabilizer fins",
      hint: "Stabilizer fins help the ship stop wobbling.",
    },
    {
      id: "radar",
      label: "Radar dish",
      hint: "Radar helps a pilot find the docking target.",
    },
  ];
  const systemLabels = {
    battery: "electric",
    fuelPump: "fuel",
    sparkPlug: "spark",
    engineBell: "thrust",
  };
  const engineReady = engineParts.every((part) => systems[part.id]);
  const nextEnginePart = engineParts.find((part) => !systems[part.id]);
  const shipPower = Math.min(
    100,
    Math.round(
      (systems.battery ? 22 : 0) +
        (systems.fuelPump ? 14 : 0) +
        (systems.sparkPlug ? 12 : 0) +
        (systems.engineBell ? 12 : 0) +
        (engineReady ? throttle * 0.4 : 0),
    ),
  );
  const flightReady = engineReady && throttle >= 45;
  const distanceToDock = Math.min(
    100,
    Math.round(Math.hypot(ship.x - 76, ship.y - 44) * 1.8),
  );
  const dockingProgress = docked
    ? 100
    : flightReady
      ? Math.max(0, 100 - distanceToDock)
      : 0;
  const currentGoal = nextEnginePart
    ? "Tap " + nextEnginePart.label
    : docked
      ? "Docked at ISS"
      : autoDocking
        ? "Docking to ISS"
        : throttle < 45
          ? "Push throttle up"
          : "Fly through the target";
  const cockpitCue = nextEnginePart
    ? "Build: " + nextEnginePart.label
    : docked
      ? "Dock complete"
      : autoDocking
        ? "Careful docking"
        : throttle < 45
          ? "Add power"
          : "Ready to dock";

  useEffect(() => {
    setReadoutVisible(true);
    const timer = setTimeout(() => setReadoutVisible(false), 4200);
    return () => clearTimeout(timer);
  }, [lesson.title, lesson.text]);

  useEffect(() => {
    const tick = (now) => {
      const last = frameRef.current.last || now;
      const dt = Math.min(2, Math.max(0.4, (now - last) / 16.67));
      frameRef.current.last = now;
      setShip((current) => {
        if (dockedRef.current) {
          return {
            ...current,
            x: current.x + (72 - current.x) * 0.12 * dt,
            y: current.y + (42 - current.y) * 0.12 * dt,
            vx: 0,
            vy: 0,
            angle: current.angle + (-6 - current.angle) * 0.12 * dt,
          };
        }
        const thrust = engineReady ? throttle / 100 : 0;
        const targetX = 76;
        const targetY = 44;
        const dockingAssist = autoDocking && engineReady;
        const guideX = flightReady
          ? Math.max(-1, Math.min(1, (targetX - current.x) / 34)) *
            (dockingAssist ? 0.52 : systems.radar ? 0.28 : 0.2)
          : 0;
        const guideY = flightReady
          ? Math.max(-1, Math.min(1, (targetY - current.y) / 28)) *
            (dockingAssist ? 0.42 : systems.radar ? 0.2 : 0.15)
          : 0;
        const wobble =
          systems.stabilizer || dockingAssist ? 0 : Math.sin(now / 620) * 0.01;
        const targetVx =
          (dockingAssist ? 0 : steer * (systems.stabilizer ? 0.1 : 0.16)) +
          guideX;
        const targetVy =
          -thrust * (dockingAssist ? 0.035 : 0.06) + guideY + 0.012;
        let vx =
          current.vx +
          (targetVx - current.vx) * (systems.stabilizer ? 0.2 : 0.16) * dt;
        let vy =
          current.vy +
          (targetVy - current.vy) * (systems.stabilizer ? 0.2 : 0.16) * dt;
        let x = current.x + vx * dt;
        let y = current.y + vy * dt;
        if (x < 18 || x > 82) {
          vx *= -0.25;
          x = Math.max(18, Math.min(82, x));
        }
        if (y < 30 || y > 76) {
          vy *= -0.22;
          y = Math.max(30, Math.min(76, y));
        }
        if (
          flightReady &&
          !dockedRef.current &&
          Math.hypot(x - 76, y - 44) < 14.5
        ) {
          dockedRef.current = true;
          setAutoDocking(false);
          setDocked(true);
          setLesson({
            title: "Docked at ISS",
            text: "Small steady moves brought the rocket to the station.",
          });
          if (window.__narration) {
            window.__narration.play("game_pilot_docked.mp3");
          }
          playKidSound("chime");
        }
        const angleTarget =
          dockingAssist || dockedRef.current
            ? 174
            : steer * 9 + wobble * 38 - thrust * 3;
        return {
          ...current,
          x,
          y,
          vx,
          vy,
          angle: current.angle + (angleTarget - current.angle) * 0.13 * dt,
        };
      });
      frameRef.current.raf = requestAnimationFrame(tick);
    };
    frameRef.current.raf = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(frameRef.current.raf);
      frameRef.current.last = 0;
    };
  }, [
    autoDocking,
    engineReady,
    flightReady,
    throttle,
    steer,
    systems.radar,
    systems.stabilizer,
  ]);

  useEffect(() => {
    const onKey = (event) => {
      if (
        !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)
      )
        return;
      event.preventDefault();
      if (event.key === "ArrowLeft") setSteer(-1);
      if (event.key === "ArrowRight") setSteer(1);
      if (event.key === "ArrowUp")
        setThrottle((value) => Math.min(100, value + 10));
      if (event.key === "ArrowDown")
        setThrottle((value) => Math.max(0, value - 10));
    };
    const onKeyUp = (event) => {
      if (event.key === "ArrowLeft" || event.key === "ArrowRight") setSteer(0);
    };
    window.addEventListener("keydown", onKey);
    window.addEventListener("keyup", onKeyUp);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("keyup", onKeyUp);
    };
  }, []);

  const partIsUnlocked = (id) => {
    if (id === "battery") return true;
    const index = engineParts.findIndex((part) => part.id === id);
    if (index > 0) return systems[engineParts[index - 1].id];
    return engineReady;
  };

  const toggleEnginePart = (part, event) => {
    if (systems[part.id]) {
      if (event?.currentTarget) event.currentTarget.blur();
      setLesson({
        title: part.label,
        text: part.label + " is already online. Keep building the path.",
      });
      playKidSound("boop");
      return;
    }
    if (!partIsUnlocked(part.id)) {
      if (event?.currentTarget) event.currentTarget.blur();
      const needed = nextEnginePart || engineParts[0];
      setLesson({
        title: "Follow the glow",
        text:
          "Tap the glowing " +
          needed.label +
          " button first. Then the next rocket part wakes up.",
      });
      playKidSound("boop");
      return;
    }
    setSystems((current) => ({ ...current, [part.id]: !current[part.id] }));
    setLesson({ title: part.label, text: part.hint });
    if (window.__narration) {
      const audioId = part.id.replace(/([A-Z])/g, "_$1").toLowerCase();
      window.__narration.play("game_pilot_" + audioId + ".mp3");
    }
    playKidSound("chime");
  };

  const toggleSupportPart = (part) => {
    if (!engineReady) {
      setLesson({
        title: "Engine first",
        text: "Build the main engine path before adding pilot tools.",
      });
      if (window.__narration) {
        window.__narration.play("game_pilot_engine_first.mp3");
      }
      playKidSound("boop");
      return;
    }
    if (systems[part.id]) {
      setLesson({
        title: part.label,
        text: part.label + " is already helping the rocket fly steady.",
      });
      playKidSound("boop");
      return;
    }
    setSystems((current) => ({ ...current, [part.id]: !current[part.id] }));
    setLesson({ title: part.label, text: part.hint });
    if (window.__narration) {
      const audioId = part.id.replace(/([A-Z])/g, "_$1").toLowerCase();
      window.__narration.play("game_pilot_" + audioId + ".mp3");
    }
    playKidSound("boop");
  };

  const setThrottleWithLesson = (value) => {
    const next = Number(value);
    const prev = throttle;
    setThrottle(next);
    if (!engineReady && next > 8 && prev <= 8) {
      setLesson({
        title: "Throttle is waiting",
        text: "The handle can move, but thrust starts after the engine is built.",
      });
      if (window.__narration) {
        window.__narration.play("game_pilot_throttle_waiting.mp3");
      }
    } else if (engineReady && next >= 45 && prev < 45) {
      setLesson({
        title: "Thrust!",
        text: "Hot gas shoots backward, so the rocket moves forward.",
      });
      if (window.__narration) {
        window.__narration.play("game_pilot_thrust.mp3");
      }
    }
  };

  const setThrottleFromStick = (event) => {
    const rect =
      throttleStickRef.current &&
      throttleStickRef.current.getBoundingClientRect();
    if (!rect) return;
    const y = Math.max(0, Math.min(rect.height, event.clientY - rect.top));
    const next = Math.round((1 - y / rect.height) * 100);
    setThrottleWithLesson(next);
  };

  const startThrottleStick = (event) => {
    event.preventDefault();
    setThrottleFromStick(event);
    try {
      event.currentTarget.setPointerCapture(event.pointerId);
    } catch {}
  };

  const resetFlightRun = () => {
    dockedRef.current = false;
    setDocked(false);
    setAutoDocking(false);
    setSteer(0);
    setThrottle(0);
    setShip({ x: 38, y: 58, vx: 0, vy: 0, angle: -4 });
    setLesson({
      title: "Ready again",
      text: "The engine stays built. Press Power up to fly another docking run.",
    });
    if (window.__narration) {
      window.__narration.play("game_pilot_try_again.mp3");
    }
    playKidSound("boop");
  };

  const startAutoDock = () => {
    if (!engineReady) {
      setLesson({
        title: "Engine first",
        text: "Build the engine path, then the dock button can guide the rocket.",
      });
      if (window.__narration) {
        window.__narration.play("game_pilot_engine_first.mp3");
      }
      playKidSound("boop");
      return;
    }
    dockedRef.current = false;
    setDocked(false);
    setAutoDocking(true);
    setSteer(0);
    setThrottle(88);
    setLesson({
      title: "Docking!",
      text: "The window zooms in. Tiny gentle moves line the rocket up with the ISS.",
    });
    if (window.__narration) {
      window.__narration.play("game_pilot_power_up.mp3");
    }
    playKidSound("chime");
  };

  return (
    <section
      className="pilot-level pilot-engineering pilot-school-redesign"
      aria-label="Spaceship control board game"
    >
      <Starfield count={170} />
      <button className="pilot-back" onClick={onExit}>
        Back
      </button>
      <button
        className={"pilot-mute " + (pilotSoundOn ? "on" : "off")}
        onClick={() => setPilotSoundOn(!pilotSoundOn)}
        aria-label={pilotSoundOn ? "Mute voice" : "Unmute voice"}
        title={pilotSoundOn ? "Mute voice" : "Unmute voice"}
      >
        <span aria-hidden="true">{pilotSoundOn ? "🔊" : "🔇"}</span>
        <strong>{pilotSoundOn ? "Voice on" : "Voice off"}</strong>
      </button>

      <div
        className={
          "pilot-front-view " +
          (engineReady ? "engine-ready " : "") +
          (flightReady ? "boost-on " : "") +
          (autoDocking || docked ? "docking-zoom" : "")
        }
        style={{
          "--pilot-thrust": engineReady ? throttle / 100 : 0.02,
          "--pilot-drift-x":
            Math.max(-12, Math.min(12, (ship.vx || 0) * -14)) + "px",
          "--pilot-drift-y":
            Math.max(-12, Math.min(12, (ship.vy || 0) * -14)) + "px",
        }}
      >
        <div className="pilot-window-monitor left">
          <strong>Mission</strong>
          <span>{cockpitCue}</span>
        </div>
        <div className="pilot-window-monitor right">
          <strong>Power</strong>
          <span>{shipPower}%</span>
        </div>
        <div className="pilot-window-status" aria-label="Rocket systems online">
          {engineParts.map((part) => (
            <span
              key={part.id}
              className={
                systems[part.id]
                  ? "on"
                  : part.id === nextEnginePart?.id
                    ? "next"
                    : ""
              }
            >
              {systemLabels[part.id] || part.part}
            </span>
          ))}
          <span className={autoDocking || docked ? "on" : ""}>dock</span>
        </div>
        <div
          className={
            "pilot-docking-lane " + (systems.radar || autoDocking ? "on" : "")
          }
          aria-hidden="true"
        />
        <div
          className={
            "pilot-star-target iss-target " +
            (systems.radar || autoDocking ? "on" : "")
          }
        >
          <SafeAssetImage
            src={GENERATED_ASSETS.pilotIssTarget}
            alt=""
            context="Pilot:issTarget"
            fallbackText=""
          />
          <span>ISS</span>
        </div>
        <div
          className={
            "pilot-view-ship " +
            (engineReady ? "engine-ready " : "") +
            (flightReady && !autoDocking && !docked ? "boosting " : "") +
            (autoDocking || docked ? "backing-up" : "")
          }
          style={{
            left: ship.x + "%",
            top: ship.y + "%",
            transform:
              "translate(-50%, -50%) rotate(" +
              ship.angle +
              "deg) scale(" +
              (autoDocking || docked ? 1.24 : 1) +
              ")",
          }}
        >
          <SafeAssetImage
            src={GENERATED_ASSETS.pilotTrainingRocket}
            alt=""
            context="Pilot:trainingRocket"
            fallbackText=""
          />
          <span
            style={{
              opacity:
                engineReady && throttle > 10 && !autoDocking && !docked
                  ? Math.max(0.18, throttle / 100)
                  : 0,
            }}
          />
        </div>
        <div
          className={
            "pilot-docking-meter " +
            (engineReady ? "" : "hidden ") +
            (docked ? "docked" : "")
          }
          aria-label="Docking progress"
        >
          <span>
            {docked
              ? "Docked"
              : autoDocking
                ? "Auto dock"
                : flightReady
                  ? "Docking"
                  : "Waiting"}
          </span>
          <strong>{dockingProgress}%</strong>
          <i style={{ width: dockingProgress + "%" }} />
        </div>
      </div>

      <div className="pilot-control-board engineering-console">
        <div className="pilot-board-column mission engineering-brief">
          <div className="pilot-panel-title">
            <span>Rocket Lab</span>
            <i aria-hidden="true">
              {engineReady ? "Engine ready" : "Build order"}
            </i>
          </div>
          <div className="pilot-lesson powered">
            <strong>{currentGoal}</strong>
            <span>{lesson.text}</span>
          </div>
          <div className="pilot-engine-strip" aria-label="Engine start order">
            {engineParts.map((part) => (
              <span
                key={part.id}
                className={
                  systems[part.id]
                    ? "on"
                    : part.id === nextEnginePart?.id
                      ? "next"
                      : ""
                }
              >
                <i>{part.short}</i>
                {part.label}
              </span>
            ))}
          </div>
        </div>

        <div className="pilot-board-column engineering-schematic">
          <div className="pilot-panel-title">
            <span>Engine Control Board</span>
            <i aria-hidden="true">Tap parts</i>
          </div>
          <div
            className="rocket-schematic pilot-board-image"
            aria-label="Rocket engine schematic"
            style={{
              "--pilot-board-bg":
                "url(" + GENERATED_ASSETS.pilotControlBoard + ")",
            }}
          >
            {engineParts.map((part, index) => (
              <button
                key={part.id}
                className={
                  "rocket-schematic-part " +
                  (systems[part.id] ? "on " : "") +
                  (part.id === nextEnginePart?.id ? "next" : "")
                }
                onClick={(event) => toggleEnginePart(part, event)}
              >
                <span className={"schematic-icon " + part.part} />
                <strong>{part.label}</strong>
                <em>
                  {systems[part.id]
                    ? "online"
                    : part.id === nextEnginePart?.id
                      ? "tap me"
                      : "waiting"}
                </em>
                {index < engineParts.length - 1 && (
                  <b
                    aria-hidden="true"
                    className={systems[part.id] ? "on" : ""}
                  />
                )}
              </button>
            ))}
          </div>
        </div>

        <div className="pilot-board-column flight-controls-simple">
          <div className="pilot-panel-title">
            <span>Pilot Controls</span>
            <i aria-hidden="true">Big handles</i>
          </div>
          <div className="pilot-throttle big-throttle throttle-joystick">
            <span>Throttle</span>
            <div
              ref={throttleStickRef}
              className="throttle-stick-track"
              role="slider"
              aria-label="Throttle"
              aria-valuemin="0"
              aria-valuemax="100"
              aria-valuenow={throttle}
              tabIndex="0"
              onPointerDown={startThrottleStick}
              onPointerMove={(event) => {
                if (event.buttons === 1) setThrottleFromStick(event);
              }}
              onKeyDown={(event) => {
                if (event.key === "ArrowUp") {
                  event.preventDefault();
                  setThrottleWithLesson(Math.min(100, throttle + 10));
                }
                if (event.key === "ArrowDown") {
                  event.preventDefault();
                  setThrottleWithLesson(Math.max(0, throttle - 10));
                }
              }}
            >
              <i className="throttle-stick-rail" />
              <b
                className="throttle-stick-fill"
                style={{ height: throttle + "%" }}
              />
              <button
                type="button"
                className="throttle-stick-handle"
                style={{ bottom: throttle + "%" }}
                tabIndex="-1"
                aria-hidden="true"
              />
            </div>
          </div>
          <div className="pilot-meter-row" aria-label="Rocket power meter">
            <span>Rocket power</span>
            <strong>{shipPower}%</strong>
            <i style={{ width: shipPower + "%" }} />
          </div>
          <div className="pilot-steer-pad" aria-label="Steer rocket">
            <button
              onPointerDown={() => {
                setSteer(-1);
                speakSteer("left");
              }}
              onPointerUp={() => setSteer(0)}
              onPointerCancel={() => setSteer(0)}
              onPointerLeave={() => setSteer(0)}
            >
              Left
            </button>
            {engineReady && !flightReady && !autoDocking && !docked ? (
              <span className="pilot-power-hint-arrow" aria-hidden="true">
                ➜
              </span>
            ) : null}
            <button
              disabled={docked}
              onClick={() => {
                if (docked) {
                  return;
                }
                setSteer(0);
                setThrottle(engineReady ? 84 : 0);
                setLesson(
                  engineReady
                    ? {
                        title: "Power up",
                        text: "The rocket moves toward the station. Tap left or right for small pilot corrections.",
                      }
                    : {
                        title: "Engine first",
                        text: "Build the engine path, then the power handle will work.",
                      },
                );
                if (window.__narration) {
                  window.__narration.play(
                    engineReady
                      ? "game_pilot_power_up.mp3"
                      : "game_pilot_engine_first.mp3",
                  );
                }
                playKidSound("chime");
              }}
            >
              {docked ? "Docked" : "Power up"}
            </button>
            <button
              onPointerDown={() => {
                setSteer(1);
                speakSteer("right");
              }}
              onPointerUp={() => setSteer(0)}
              onPointerCancel={() => setSteer(0)}
              onPointerLeave={() => setSteer(0)}
            >
              Right
            </button>
          </div>
          <button
            className={"pilot-dock-button " + (autoDocking ? "active" : "")}
            onClick={docked ? resetFlightRun : startAutoDock}
          >
            {docked ? "Fly again" : autoDocking ? "Docking..." : "Dock ISS"}
          </button>
          <div className="support-toggle-row">
            {supportParts.map((part) => (
              <button
                key={part.id}
                className={systems[part.id] ? "on" : ""}
                onClick={() => toggleSupportPart(part)}
              >
                <strong>{part.label}</strong>
                <span>
                  {systems[part.id]
                    ? "online"
                    : engineReady
                      ? part.id === "radar"
                        ? "show path"
                        : "steady ship"
                      : "add after engine"}
                </span>
              </button>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
