// AGENT_TARGET: star-spectrum — electromagnetic spectrum overlay on star detail page
// Shows known spectral absorption/emission lines with wavelength labels for each peak.

// Spectral line data keyed by star spectral class (M, G, K, F).
// Each line: { nm: wavelength in nm, label: element/ion, strength: 1-3 }
const SPECTRAL_LINES = {
  G: [
    { nm: 393, label: "Ca II K", strength: 3 },
    { nm: 397, label: "Ca II H", strength: 2 },
    { nm: 431, label: "CH G", strength: 1 },
    { nm: 434, label: "Hγ", strength: 2 },
    { nm: 486, label: "Hβ", strength: 3 },
    { nm: 517, label: "Mg b", strength: 2 },
    { nm: 527, label: "Fe", strength: 1 },
    { nm: 589, label: "Na D", strength: 2 },
    { nm: 656, label: "Hα", strength: 3 },
    { nm: 686, label: "O₂ B", strength: 1 },
  ],
  K: [
    { nm: 393, label: "Ca II K", strength: 3 },
    { nm: 397, label: "Ca II H", strength: 3 },
    { nm: 422, label: "Ca I", strength: 2 },
    { nm: 486, label: "Hβ", strength: 2 },
    { nm: 517, label: "Mg b", strength: 3 },
    { nm: 589, label: "Na D", strength: 3 },
    { nm: 630, label: "Fe I", strength: 2 },
    { nm: 656, label: "Hα", strength: 2 },
  ],
  M: [
    { nm: 393, label: "Ca II K", strength: 2 },
    { nm: 448, label: "TiO", strength: 3 },
    { nm: 477, label: "TiO", strength: 3 },
    { nm: 517, label: "Mg b", strength: 2 },
    { nm: 549, label: "TiO", strength: 3 },
    { nm: 589, label: "Na D", strength: 2 },
    { nm: 620, label: "TiO", strength: 3 },
    { nm: 656, label: "Hα", strength: 2 },
    { nm: 668, label: "TiO", strength: 3 },
    { nm: 706, label: "TiO", strength: 2 },
  ],
  F: [
    { nm: 393, label: "Ca II K", strength: 2 },
    { nm: 410, label: "Hδ", strength: 3 },
    { nm: 434, label: "Hγ", strength: 3 },
    { nm: 486, label: "Hβ", strength: 3 },
    { nm: 517, label: "Fe", strength: 1 },
    { nm: 589, label: "Na D", strength: 1 },
    { nm: 656, label: "Hα", strength: 3 },
  ],
};

const STAR_TEMPERATURE_GUIDES = {
  M: {
    label: "Cool red",
    temp: "2,400-3,700 K",
    clue: "Red stars glow cooler and gentler.",
  },
  K: {
    label: "Warm orange",
    temp: "3,700-5,200 K",
    clue: "Orange stars sit between red and sunlike yellow.",
  },
  G: {
    label: "Sunlike yellow",
    temp: "5,200-6,000 K",
    clue: "Yellow-white stars are hot like our Sun.",
  },
  F: {
    label: "Hot white",
    temp: "6,000-7,500 K",
    clue: "Whiter stars burn hotter than the Sun.",
  },
};

const STAR_TEMPERATURE_ORDER = ["M", "K", "G", "F"];

// AGENT_TARGET: star-spectrum — derive spectral class from planet.type string
function deriveSpectralClass(planet) {
  const typeStr = String((planet && planet.type) || "").toUpperCase();
  if (
    typeStr.includes("M8") ||
    typeStr.includes("M-TYPE") ||
    typeStr.includes("M DWARF") ||
    typeStr.includes("RED DWARF")
  )
    return "M";
  if (
    typeStr.includes("K-TYPE") ||
    typeStr.includes("K8") ||
    typeStr.includes("K0") ||
    typeStr.includes("G8")
  )
    return "K";
  if (
    typeStr.includes("F-TYPE") ||
    typeStr.includes("F5") ||
    typeStr.includes("F8")
  )
    return "F";
  // Sun and most exoplanet hosts are G-type by default
  return "G";
}

// AGENT_TARGET: star-spectrum — convert wavelength (nm) to an approximate visible RGB hex
function nmToHex(nm) {
  // Simplified Bruton's algorithm for visible spectrum 380–780 nm
  let r = 0,
    g = 0,
    b = 0;
  if (nm >= 380 && nm < 440) {
    r = -(nm - 440) / 60;
    g = 0;
    b = 1;
  } else if (nm >= 440 && nm < 490) {
    r = 0;
    g = (nm - 440) / 50;
    b = 1;
  } else if (nm >= 490 && nm < 510) {
    r = 0;
    g = 1;
    b = -(nm - 510) / 20;
  } else if (nm >= 510 && nm < 580) {
    r = (nm - 510) / 70;
    g = 1;
    b = 0;
  } else if (nm >= 580 && nm < 645) {
    r = 1;
    g = -(nm - 645) / 65;
    b = 0;
  } else if (nm >= 645 && nm <= 780) {
    r = 1;
    g = 0;
    b = 0;
  }
  const factor =
    nm < 420
      ? 0.3 + (0.7 * (nm - 380)) / 40
      : nm > 700
        ? 0.3 + (0.7 * (780 - nm)) / 80
        : 1;
  const toInt = (x) => Math.round(255 * Math.pow(x * factor, 0.8));
  return `rgb(${toInt(r)},${toInt(g)},${toInt(b)})`;
}

