<script lang="ts">
  import { useEntity } from "../../../lib/entity";
  import Spinner from "../../utils/Spinner.svelte";
  export let address: string;
  export let detail: boolean;
  import { xywh } from "../../../util/fragments/xywh";
  import { createEventDispatcher } from "svelte";
  import api from "../../../lib/api";
  const dispatch = createEventDispatcher();

  const { entity } = useEntity(address);

  $: objectAddress = String($entity?.get("ANNOTATES") || "");

  $: imageFragment = String($entity?.get("W3C_FRAGMENT_SELECTOR")).includes(
    "xywh="
  );

  let imageLoaded = false;
  $: imageLoaded && dispatch("loaded");
  $: if ($entity && !imageFragment) imageLoaded = true;
</script>

<div class="fragment-viewer">
  {#if !imageLoaded}
    <Spinner />
  {/if}
  {#if $entity}
    {#if imageFragment}
      <img
        class="preview-image"
        class:imageLoaded
        src="{api.apiUrl}/{detail ? 'raw' : 'thumb'}/{objectAddress}#{$entity?.get(
          'W3C_FRAGMENT_SELECTOR'
        )}"
        use:xywh
        alt={address}
        on:load={() => (imageLoaded = true)}
        draggable="false"
      />
    {/if}
  {/if}
</div>

<style lang="scss">
  @use "../../../styles/colors";

  .fragment-viewer {
    width: 100%;
    display: flex;
    justify-content: center;
    min-height: 0;
  }

  img {
    max-width: 100%;
    box-sizing: border-box;
    min-height: 0;
    &.imageLoaded {
      border: 2px dashed colors.$yellow;
    }
  }
</style>
