<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);
  });
  $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">
      {#if url}
        <span class="opacity-70">Get Canary:</span>
        <a
          class="opacity-90 hover:underline text-blue-400 hover:text-blue-300"
          href={url.signed}
        >
          Signed
        </a>
        <a
          class="opacity-90 hover:underline text-blue-400 hover:text-blue-300"
          href={url.stripped}
        >
          Stripped
        </a>
      {:else if status === "failed_fetch"}
        <span class="opacity-70">Get Canary:</span>
        <a
          class="opacity-90 hover:underline text-blue-400 hover:text-blue-300"
          href={canary.url}
        >
          Signed
        </a>
        <span class="opacity-70 text-blue-400 grayscale cursor-not-allowed">
          Stripped
        </span>
      {:else}
        No URL yet
      {/if}
    </div>
  </div>
</div>
