// quiz-rocket-cause.jsx
// Rocket Cause level: predict cause/effect of rocket controls (RocketCauseLevel).

const ROCKET_CAUSE_CONTROLS = [
  {
    id: "fuel",
    label: "Fuel",
    low: "tiny push",
    high: "big push",
    lesson: "More fuel makes a bigger upward push.",
  },
  {
    id: "fins",
    label: "Fins",
    low: "wobbly",
    high: "steady",
    lesson: "Fins help the rocket point straight.",
  },
  {
    id: "cargo",
    label: "Cargo",
    low: "light",
    high: "heavy",
    lesson: "Heavy cargo makes the rocket work harder.",
  },
];

const ROCKET_CAUSE_PROMPTS = [
  {
    text: "Try more fuel. What changes?",
    action: "Add fuel",
    setup: { fuel: 3, fins: 2, cargo: 1 },
  },
  {
    text: "Try fewer fins. What changes?",
    action: "Remove fins",
    setup: { fuel: 2, fins: 1, cargo: 1 },
  },
  {
    text: "Try heavy cargo. What changes?",
    action: "Add cargo",
    setup: { fuel: 2, fins: 2, cargo: 3 },
  },
];

const ROCKET_PREDICTION_STICKERS = [
  { id: "low", label: "Low", icon: "🌙" },
  { id: "medium", label: "Medium", icon: "⭐" },
  { id: "high", label: "High", icon: "☀️" },
];

function clampRocketCauseValue(value) {
  return Math.max(1, Math.min(3, value));
}

function rocketCauseResult(settings) {
  const push = settings.fuel * 34 - settings.cargo * 12;
  const height = Math.max(28, Math.min(100, push + 34));
  const steady = settings.fins * 28 - settings.fuel * 4 - settings.cargo * 3;
  const wobble = Math.max(0, Math.min(18, 22 - steady));
  const label =
    height > 78
      ? "High flight"
      : height < 48
        ? "Short hop"
        : "Medium flight";
  const tip =
    wobble > 10
      ? "The rocket wobbled. Add fins to make it steady."
      : settings.cargo >= 3 && settings.fuel <= 1
        ? "Heavy cargo needs more fuel."
        : settings.fuel >= 3
          ? "More fuel gave the rocket a stronger push."
          : "Change one control and watch the rocket respond.";
  return { height, wobble, label, tip };
}

