// solar-sail-skimmer.jsx
// Solar Sail Skimmer: preschool photon-push experiment with a generated raster sail craft.

const SOLAR_SAIL_SKIMMER_ASSET =
  "data/generated-assets/physics/solar-sail-skimmer.png?v=solar-sail-skimmer-20260601";

const SOLAR_SAIL_LIGHTS = [
  { id: "soft", label: "Soft light", force: 1, beam: "gentle beam" },
  { id: "bright", label: "Bright light", force: 2, beam: "steady beam" },
  { id: "sunny", label: "Sunny blast", force: 3, beam: "big beam" },
];

const SOLAR_SAIL_ANGLES = [
  { id: "peek", label: "Tiny catch", catch: 1, note: "The sail catches a little light." },
  { id: "tilt", label: "Half catch", catch: 2, note: "The sail catches more light." },
  { id: "open", label: "Wide catch", catch: 3, note: "The sail catches the most light." },
];

const SOLAR_SAIL_CHALLENGES = [
  {
    id: "short",
    title: "Reach the close sparkle.",
    target: "small glide",
    min: 2,
    max: 3,
  },
  {
    id: "middle",
    title: "Reach the middle sparkle.",
    target: "middle glide",
    min: 4,
    max: 5,
  },
  {
    id: "far",
    title: "Reach the far sparkle.",
    target: "big glide",
    min: 6,
    max: 9,
  },
];