// AGENT_TARGET: star-spectrum — StarSpectrum main component
function StarSpectrum({ planet }) {
  const [open, setOpen] = React.useState(false);

  if (!planet || !planet.isStar) return null;

  const spectralClass = deriveSpectralClass(planet);
  const lines = SPECTRAL_LINES[spectralClass] || SPECTRAL_LINES.G;

  // Visible range displayed: 370–720 nm
  const NM_MIN = 370;
  const NM_MAX = 720;
  const nmToPercent = (nm) => ((nm - NM_MIN) / (NM_MAX - NM_MIN)) * 100;

  const classNames = {
    G: "G-type (Sun-like)",
    K: "K-type (orange dwarf)",
    M: "M-type (red dwarf)",
    F: "F-type (hot yellow-white)",
  };
  const temperatureGuide =
    STAR_TEMPERATURE_GUIDES[spectralClass] || STAR_TEMPERATURE_GUIDES.G;

  return (
    <div className="star-spectrum-card">
      <button
        className="star-spectrum-toggle"
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
      >
        🌈 Star Spectrum {open ? "▲" : "▼"}
      </button>

      {open && (
        <div className="star-spectrum-body">
          <div className="star-spectrum-class-label">
            Spectral class: <strong>{spectralClass}</strong> —{" "}
            {classNames[spectralClass] || ""}
          </div>

          <div
            className={`star-temperature-ladder star-temperature-${spectralClass.toLowerCase()}`}
            aria-label={`Star color temperature clue: ${temperatureGuide.clue}`}
          >
            <div className="star-temperature-track">
              {STAR_TEMPERATURE_ORDER.map((key) => {
                const guide = STAR_TEMPERATURE_GUIDES[key];
                const active = key === spectralClass;
                return (
                  <div
                    key={key}
                    className={`star-temperature-chip ${active ? "active" : ""}`}
                    aria-current={active ? "true" : undefined}
                  >
                    <span className="star-temperature-key">{key}</span>
                    <span className="star-temperature-label">{guide.label}</span>
                    <span className="star-temperature-temp">{guide.temp}</span>
                  </div>
                );
              })}
            </div>
            <div className="star-temperature-clue">{temperatureGuide.clue}</div>
          </div>

          <div
            className="star-spectrum-bar-wrap"
            aria-label="Electromagnetic spectrum from UV to IR"
          >
            {/* UV shoulder */}
            <div
              className="spectrum-region spectrum-uv"
              aria-label="Ultraviolet"
              title="Ultraviolet (UV)"
            />
            {/* Visible rainbow bar */}
            <div className="spectrum-region spectrum-visible">
              <div className="spectrum-rainbow" />
              {/* Absorption line ticks */}
              {lines.map((line) => {
                const pct = nmToPercent(line.nm);
                if (pct < 0 || pct > 100) return null;
                return (
                  <div
                    key={line.nm}
                    className={`spectrum-line strength-${line.strength}`}
                    style={{ left: `${pct}%` }}
                    title={`${line.label} — ${line.nm} nm`}
                  >
                    <div className="spectrum-line-tick" />
                    <div className="spectrum-line-label">{line.label}</div>
                    <div className="spectrum-line-nm">{line.nm} nm</div>
                  </div>
                );
              })}
              {/* Wavelength axis labels */}
              <div className="spectrum-axis">
                {[400, 450, 500, 550, 600, 650, 700].map((nm) => (
                  <div
                    key={nm}
                    className="spectrum-axis-mark"
                    style={{ left: `${nmToPercent(nm)}%` }}
                  >
                    <span>{nm}</span>
                  </div>
                ))}
              </div>
            </div>
            {/* IR shoulder */}
            <div
              className="spectrum-region spectrum-ir"
              aria-label="Infrared"
              title="Infrared (IR)"
            />
          </div>

          <div className="spectrum-legend">
            <span className="legend-dot strength-3" /> Strong absorption &nbsp;
            <span className="legend-dot strength-2" /> Moderate &nbsp;
            <span className="legend-dot strength-1" /> Weak
          </div>

          <div className="spectrum-note">
            Absorption lines appear where atoms in the star's atmosphere absorb
            specific wavelengths of light — leaving dark gaps in the rainbow
            that act like a chemical fingerprint.
          </div>
        </div>
      )}
    </div>
  );
}
