// quiz-mission-control.jsx
// Mission Control: toggle the right switches in sequence (MissionControlLevel).

const MISSION_SWITCHES = [
  {
    id: "power",
    label: "Power",
    fact: "Power wakes up the spacecraft computers.",
    path: "Energy wakes the computers.",
    color: "#ffd66b",
  },
  {
    id: "radio",
    label: "Radio",
    fact: "Radio signals carry voices between Earth and space.",
    path: "Signals travel to Earth.",
    color: "#7ee7ff",
  },
  {
    id: "cooling",
    label: "Cooling",
    fact: "Cooling loops move heat away from busy machines.",
    path: "Heat moves out and away.",
    color: "#8dffb2",
  },
  {
    id: "lights",
    label: "Lights",
    fact: "Docking lights help pilots see where to go.",
    path: "Light shows the safe path.",
    color: "#ffb1d4",
  },
];

function MissionControlLevel({ onExit }) {
  const [step, setStep] = useState(0);
  const [online, setOnline] = useState([]);
  const [pickedId, setPickedId] = useState(null);
  const [message, setMessage] = useState("Turn on the glowing switch.");
  const feedbackTimerRef = useRef(null);
  const switchLockRef = useRef(false);
  const celebrationShownRef = useRef(false);
  const done = online.length === MISSION_SWITCHES.length;
  const target = MISSION_SWITCHES[step] || MISSION_SWITCHES[0];

  useEffect(() => {
    return () => window.clearTimeout(feedbackTimerRef.current);
  }, []);

  useEffect(() => {
    if (!done || celebrationShownRef.current) return;
    celebrationShownRef.current = true;
    window.SpaceExplorerFoundation?.celebrateGameFinish?.({
      gameId: "mission-control",
      emoji: "✅",
      title: "All systems go!",
      message: "Mission Control is ready for launch.",
    });
  }, [done]);

  const choose = (item) => {
    if (done) return;
    if (switchLockRef.current && item.id === target.id) return;
    window.clearTimeout(feedbackTimerRef.current);
    setPickedId(item.id);
    if (online.includes(item.id)) {
      setMessage(`${item.label} is already glowing. Tap ${target.label} next.`);
      playKidSound("boop");
      feedbackTimerRef.current = window.setTimeout(() => setPickedId(null), 700);
      return;
    }
    if (item.id !== target.id) {
      setMessage(`${item.label} waits its turn. Tap ${target.label}.`);
      playKidSound("pop");
      feedbackTimerRef.current = window.setTimeout(() => setPickedId(null), 850);
      return;
    }
    playKidSound("chime");
    switchLockRef.current = true;
    setOnline((current) =>
      current.includes(item.id) ? current : [...current, item.id],
    );
    setMessage(`${item.label} online! ${item.fact}`);
    feedbackTimerRef.current = window.setTimeout(() => {
      switchLockRef.current = false;
      setPickedId(null);
      setStep((current) => {
        const next = current + 1;
        if (next < MISSION_SWITCHES.length) {
          setMessage("Nice switch! Find the next glow.");
        } else {
          setMessage("Mission control is ready for launch.");
        }
        return next;
      });
    }, 900);
  };

  const reset = () => {
    window.clearTimeout(feedbackTimerRef.current);
    switchLockRef.current = false;
    setStep(0);
    setOnline([]);
    setPickedId(null);
    setMessage("Turn on the glowing switch.");
    celebrationShownRef.current = false;
  };

  return (
    <section className="mission-control-level" aria-label="Mission control switchboard game">
      <Starfield count={230} />
      <button className="planet-sort-back" onClick={onExit}>
        ← Back to planets
      </button>
      <div className="mission-control-shell">
        <div className="mission-control-copy">
          <span>Mission Control</span>
          <h1>{done ? "All systems go!" : `Turn on ${target.label}.`}</h1>
          <p>Spacecraft teams check each system before a safe launch.</p>
          <div className={`mission-control-message ${done ? "done" : ""}`} role="status" aria-live="polite">
            <strong>{message}</strong>
          </div>
          <div className="mission-control-progress" aria-label="Systems online">
            {MISSION_SWITCHES.map((item) => (
              <span key={item.id} className={online.includes(item.id) ? "on" : ""} />
            ))}
          </div>
          <div className="mission-system-path" aria-label="Spacecraft systems path">
            {MISSION_SWITCHES.map((item, index) => {
              const isOnline = online.includes(item.id);
              const isTarget = item.id === target.id && !done;
              return (
                <span
                  key={`path-${item.id}`}
                  className={`${isOnline ? "on " : ""}${isTarget ? "next" : ""}`}
                  style={{ "--switch-color": item.color }}
                >
                  <em>{index + 1}</em>
                  <strong>{item.label}</strong>
                  <small>{item.path}</small>
                </span>
              );
            })}
          </div>
          {done ? (
            <div className="mission-control-actions">
              <button onClick={reset}>Play again</button>
              <button onClick={onExit}>Done</button>
            </div>
          ) : null}
        </div>
        <div className="mission-switchboard">
          {MISSION_SWITCHES.map((item) => {
            const isOnline = online.includes(item.id);
            const isTarget = item.id === target.id && !done;
            const isWrong = pickedId === item.id && !isTarget;
            return (
              <button
                key={item.id}
                className={
                  "mission-switch " +
                  (isOnline ? "online " : "") +
                  (isTarget ? "target " : "") +
                  (isWrong ? "wrong" : "")
                }
                style={{ "--switch-color": item.color }}
                onClick={() => choose(item)}
              >
                <span className="mission-switch-light" />
                <strong>{item.label}</strong>
                <small>{isOnline ? "online" : isTarget ? "tap me" : "waiting"}</small>
              </button>
            );
          })}
        </div>
      </div>
    </section>
  );
}