function RocketCauseLevel({ onExit }) {
  const [settings, setSettings] = useState({ fuel: 2, fins: 2, cargo: 1 });
  const [promptIndex, setPromptIndex] = useState(0);
  const [prediction, setPrediction] = useState(null);
  const result = rocketCauseResult(settings);
  const currentPrompt = ROCKET_CAUSE_PROMPTS[promptIndex];
  const resultBand =
    result.label === "High flight"
      ? "high"
      : result.label === "Medium flight"
        ? "medium"
        : "low";
  const predictionMatched = prediction && prediction === resultBand;
  const predictionText = !prediction
    ? "Pick a flight sticker before you launch."
    : predictionMatched
      ? "Prediction star! You called it."
      : "Surprise data! Change a control and compare.";
  const forceReadouts = [
    {
      id: "fuel",
      label: "Push up",
      percent: (settings.fuel / 3) * 100,
      note: "Fuel pushes the rocket upward.",
    },
    {
      id: "cargo",
      label: "Weight down",
      percent: (settings.cargo / 3) * 100,
      note: "Cargo pulls the rocket back down.",
    },
    {
      id: "fins",
      label: "Stay straight",
      percent: (settings.fins / 3) * 100,
      note: "Fins help the rocket wobble less.",
    },
  ];

  const setControl = (id, delta) => {
    setSettings((current) => ({
      ...current,
      [id]: clampRocketCauseValue(current[id] + delta),
    }));
    playKidSound("boop");
  };

  const tryPrompt = () => {
    setSettings(currentPrompt.setup);
    playKidSound("chime");
  };

  const nextPrompt = () => {
    setPromptIndex((index) => (index + 1) % ROCKET_CAUSE_PROMPTS.length);
    playKidSound("boop");
  };

  return (
    <section
      className="rocket-cause-level"
      aria-label="Rocket cause and effect lab"
      style={{
        "--rocket-result-lift": `${Math.round(result.height * 2.6)}px`,
        "--rocket-result-settle": `${Math.round(result.height * 2.1)}px`,
        "--rocket-result-wobble": `${result.wobble}deg`,
        "--rocket-result-counter-wobble": `${-result.wobble}deg`,
        "--rocket-fuel": settings.fuel,
        "--rocket-fins": settings.fins,
        "--rocket-cargo": settings.cargo,
      }}
    >
      <Starfield count={240} />
      <button className="planet-sort-back" onClick={onExit}>
        ← Back to planets
      </button>
      <div className="rocket-cause-shell">
        <div className="rocket-cause-copy">
          <span>Rocket Lab</span>
          <h1>Change one thing. Watch what happens.</h1>
          <p>Fuel pushes. Fins steady. Cargo adds weight.</p>
          <div className="rocket-cause-prompt" role="status">
            <strong>{currentPrompt.text}</strong>
            <button onClick={tryPrompt}>{currentPrompt.action}</button>
            <button onClick={nextPrompt}>Next idea</button>
          </div>
          <div className="rocket-cause-result" aria-live="polite">
            <strong>{result.label}</strong>
            <span>{result.tip}</span>
          </div>
          <div className="rocket-force-balance" aria-label="Rocket force balance">
            <strong>Force balance</strong>
            {forceReadouts.map((readout) => (
              <span key={readout.id} className={readout.id}>
                <em>{readout.label}</em>
                <i>
                  <b style={{ width: `${readout.percent}%` }} />
                </i>
                <small>{readout.note}</small>
              </span>
            ))}
          </div>
          <div className="rocket-prediction-panel" aria-label="Flight prediction">
            <strong>Prediction stickers</strong>
            <div className="rocket-prediction-row">
              {ROCKET_PREDICTION_STICKERS.map((sticker) => (
                <button
                  key={sticker.id}
                  className={prediction === sticker.id ? "selected" : ""}
                  onClick={() => {
                    setPrediction(sticker.id);
                    playKidSound("pop");
                  }}
                  aria-pressed={prediction === sticker.id}
                >
                  <span>{sticker.icon}</span>
                  {sticker.label}
                </button>
              ))}
            </div>
            <em className={predictionMatched ? "matched" : ""}>
              {predictionText}
            </em>
          </div>
        </div>

        <div className="rocket-cause-stage" aria-hidden="true">
          <SafeAssetImage
            className="rocket-cause-bg"
            src={GENERATED_ASSETS.rocketLabStage}
            alt=""
            context="RocketCause:stage"
            fallbackText=""
          />
          <div className="rocket-cause-height">
            <span>high</span>
            <i />
            <span>low</span>
          </div>
          <div className="rocket-cause-readouts">
            <span className="rocket-cause-readout fuel">Fuel {settings.fuel}</span>
            <span className="rocket-cause-readout fins">Fins {settings.fins}</span>
            <span className="rocket-cause-readout cargo">Cargo {settings.cargo}</span>
          </div>
          <div className="rocket-cause-ship">
            <SafeAssetImage
              src={GENERATED_ASSETS.rocketLabRocket}
              alt=""
              context="RocketCause:rocket"
              fallbackText=""
            />
            <SafeAssetImage
              className="rocket-cause-flame"
              src={GENERATED_ASSETS.rocketLabExhaust}
              alt=""
              context="RocketCause:flame"
              fallbackText=""
            />
          </div>
        </div>

        <div className="rocket-cause-controls" aria-label="Rocket controls">
          {ROCKET_CAUSE_CONTROLS.map((control) => (
            <div
              className={`rocket-cause-control ${control.id}`}
              key={control.id}
              data-level={settings[control.id]}
            >
              <div>
                <strong>{control.label}</strong>
                <span>{control.lesson}</span>
              </div>
              <div className="rocket-cause-stepper">
                <button
                  onClick={() => setControl(control.id, -1)}
                  aria-label={`Less ${control.label}`}
                >
                  −
                </button>
                <span aria-live="polite">
                  {settings[control.id] === 1
                    ? control.low
                    : settings[control.id] === 3
                      ? control.high
                      : "middle"}
                </span>
                <button
                  onClick={() => setControl(control.id, 1)}
                  aria-label={`More ${control.label}`}
                >
                  +
                </button>
              </div>
              <div
                className="rocket-cause-meter"
                aria-hidden="true"
                style={{ "--meter-level": settings[control.id] }}
              >
                <i />
                <i />
                <i />
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
