---
import { fetchGithub } from "../../utils/fetchGithub";

export interface Props {
  path: string;
}
const { path } = Astro.props;

const [_1, _2, _3, ...rest] = path.split("/");

const englishPath = `src/pages/en/${rest.join("/")}`;
const engHref = `/en/${rest.join("/").replace(/\.[^/.]+$/, "")}`;

const url = `https://api.github.com/repos/t3-oss/create-t3-app/commits?path=www/${path}&per_page=1`;
const engUrl = `https://api.github.com/repos/t3-oss/create-t3-app/commits?path=www/${englishPath}&per_page=1`;

// File may not be on Github yet, so we only throw an error if we're in production
async function getCommitDiff() {
  try {
    const thisLangCommit = await fetchGithub(url, { fetchType: "commits" });
    const englishCommit = await fetchGithub(engUrl, { fetchType: "commits" });

    const thisLangDate = thisLangCommit?.length
      ? new Date(thisLangCommit[0]?.commit.author.date ?? "")
      : new Date();
    const englishDate = englishCommit?.length
      ? new Date(englishCommit[0]?.commit.author.date ?? "")
      : new Date();

    const diffInDays = Math.round(
      (englishDate.getTime() - thisLangDate.getTime()) / (1000 * 3600 * 24),
    );
    return diffInDays;
  } catch (e) {
    console.warn(`[warn]  /src/components/outDatedDocsBanner.astro 
    ${(e as Error)?.message ?? e}
    If you're in production, this is a problem. If you're in dev, it's probably fine.
    If this warning appears on a translated file that's not yet on origin, it's fine.`);

    return 0;
  }
}

const diffInDays = await getCommitDiff();

const ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
Astro.response.headers.set("Cache-Control", `s-max-age=${ONE_WEEK}`);
---

{
  diffInDays > 0 && (
    <div
      dir="ltr"
      class="mx-4 mb-6 rounded-lg bg-t3-purple-200/50 p-4 font-medium lg:mx-0 lg:ml-4 dark:bg-t3-purple-200/10"
    >
      <p>
        Attention: This page is{" "}
        <span class="font-extrabold">
          {diffInDays} {diffInDays === 1 ? "day" : "days"}
        </span>
        older than the English version and might be outdated. If you're a native
        speaker of this language and would like to contribute to the project,
        please consider updating this page to match the latest English version.
      </p>
      <p class="mt-3">
        You can also
        <a class="inline-block text-t3-purple-400" href={engHref}>
          view the English version
        </a>
        of this page.
      </p>
    </div>
  )
}