function SolarSailSkimmerLevel({ onExit }) {
  const [stageIndex, setStageIndex] = useState(0);
  const [lightId, setLightId] = useState("bright");
  const [angleId, setAngleId] = useState("tilt");
  const [launched, setLaunched] = useState(false);
  const [message, setMessage] = useState("Choose light. Open the sail. Then shine.");
  const [wins, setWins] = useState(0);
  const timerRef = useRef(null);
  const celebrationShownRef = useRef(false);
  const challenge = SOLAR_SAIL_CHALLENGES[stageIndex] || SOLAR_SAIL_CHALLENGES[0];
  const light = SOLAR_SAIL_LIGHTS.find((item) => item.id === lightId) || SOLAR_SAIL_LIGHTS[0];
  const angle = SOLAR_SAIL_ANGLES.find((item) => item.id === angleId) || SOLAR_SAIL_ANGLES[0];
  const pushScore = light.force * angle.catch;
  const glidePercent = Math.min(94, 18 + pushScore * 10);
  const targetPercent = Math.min(90, 18 + challenge.min * 10);
  const done = wins >= SOLAR_SAIL_CHALLENGES.length;
  const pushStatus =
    pushScore < challenge.min
      ? { id: "low", label: "Needs more push" }
      : pushScore > challenge.max
        ? { id: "high", label: "Too much push" }
        : { id: "ready", label: "Ready to shine" };

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

  useEffect(() => {
    if (!done || celebrationShownRef.current) return;
    celebrationShownRef.current = true;
    window.SpaceExplorerFoundation?.celebrateGameFinish?.({
      gameId: "solar-sail-skimmer",
      emoji: "☀️",
      title: "Solar sail scientist!",
      message: "You used light to push a shiny sail.",
    });
  }, [done]);

  const chooseLight = (id) => {
    setLightId(id);
    setLaunched(false);
    setMessage("Light strength changed. Try a shine.");
    playKidSound("boop");
  };

  const chooseAngle = (id) => {
    setAngleId(id);
    setLaunched(false);
    setMessage("Sail angle changed. Catch the beam.");
    playKidSound("boop");
  };

  const shine = () => {
    window.clearTimeout(timerRef.current);
    const success = pushScore >= challenge.min && pushScore <= challenge.max;
    const nextWins = Math.min(SOLAR_SAIL_CHALLENGES.length, wins + 1);
    const finishedAll = nextWins >= SOLAR_SAIL_CHALLENGES.length;
    setLaunched(true);
    if (success) {
      playKidSound("chime");
      setMessage(`Nice ${challenge.target}! Light pushed the sail just right.`);
      timerRef.current = window.setTimeout(() => {
        setWins(nextWins);
        setStageIndex((current) =>
          finishedAll ? current : Math.min(SOLAR_SAIL_CHALLENGES.length - 1, current + 1),
        );
        setLaunched(false);
        setMessage(
          finishedAll
            ? "All sparkle gates reached. Light pushed the sail beautifully."
            : "New sparkle target. Change one thing and shine again.",
        );
      }, 900);
    } else {
      playKidSound("pop");
      setMessage(
        pushScore < challenge.min
          ? "Too tiny. Catch more light or use a brighter beam."
          : "Too far. Catch less light or use a softer beam.",
      );
    }
  };

  const reset = () => {
    window.clearTimeout(timerRef.current);
    celebrationShownRef.current = false;
    setStageIndex(0);
    setWins(0);
    setLaunched(false);
    setMessage("Choose light. Open the sail. Then shine.");
    playKidSound("boop");
  };

  return (
    <section className="solar-sail-level" aria-label="Solar sail skimmer game">
      <Starfield count={220} />
      <button className="planet-sort-back" onClick={onExit}>
        ← Back to planets
      </button>
      <div className="solar-sail-shell">
        <div className="solar-sail-copy">
          <span>Solar Sail Skimmer</span>
          <h1>Use light to push the sail.</h1>
          <p>Light taps the shiny sail and makes the skimmer glide.</p>
          <div className="solar-sail-card" role="status" aria-live="polite">
            <strong>{done ? "All sparkle gates reached!" : challenge.title}</strong>
            <span>{message}</span>
          </div>
          <div className="solar-sail-meter" aria-label="Photon push meter">
            <strong>Photon push</strong>
            <i>
              <b style={{ width: `${(pushScore / 9) * 100}%` }} />
            </i>
            <small>
              {light.beam} + {angle.label.toLowerCase()}
            </small>
          </div>
          <div className="solar-sail-push-guide" aria-label="Solar sail target guide">
            <span>
              <small>Target</small>
              <strong>
                {challenge.min}-{challenge.max}
              </strong>
            </span>
            <span>
              <small>Your push</small>
              <strong>{pushScore}</strong>
            </span>
            <span className={`solar-sail-push-${pushStatus.id}`}>
              <small>Result</small>
              <strong>{pushStatus.label}</strong>
            </span>
          </div>
          {done ? (
            <div className="solar-sail-actions">
              <button onClick={reset}>Play again</button>
              <button onClick={onExit}>Done</button>
            </div>
          ) : null}
        </div>

        <div
          className={`solar-sail-stage ${launched ? "launched" : ""}`}
          style={{
            "--sail-glide": `${glidePercent}%`,
            "--target-stop": `${targetPercent}%`,
            "--sail-angle": `${(angle.catch - 2) * -8}deg`,
          }}
        >
          <div className="solar-sail-sun" aria-hidden="true" />
          <div className="solar-sail-beam" aria-hidden="true" />
          <div className="solar-sail-target" aria-hidden="true">
            <span />
          </div>
          <SafeAssetImage
            className="solar-sail-craft"
            src={SOLAR_SAIL_SKIMMER_ASSET}
            alt=""
            context="SolarSailSkimmer:craft"
            fallbackText=""
          />
        </div>

        <div className="solar-sail-controls" aria-label="Solar sail controls">
          <div>
            <strong>Light</strong>
            {SOLAR_SAIL_LIGHTS.map((item) => (
              <button
                key={item.id}
                className={lightId === item.id ? "selected" : ""}
                onClick={() => chooseLight(item.id)}
                aria-pressed={lightId === item.id}
              >
                {item.label}
              </button>
            ))}
          </div>
          <div>
            <strong>Sail angle</strong>
            {SOLAR_SAIL_ANGLES.map((item) => (
              <button
                key={item.id}
                className={angleId === item.id ? "selected" : ""}
                onClick={() => chooseAngle(item.id)}
                aria-pressed={angleId === item.id}
              >
                {item.label}
                <small>{item.note}</small>
              </button>
            ))}
          </div>
          <button className="solar-sail-shine" onClick={shine} disabled={done}>
            Shine light
          </button>
        </div>
      </div>
    </section>
  );
}
