//
// 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, Card } from "react-bootstrap";
import { atom, useAtomValue } from "jotai";
import { createQueryAtom } from "./utils/query.ts";
import { DiagnosticsCard } from "./components/DiagnosticsCard.tsx";

const statusStringQueryAtom = createQueryAtom("status_string", "api/status", {
  refetchInterval: 500,
});
const statusStringAtom = atom((get) => {
  const response = get(statusStringQueryAtom);
  if (response.isPending || response.isError || !response.data.status) {
    return "N/A";
  }
  return response.data.message;
});

const uptimeQueryAtom = createQueryAtom("api/uptime", {
  refetchInterval: 1000,
});
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>
  );
}
