// AGENT_TARGET: spacecraft-trajectory — pick two planets, see Hohmann transfer arc + travel time

const TRAJ_PLANETS = [
  { id: "mercury", name: "Mercury", au: 0.387, color: "#b5b5b5" },
  { id: "venus", name: "Venus", au: 0.723, color: "#f5c842" },
  { id: "earth", name: "Earth", au: 1.0, color: "#4c9eff" },
  { id: "mars", name: "Mars", au: 1.524, color: "#e05c35" },
  { id: "jupiter", name: "Jupiter", au: 5.203, color: "#c8a46e" },
  { id: "saturn", name: "Saturn", au: 9.537, color: "#e8d59a" },
  { id: "uranus", name: "Uranus", au: 19.19, color: "#7de8e8" },
  { id: "neptune", name: "Neptune", au: 30.07, color: "#4763ff" },
];

const TRAJ_MAX_AU = 30.07;
const TRAJ_ARC_STEPS = 72;
const TRAJ_ROCKET_MS = 3000; // ms for one rocket lap along the arc

const TRAJ_FACTS = {
  mercury:
    "Mercury zips around the Sun in just 88 Earth days — the shortest year!",
  venus: "Venus is hotter than Mercury even though it's farther from the Sun.",
  earth: "Home sweet home — the only planet with liquid oceans on its surface.",
  mars: "NASA's Perseverance rover took about 7 months to reach Mars in 2021.",
  jupiter: "Jupiter is so huge that 1,300 Earths could fit inside it.",
  saturn: "Saturn's rings are made of billions of ice and rock chunks.",
  uranus: "Uranus spins on its side — its axis is tilted nearly 98 degrees!",
  neptune: "Voyager 2 took 12 years to reach Neptune after launching in 1977.",
};

// Fixed launch angle so the arc always sweeps visually over the top of the canvas.
const TRAJ_START_ANGLE = Math.PI * 1.15;

