components_ItemGrid_GridItemSmall.bs

import "pkg:/source/constants/imageSize.bs"
import "pkg:/source/utils/itemImageUrl.bs"
import "pkg:/source/utils/misc.bs"

sub init()
  m.itemPoster = m.top.findNode("itemPoster")
  m.posterText = m.top.findNode("posterText")
  initTitle()
  m.backdrop = m.top.findNode("backdrop")

  m.itemPoster.observeField("loadStatus", "onPosterLoadStatusChanged")

  'Parent is MarkupGrid and it's parent is the ItemGrid
  m.topParent = m.top.GetParent().GetParent()

  m.title.visible = false

  'Get the imageDisplayMode for these grid items
  if isValid(m.topParent.imageDisplayMode)
    m.itemPoster.loadDisplayMode = m.topParent.imageDisplayMode
  end if
end sub

sub initTitle()
  m.title = m.top.findNode("title")
end sub

sub itemContentChanged()
  m.title.visible = false

  if isValid(m.topParent.showItemTitles)
    if LCase(m.topParent.showItemTitles) = "showalways"
      m.title.visible = true
    end if
  end if

  itemData = m.top.itemContent

  if not isValid(itemData) then return
  if not isValidAndNotEmpty(itemData.id) then return

  userSettings = m.global.user.settings

  if not userSettings.uiTvShowsDisableUnwatchedCount
    if itemData.isWatched
      m.itemPoster.isWatched = true
    else if itemData.unplayedItemCount > 0
      m.itemPoster.unplayedCount = itemData.unplayedItemCount
    end if
  end if

  if LCase(itemData.type) = "genre" or LCase(itemData.folderType) = "genre"
    ' "View All [Genre]" items always display as backdrop-with-text — never load an image.
    ' Force the no-image fallback state immediately so it looks intentional, not like a load failure.
    ' Check both type and folderType: if Jellyfin returns IsFolder=false/absent the transformer
    ' leaves type="Genre" and folderType="", so we must match on type directly.
    m.itemPoster.uri = ""
    m.backdrop.visible = true
    m.posterText.visible = true
  else
    m.itemPoster.uri = getItemPosterUrl(itemData)
    'If Poster not loaded, ensure "blue box" is shown until loaded
    if m.itemPoster.loadStatus <> "ready"
      m.backdrop.visible = true
      m.posterText.visible = true
    end if
  end if

  m.posterText.text = itemData.title
  m.title.text = itemData.title
end sub

sub focusChanged()
  if not isValid(m.title) then initTitle()

  if m.top.itemHasFocus = true
    m.title.repeatCount = -1
  else
    m.title.repeatCount = 0
  end if

  if isValid(m.topParent.showItemTitles)
    if LCase(m.topParent.showItemTitles) = "showonhover"
      m.title.visible = m.top.itemHasFocus
    end if
  end if
end sub

'Hide backdrop and text when poster loaded
sub onPosterLoadStatusChanged()
  if m.itemPoster.loadStatus = "ready"
    m.backdrop.visible = false
    m.posterText.visible = false
  end if
end sub