/**
 * @file Apotheosis panel component for the final prestige layer.
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */
/* eslint-disable max-lines-per-function -- Complex component with many render paths */
/* eslint-disable complexity -- Complex component with many conditional render paths */
import { type JSX, useState } from "react";
import { useGame } from "../../context/gameContext.js";
import { TRANSCENDENCE_UPGRADES } from "../../data/transcendenceUpgrades.js";

const totalEchoUpgrades = TRANSCENDENCE_UPGRADES.length;

/**
 * Renders the apotheosis panel for achieving the final game milestone.
 * @returns The JSX element.
 */
const ApotheosisPanel = (): JSX.Element => {
  const { state, apotheosis } = useGame();
  const [ isPending, setIsPending ] = useState(false);
  const [ result, setResult ] = useState<number | null>(null);
  const [ error, setError ] = useState<string | null>(null);

  if (state === null) {
    return (
      <section className="panel">
        <p>{"Loading..."}</p>
      </section>
    );
  }

  const purchasedIds = state.transcendence?.purchasedUpgradeIds ?? [];
  const purchasedCount = TRANSCENDENCE_UPGRADES.filter((upgrade) => {
    return purchasedIds.includes(upgrade.id);
  }).length;
  const isEligible = purchasedCount >= totalEchoUpgrades;
  const apotheosisCount = state.apotheosis?.count ?? 0;

  async function handleApotheosis(): Promise<void> {
    setIsPending(true);
    setError(null);
    try {
      const data = await apotheosis();
      setResult(data.newApotheosisCount);
    } catch (caughtError) {
      setError(
        caughtError instanceof Error
          ? caughtError.message
          : "Apotheosis failed",
      );
    } finally {
      setIsPending(false);
    }
  }

  function handleApotheosisClick(): void {
    void handleApotheosis();
  }

  const plural = apotheosisCount === 1
    ? ""
    : "s";

  return (
    <section className="panel apotheosis-panel">
      <h2>{"✨ Apotheosis"}</h2>

      <p className="apotheosis-intro">
        {"Apotheosis is the final act — a complete dissolution of everything"
          + " you have built. Prestige, Transcendence, Echoes, upgrades,"
          + " equipment, resources: all of it returns to nothing."
          + " In exchange, you receive only one thing:"}
      </p>
      <p className="apotheosis-reward">
        {"The "}
        <strong>{"✨ Apotheosis"}</strong>
        {" badge. Proof that you have done it all."}
      </p>
      <p className="apotheosis-intro">
        {"Apotheosis can be achieved multiple times. Each cycle requires"
          + " you to purchase every Transcendence upgrade again before the"
          + " next Apotheosis becomes available. There is no mechanical"
          + " benefit — only the knowledge that you have reached the"
          + " pinnacle, dissolved it, and climbed back up."}
      </p>

      {apotheosisCount > 0
        && <div className="apotheosis-count">
          <span>
            {"You have achieved Apotheosis "}
            <strong>{apotheosisCount}</strong>
            {" time"}
            {plural}
            {"."}
          </span>
        </div>
      }

      <div className="apotheosis-status">
        <p>
          {"Transcendence upgrades purchased: "}
          <strong>
            {purchasedCount}
            {" / "}
            {totalEchoUpgrades}
          </strong>
        </p>
        {isEligible
          ? null
          : <p className="apotheosis-missing">
            {"🔒 Purchase all "}
            {totalEchoUpgrades}
            {" Transcendence upgrades to unlock Apotheosis. ("}
            {totalEchoUpgrades - purchasedCount}
            {" remaining)"}
          </p>
        }
        {isEligible
          ? <p className="apotheosis-ready">
            {"✅ All Transcendence upgrades purchased. You are ready."}
          </p>
          : null}
      </div>

      {isEligible
        ? <div className="prestige-form">
          <p>
            {"This action is "}
            <strong>{"permanent and irreversible"}</strong>
            {"."}
          </p>
          <button
            className="apotheosis-button"
            disabled={isPending}
            onClick={handleApotheosisClick}
            type="button"
          >
            {isPending
              ? "Ascending..."
              : "✨ Achieve Apotheosis"}
          </button>
          {error === null
            ? null
            : <p className="error">{error}</p>}
          {result !== null
            && <p className="success">
              {"Apotheosis achieved. This is cycle "}
              <strong>{result}</strong>
              {". The infinite loop continues."}
            </p>
          }
        </div>
        : null}
    </section>
  );
};

export { ApotheosisPanel };