// Draw one frame of the trajectory visualizer.
// AGENT_TARGET: spacecraft-trajectory — canvas frame draw for orbit arc + rocket
function drawTrajFrame(ctx, W, H, fromIdx, toIdx, rocketT) {
  const cx = W / 2,
    cy = H / 2;
  const R = Math.min(W, H) / 2;

  const auToPx = (au) =>
    typeof tmAuToPx === "function"
      ? tmAuToPx(au, R, TRAJ_MAX_AU)
      : R * 0.88 * Math.sqrt(au / TRAJ_MAX_AU);

  // Background
  ctx.fillStyle = "#060418";
  ctx.fillRect(0, 0, W, H);

  // Stars (deterministic)
  ctx.fillStyle = "rgba(255,255,255,0.38)";
  for (let i = 0; i < 65; i++) {
    ctx.fillRect(
      Math.floor(((i * 137.508) % 1) * W),
      Math.floor(((i * 97.331) % 1) * H),
      1,
      1,
    );
  }

  // Orbit rings (all planets)
  TRAJ_PLANETS.forEach((p) => {
    const r = auToPx(p.au);
    ctx.strokeStyle = "rgba(160,190,255,0.10)";
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    ctx.stroke();
  });

  // Sun
  const sg = ctx.createRadialGradient(cx, cy, 0, cx, cy, 16);
  sg.addColorStop(0, "#fff9d0");
  sg.addColorStop(0.55, "#ffe455");
  sg.addColorStop(1, "rgba(255,220,60,0)");
  ctx.beginPath();
  ctx.arc(cx, cy, 16, 0, Math.PI * 2);
  ctx.fillStyle = sg;
  ctx.fill();

  const from = TRAJ_PLANETS[fromIdx];
  const to = TRAJ_PLANETS[toIdx];
  const inward = from.au > to.au;

  // inner/outer planet for Hohmann math
  const innerP = inward ? to : from;
  const outerP = inward ? from : to;
  const innerPx = auToPx(innerP.au);
  const outerPx = auToPx(outerP.au);

  // Arc: from perihelion (inner planet) to aphelion (outer planet)
  const arcPts =
    typeof tmHohmannArc === "function"
      ? tmHohmannArc(cx, cy, innerPx, outerPx, TRAJ_START_ANGLE, TRAJ_ARC_STEPS)
      : [];

  // Positions of the two selected planets
  const innerPos = arcPts[0];
  const outerPos = arcPts[arcPts.length - 1];
  const fromPos = inward ? outerPos : innerPos;
  const toPos = inward ? innerPos : outerPos;

  // Other planet dots at fixed angles around their orbits
  TRAJ_PLANETS.forEach((p, idx) => {
    if (idx === fromIdx || idx === toIdx) return;
    const r = auToPx(p.au);
    const angle = TRAJ_START_ANGLE + 0.55 + idx * 0.48;
    const px = cx + r * Math.cos(angle);
    const py = cy + r * Math.sin(angle);
    ctx.beginPath();
    ctx.arc(px, py, 3, 0, Math.PI * 2);
    ctx.fillStyle = p.color;
    ctx.fill();
  });

  // Transfer arc — glow + solid line
  if (arcPts.length > 1) {
    ctx.save();
    ctx.shadowColor = "#50dfff";
    ctx.shadowBlur = 10;
    ctx.strokeStyle = "rgba(80,215,255,0.75)";
    ctx.lineWidth = 2.5;
    ctx.beginPath();
    ctx.moveTo(arcPts[0].x, arcPts[0].y);
    for (let i = 1; i < arcPts.length; i++)
      ctx.lineTo(arcPts[i].x, arcPts[i].y);
    ctx.stroke();
    ctx.restore();
  }

  // Highlight from-planet
  if (fromPos) {
    ctx.save();
    ctx.shadowColor = from.color;
    ctx.shadowBlur = 14;
    ctx.beginPath();
    ctx.arc(fromPos.x, fromPos.y, 7, 0, Math.PI * 2);
    ctx.fillStyle = from.color;
    ctx.fill();
    ctx.restore();
    ctx.fillStyle = "rgba(255,255,255,0.72)";
    ctx.font = "bold 11px Inter, sans-serif";
    ctx.textAlign = "center";
    ctx.fillText(from.name, fromPos.x, fromPos.y + 19);
  }

  // Highlight to-planet
  if (toPos) {
    ctx.save();
    ctx.shadowColor = to.color;
    ctx.shadowBlur = 14;
    ctx.beginPath();
    ctx.arc(toPos.x, toPos.y, 7, 0, Math.PI * 2);
    ctx.fillStyle = to.color;
    ctx.fill();
    ctx.restore();
    ctx.fillStyle = "rgba(255,255,255,0.72)";
    ctx.font = "bold 11px Inter, sans-serif";
    ctx.textAlign = "center";
    ctx.fillText(to.name, toPos.x, toPos.y + 19);
  }

  // Rocket along arc (inward trips traverse arc in reverse)
  if (arcPts.length > 1) {
    const t = inward ? 1 - rocketT : rocketT;
    const rawIdx = t * (arcPts.length - 1);
    const i0 = Math.floor(rawIdx);
    const frac = rawIdx - i0;
    const p0 = arcPts[Math.min(i0, arcPts.length - 1)];
    const p1 = arcPts[Math.min(i0 + 1, arcPts.length - 1)];
    const rx = p0.x + (p1.x - p0.x) * frac;
    const ry = p0.y + (p1.y - p0.y) * frac;
    const rAngle =
      Math.atan2(p1.y - p0.y, p1.x - p0.x) + (inward ? Math.PI : 0);
    ctx.save();
    ctx.translate(rx, ry);
    ctx.rotate(rAngle);
    ctx.font = "18px serif";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText("🚀", 0, 0);
    ctx.restore();
  }
}

