// AGENT_TARGET: fuel-gauge-travel — fuel gauge mini-game teaching planetary travel costs by real AU distance

const FUEL_PLANETS = [
  { id: "mercury", name: "Mercury", au: 0.39, symbol: "☿", color: "#b0b0b0" },
  { id: "venus", name: "Venus", au: 0.72, symbol: "♀", color: "#f5c842" },
  { id: "earth", name: "Earth", au: 1.0, symbol: "🌍", color: "#4c9eff" },
  { id: "mars", name: "Mars", au: 1.52, symbol: "♂", color: "#e05c35" },
  { id: "jupiter", name: "Jupiter", au: 5.2, symbol: "♃", color: "#c8a46e" },
  { id: "saturn", name: "Saturn", au: 9.58, symbol: "♄", color: "#e8d59a" },
  { id: "uranus", name: "Uranus", au: 19.22, symbol: "⛢", color: "#7de8e8" },
  { id: "neptune", name: "Neptune", au: 30.05, symbol: "♆", color: "#4763ff" },
];

const FUEL_MAX = 100;
const AU_SCALE = 30.05; // Neptune = full tank burn

function FuelGaugeTravel({ onClose }) {
  // AGENT_TARGET: fuel-gauge-travel — FuelGaugeTravel main component
  const [originIdx, setOriginIdx] = React.useState(2); // Earth
  const [destIdx, setDestIdx] = React.useState(null);
  const [fuel, setFuel] = React.useState(FUEL_MAX);
  const [draining, setDraining] = React.useState(false);
  const [message, setMessage] = React.useState(null);
  const rafRef = React.useRef(null);
  const drainRef = React.useRef(null);

  React.useEffect(() => () => cancelAnimationFrame(rafRef.current), []);

  const fuelCostFor = (fromIdx, toIdx) => {
    const dist = Math.abs(FUEL_PLANETS[toIdx].au - FUEL_PLANETS[fromIdx].au);
    return Math.max(1, Math.round((dist / AU_SCALE) * FUEL_MAX));
  };

  const flyTo = (toIdx) => {
    if (draining || toIdx === originIdx) return;
    const cost = fuelCostFor(originIdx, toIdx);
    const current = drainRef.current !== null ? drainRef.current : fuel;
    if (current <= 0) {
      setMessage({ text: "Tank empty! Refuel first.", emoji: "⚠️" });
      return;
    }
    const actualCost = Math.min(cost, current);
    const start = current;
    const target = start - actualCost;
    const duration = 900 + actualCost * 18; // ms — longer trips animate longer
    const t0 = performance.now();
    setDestIdx(toIdx);
    setDraining(true);
    setMessage(null);
    drainRef.current = start;

    const tick = (now) => {
      const elapsed = now - t0;
      const pct = Math.min(1, elapsed / duration);
      const eased = 1 - Math.pow(1 - pct, 2); // ease-out
      const next = start - eased * actualCost;
      drainRef.current = next;
      setFuel(next);
      if (pct < 1) {
        rafRef.current = requestAnimationFrame(tick);
      } else {
        drainRef.current = target;
        setFuel(target);
        setDraining(false);
        setDestIdx(null);
        setOriginIdx(toIdx);
        if (target <= 0) {
          setMessage({
            text: "Tank empty! Tap Refuel to continue.",
            emoji: "⛽",
          });
        } else {
          const pname = FUEL_PLANETS[toIdx].name;
          setMessage({
            text: `Arrived at ${pname}! Used ${actualCost}% fuel.`,
            emoji: FUEL_PLANETS[toIdx].symbol,
          });
        }
      }
    };
    rafRef.current = requestAnimationFrame(tick);
  };

  const refuel = () => {
    cancelAnimationFrame(rafRef.current);
    drainRef.current = FUEL_MAX;
    setFuel(FUEL_MAX);
    setDraining(false);
    setDestIdx(null);
    setMessage({
      text: "Refuelled from the Sun's solar wind! ☀️",
      emoji: "☀️",
    });
  };

  const reset = () => {
    cancelAnimationFrame(rafRef.current);
    drainRef.current = FUEL_MAX;
    setFuel(FUEL_MAX);
    setDraining(false);
    setDestIdx(null);
    setOriginIdx(2);
    setMessage(null);
  };

  const fuelPct = Math.max(0, fuel / FUEL_MAX);
  const barColor =
    fuelPct > 0.5 ? "#4cff9e" : fuelPct > 0.25 ? "#ffd43b" : "#ff5252";
  const origin = FUEL_PLANETS[originIdx];

  return (
    <div
      className="fuel-travel-overlay"
      role="dialog"
      aria-modal="true"
      aria-label="Fuel Gauge Travel mini-game"
    >
      <button
        className="fuel-travel-close"
        onClick={onClose}
        aria-label="Close fuel travel game"
      >
        ✕
      </button>
      <h2 className="fuel-travel-title">⛽ Fuel Gauge Travel</h2>
      <p className="fuel-travel-subtitle">
        Tap a planet to fly there. Farther worlds burn <em>way</em> more fuel!
      </p>

      {/* Fuel bar */}
      <div
        className="fuel-bar-wrap"
        aria-label={`Fuel ${Math.round(fuelPct * 100)}%`}
      >
        <span className="fuel-bar-label">⛽ FUEL</span>
        <div className="fuel-bar-track">
          <div
            className="fuel-bar-fill"
            style={{
              width: `${fuelPct * 100}%`,
              background: barColor,
              transition: draining ? "none" : "width 0.3s",
            }}
          />
        </div>
        <span className="fuel-bar-pct">{Math.round(fuelPct * 100)}%</span>
      </div>

      {/* Current location */}
      <div className="fuel-location">
        <span className="fuel-location-label">Launching from:</span>
        <span className="fuel-location-name" style={{ color: origin.color }}>
          {origin.symbol} {origin.name}
        </span>
        <span className="fuel-location-au">{origin.au} AU from Sun</span>
      </div>

      {/* Planet buttons */}
      <div className="fuel-planet-grid">
        {FUEL_PLANETS.map((p, i) => {
          const isOrigin = i === originIdx;
          const isDest = i === destIdx;
          const cost = isOrigin ? 0 : fuelCostFor(originIdx, i);
          return (
            <button
              key={p.id}
              className={`fuel-planet-btn${isOrigin ? " fuel-origin" : ""}${isDest ? " fuel-dest" : ""}`}
              onClick={() => flyTo(i)}
              disabled={draining || isOrigin}
              style={{ "--planet-color": p.color }}
              title={
                isOrigin ? "You are here" : `Fly to ${p.name}: ${cost}% fuel`
              }
            >
              <span className="fuel-btn-symbol">{p.symbol}</span>
              <span className="fuel-btn-name">{p.name}</span>
              {isOrigin ? (
                <span className="fuel-btn-cost fuel-here">HERE</span>
              ) : (
                <>
                  <span className="fuel-btn-cost">{cost}%</span>
                  <span className="fuel-btn-cost-bar" aria-hidden="true">
                    <i style={{ width: `${Math.max(8, cost)}%` }} />
                  </span>
                </>
              )}
            </button>
          );
        })}
      </div>

      {/* Message */}
      {message && (
        <div className="fuel-message" aria-live="polite">
          <span>{message.emoji}</span> {message.text}
        </div>
      )}

      {/* Educational fact */}
      <div className="fuel-fact">
        <strong>Did you know?</strong> Neptune is 30× farther from the Sun than
        Earth. That's why the Voyager probe took <strong>12 years</strong> to
        reach it!
      </div>

      <div className="fuel-actions">
        {fuel <= 5 && (
          <button className="fuel-refuel-btn" onClick={refuel}>
            ☀️ Refuel
          </button>
        )}
        <button className="fuel-reset-btn" onClick={reset}>
          ↺ Start over
        </button>
      </div>
    </div>
  );
}
