import { html, keyed } from "/js/lib/lit-html.js";
import { avatarThumbnailUrl, isLabelerProfile } from "/js/dataHelpers.js";
import { classnames } from "/js/utils.js";
import { linkToProfile } from "/js/navigation.js";
import "/js/components/lightbox-image-group.js";

// CLick actions: "link", "lightbox", "none"

function avatarWrapperTemplate({ author, clickAction, children }) {
  if (clickAction === "link") {
    return html`<a class="avatar-link" href="${linkToProfile(author)}"
      >${children}</a
    >`;
  } else if (clickAction === "lightbox") {
    return html`<lightbox-image-group hide-alt-text="true" image-shape="circle"
      >${children}</lightbox-image-group
    >`;
  } else {
    return children;
  }
}

function getAvatarFallbackUrl(isLabeler) {
  if (isLabeler) {
    return "/img/labeler-avatar-fallback.svg";
  } else {
    return "/img/avatar-fallback.svg";
  }
}

function getAvataThumbnailUrl(author, isLabeler) {
  if (author.avatar) {
    return avatarThumbnailUrl(author.avatar);
  } else {
    return getAvatarFallbackUrl(isLabeler);
  }
}

function getAvatarFullSizeUrl(author, isLabeler) {
  if (author.avatar) {
    return author.avatar;
  } else {
    return getAvatarFallbackUrl(isLabeler);
  }
}

export function avatarTemplate({
  author,
  clickAction = "link",
  lazyLoad = false,
  // lazyLoad = true,
}) {
  const isLabeler = isLabelerProfile(author);
  const isBlurred = !!author.blurLabel;
  const avatarThumbnailUrl = getAvataThumbnailUrl(author, isLabeler);
  const avatarFullSizeUrl = getAvatarFullSizeUrl(author, isLabeler);
  return html`<div class="avatar" data-testid="avatar">
    ${avatarWrapperTemplate({
      author,
      clickAction,
      children: keyed(
        author.handle,
        html`<div
          class=${classnames("avatar-image-frame", {
            "labeler-avatar": isLabeler,
          })}
        >
          <span class="hack-x">x</span>
          <img
            src="${avatarThumbnailUrl}"
            alt="${author.displayName} profile picture"
            class=${classnames("avatar-image", {
              "labeler-avatar": isLabeler,
              "avatar-image--blurred": isBlurred,
            })}
            data-testid="avatar-image"
            data-lightbox-src="${avatarFullSizeUrl}"
            loading=${lazyLoad ? "lazy" : "eager"}
          />
        </div>`,
      ),
    })}
  </div>`;
}
