<script lang="ts">
  import type { Canary } from "./canaries";
  let {
    canary,
  }: {
    canary: Canary;
  } = $props();
  let rawText = $state(null as string | null);
  let failedFetch = $state(false);
  let url = $state(
    null as {
      stripped: string;
      signed: string;
    } | null,
  );
  let status = $derived(
    url !== null
      ? ("ok" as const)
      : failedFetch
        ? ("failed_fetch" as const)
        : rawText === null
          ? ("fetching" as const)
          : ("failed_sigcheck" as const),
  );
  $effect(() => {
    (async (canary) => {
      rawText = await canary.getRawText();
    })(canary).catch((e) => {
      failedFetch = true;
    });
  });
  $effect(() => {
    (async (canary) => {
      url = await canary.getUrl();
    })(canary);
  });
</script>

<div
  class="canary p-4 bg-opacity-10 flex-1 max-w-[1024px] min-w-[min(100%,500px)] overflow-x-auto flex flex-col justify-between rounded-2xl"
  class:bg-white={status === "ok"}
  class:bg-blue-500={status === "fetching"}
  class:bg-red-500={status === "failed_sigcheck"}
  class:bg-red-800={status === "failed_fetch"}
>
  <div class="top">
    <small class="opacity-50">{canary.signer}'s canary for</small>
    <h2 class="canary-name text-lg">{canary.name}</h2>
    <p class="opacity-80 text-white font-normal mt-1">
      {#if status === "ok"}
        {canary.description}
      {:else if status === "fetching"}
        Fetching Canary...
      {:else if status === "failed_sigcheck"}
        Failed Signature Check!<br />
        Either the upstream key changed, or the canary is fucked!
      {:else if status === "failed_fetch"}
        Failed to fetch canary!
      {/if}
    </p>
  </div>
  <div class="bottom">
    <div class="mt-2">
      <span class="opacity-70">Get Canary:</span>
      {#if canary.upstream}
        <a
          class="opacity-90 hover:underline text-blue-400 hover:text-blue-300"
          href={canary.upstream}
        >
          Upstream
        </a>
      {/if}
      {#if status !== "failed_sigcheck" && status !== "failed_fetch"}
        <a
          class="opacity-90 hover:underline text-blue-400 hover:text-blue-300"
          href={url?.signed ?? canary.url}
        >
          Signed
        </a>
      {:else}
        <a
          class="opacity-90 hover:underline text-red-400 hover:text-red-300"
          href={url?.signed ?? canary.url}
        >
          Signed, {status === "failed_sigcheck"
            ? "bad signature"
            : "unreachable"}
        </a>
      {/if}
      {#if url}
        <a
          class="opacity-90 hover:underline text-blue-400 hover:text-blue-300"
          href={url.stripped}
        >
          Stripped
        </a>
      {:else}
        <span class="opacity-70 text-blue-400 grayscale cursor-not-allowed">
          Stripped
        </span>
      {/if}
    </div>
  </div>
</div>