function SpacecraftTrajectory({ onClose }) {
  // AGENT_TARGET: spacecraft-trajectory — SpacecraftTrajectory main component
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const t0Ref = React.useRef(null);

  const [fromIdx, setFromIdx] = React.useState(2); // Earth
  const [toIdx, setToIdx] = React.useState(3); // Mars
  const [rocketT, setRocketT] = React.useState(0);

  // Stats derived from selection
  const from = TRAJ_PLANETS[fromIdx];
  const to = TRAJ_PLANETS[toIdx];
  const days =
    typeof tmHohmannDays === "function" && fromIdx !== toIdx
      ? Math.round(tmHohmannDays(from.au, to.au))
      : 0;
  const gapMKm =
    typeof tmOrbitGapMKm === "function" && fromIdx !== toIdx
      ? Math.round(tmOrbitGapMKm(from.au, to.au))
      : 0;
  const years = days > 0 ? (days / 365.25).toFixed(1) : "0";
  const fact = TRAJ_FACTS[to.id] || "";
  const transferDirection = to.au > from.au ? "Outward transfer" : "Inward transfer";
  const transferStage =
    rocketT < 0.18
      ? "Launch burn"
      : rocketT > 0.82
        ? "Arrive and slow"
        : "Coast on oval";
  const transferClue =
    transferStage === "Launch burn"
      ? "A short push starts the path."
      : transferStage === "Arrive and slow"
        ? "A second push helps match the new orbit."
        : "Most of the trip is coasting along gravity's curve.";

  // Animation loop
  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const W = canvas.width,
      H = canvas.height;
    const ctx = canvas.getContext("2d");

    t0Ref.current = null;

    const tick = (now) => {
      if (!t0Ref.current) t0Ref.current = now;
      const elapsed = (now - t0Ref.current) % TRAJ_ROCKET_MS;
      const t = elapsed / TRAJ_ROCKET_MS;
      setRocketT(t);
      drawTrajFrame(ctx, W, H, fromIdx, toIdx, t);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [fromIdx, toIdx]);

  const selectFrom = (idx) => {
    if (idx === toIdx) return;
    setFromIdx(idx);
  };
  const selectTo = (idx) => {
    if (idx === fromIdx) return;
    setToIdx(idx);
  };

  return (
    <div
      className="traj-overlay"
      role="dialog"
      aria-label="Spacecraft Trajectory Planner"
    >
      <button className="traj-close" onClick={onClose} aria-label="Close">
        ✕
      </button>
      <h2 className="traj-title">🚀 Mission Trajectory Planner</h2>
      <p className="traj-subtitle">
        Pick two planets to see the shortest flight path!
      </p>

      <canvas
        ref={canvasRef}
        className="traj-canvas"
        width={340}
        height={280}
        aria-hidden="true"
      />

      <div className="traj-selector-group">
        <div className="traj-selector-label">Launch from</div>
        <div className="traj-planet-row">
          {TRAJ_PLANETS.map((p, idx) => (
            <button
              key={p.id}
              className={`traj-planet-btn ${idx === fromIdx ? "traj-selected-from" : ""} ${idx === toIdx ? "traj-disabled" : ""}`}
              onClick={() => selectFrom(idx)}
              disabled={idx === toIdx}
              style={{ "--traj-color": p.color }}
              title={p.name}
            >
              {p.name.slice(0, 3)}
            </button>
          ))}
        </div>
      </div>

      <div className="traj-selector-group">
        <div className="traj-selector-label">Fly to</div>
        <div className="traj-planet-row">
          {TRAJ_PLANETS.map((p, idx) => (
            <button
              key={p.id}
              className={`traj-planet-btn ${idx === toIdx ? "traj-selected-to" : ""} ${idx === fromIdx ? "traj-disabled" : ""}`}
              onClick={() => selectTo(idx)}
              disabled={idx === fromIdx}
              style={{ "--traj-color": p.color }}
              title={p.name}
            >
              {p.name.slice(0, 3)}
            </button>
          ))}
        </div>
      </div>

      {fromIdx !== toIdx && (
        <div className="traj-stats">
          <div className="traj-transfer-cue">
            <div className="traj-transfer-head">
              <span>{transferDirection}</span>
              <strong>{transferStage}</strong>
            </div>
            <div className="traj-transfer-rail" aria-hidden="true">
              <i style={{ width: `${Math.round(rocketT * 100)}%` }} />
            </div>
            <p>{transferClue}</p>
          </div>
          <div className="traj-stat">
            <span className="traj-stat-label">Travel time</span>
            <span className="traj-stat-value">
              {days < 365 ? `~${days} days` : `~${years} years (${days} days)`}
            </span>
          </div>
          <div className="traj-stat">
            <span className="traj-stat-label">Orbit gap</span>
            <span className="traj-stat-value">
              ~{gapMKm.toLocaleString()} million km
            </span>
          </div>
          <p className="traj-fact">💡 {fact}</p>
        </div>
      )}
    </div>
  );
}
