//
// 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 "./components/AppNav.tsx";
import { Container, Row, Col, Image, Card } from "react-bootstrap";
import { atom, useAtomValue } from "jotai";
import { atomWithQuery } from "jotai-tanstack-query";
import { DiagnosticsCard } from "./components/DiagnosticsCard.tsx";

const statusStringQuery = async () => {
  const resp = await fetch("api/status");
  if (!resp.ok) {
    throw new Error("Network response was not ok");
  }
  return resp.json();
};
const statusStringQueryAtom = atomWithQuery(() => ({
  queryKey: ["status_string"],
  queryFn: statusStringQuery,
  refetchInterval: 500, // 0.5s
}));
const statusStringAtom = atom((get) => {
  const response = get(statusStringQueryAtom);
  if (response.isPending || response.isError || !response.data.status) {
    return "N/A";
  }
  return response.data.message;
});

const uptimeQuery = async () => {
  const resp = await fetch("api/uptime");
  if (!resp.ok) {
    throw new Error("Network response was not ok");
  }
  return resp.json();
};
const uptimeQueryAtom = atomWithQuery(() => ({
  queryKey: ["uptime"],
  queryFn: uptimeQuery,
  refetchInterval: 1000, // 1s
}));
const uptimeAtom = atom((get) => {
  const response = get(uptimeQueryAtom);
  if (response.isPending || response.isError) {
    return "N/A";
  }
  return response.data.uptime.toFixed(1);
});

function StatusCard() {
  const statusString = useAtomValue(statusStringAtom);
  return (
    <Card className="padded">
      <Row>
        <p>Status:</p>
      </Row>
      <Row>
        <p>{statusString}</p>
      </Row>
    </Card>
  );
}

function UptimeCard() {
  const uptime = useAtomValue(uptimeAtom);
  return (
    <Card className="padded">
      <Row>
        <p>Uptime:</p>
      </Row>
      <Row>
        <p>{uptime}s</p>
      </Row>
    </Card>
  );
}

export function Home() {
  return (
    <div>
      <AppNav />
      <Container className="vert-padded">
        <Row>
          <Col>
            <UptimeCard />
          </Col>
          <Col>
            <StatusCard />
          </Col>
        </Row>
        <Row className="vert-padded">
          <Col>
            <DiagnosticsCard />
          </Col>
        </Row>
      </Container>
      <Footer />
    </div>
  );
}
