//
// Copyright 2026 James Pace
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, v. 2.0.
//
import { AppNav, Footer } from "./AppNav.tsx";
import { Container, Row, Col, Card } from "react-bootstrap";
import { atom, useAtomValue } from "jotai";
import { atomWithQuery } from "jotai-tanstack-query";
import YAML from "yaml";

const versionQueryFn = async () => {
  const resp = await fetch("api/build_info");
  if (!resp.ok) {
    throw new Error("Network response was not ok");
  }
  return resp.json();
};

const versionQueryAtom = atomWithQuery(() => ({
  queryKey: ["version"],
  queryFn: versionQueryFn,
}));

const versionAtom = atom((get) => {
  const version = get(versionQueryAtom);
  if (version.isPending) {
    return "Loading...";
  }
  if (version.isError) {
    return "Error loading!";
  }
  if (!version.data.status) {
    return "Can not find version";
  }
  return YAML.stringify(version.data.message);
});

export function Version() {
  let versionText = useAtomValue(versionAtom);

  return (
    <div>
      <AppNav />
      <Container className="vert-padded">
        <Card className="padded">
          <Card.Title>project.yaml</Card.Title>
          <Card.Body>
            <pre>{versionText}</pre>
          </Card.Body>
        </Card>
      </Container>
      <Footer />
    </div>
  );
}
