{% set source_dir = album.gallery.settings.source.split('/')[-1] %}

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>{{ album.gallery.title }}{% if source_dir != album.title|striptags %} - {{ album.title|striptags }}{% endif %}</title>
    <meta name="description" content="">
    <meta name="author" content="{{ album.author }}">
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="{{ theme.url }}/css/normalize.css">
    <link rel="stylesheet" href="{{ theme.url }}/css/style.css">
  </head>
  <body>
    <div id="main"{% if not album.gallery.full_tree %} class="no_menu"{% endif %}>
      {% if album.gallery.full_tree %}
        <div id="menu">
          {% if album.gallery.title %}
            <p class="title">
              <a href="{{ album.path_to_root }}">{{ album.gallery.title }}</a>
            </p>
          {% endif %}
          {% with albums=album.gallery.full_tree, depth=0 %}
            {% include './menu.html' %}
          {% endwith %}
        </div>
      {% endif %}

      {% if album.medias %}
        <div id="thumbnails">
          {% for media in album.medias -%}
            <a
              href="#{{ media.dst_filename }}"
              data-id="{{ media.dst_filename }}"
            ><img
              src="{{ media.thumbnail }}"
              alt="{{ media.title or media.src_filename }}"
            ></a>
          {%- endfor %}
        </div>

        <div id="canvas">
          {% for media in album.medias %}
            <div
              id="{{ media.dst_filename }}"
            >
              {% if media.type == "image" -%}
                <span>{{ media.title or media.src_filename }}     {{ media.exif.dateobj.strftime('%y%m%d %H%M%S') if media.exif and 'dateobj' in media.exif else '(unknown date)' }}</span>
                <img
                  src="{{ media.dst_filename }}"
                  alt="{{ media.title or media.src_filename }}     {{ media.exif.dateobj.strftime('%y%m%d %H%M%S') if media.exif and 'dateobj' in media.exif else '(unknown date)' }}"
                  loading="lazy"
                >
              {%- elif media.type == "video" %}
                <span>{{ media.title or media.src_filename }}</span>
                <video
                  controls
                  preload="metadata"
                  poster="{{ media.thumbnail }}"
                >
                  <source src='{{ media.src_filename }}' type='{{ media.mime }}' />
                </video>
              {% endif %}
            </div>
          {% endfor %}
        </div>

        <div id="fullscreen"></div>
      {% endif %}

    </div>

    <script>
      function leftHandler() {
        // Go to previous image
        pauseCurrent()
        const current = document.getElementById(window.location.hash.slice(1))
        const next = current?.previousElementSibling ? current.previousElementSibling : document.getElementById('canvas').lastElementChild
        location.replace(`#${next.id}`)
        preloadSurrounding()
      }

      function rightHandler() {
        // Go to next image
        pauseCurrent()
        const current = document.getElementById(window.location.hash.slice(1))
        const next = current?.nextElementSibling ? current.nextElementSibling : document.getElementById('canvas').firstElementChild
        location.replace(`#${next.id}`)
        preloadSurrounding()
      }

      function upHandler() {
        // Go to first image
        pauseCurrent()
        const next = document.getElementById('canvas').firstElementChild
        location.replace(`#${next.id}`)
        preloadSurrounding()
      }

      function downHandler() {
        // Go to last image
        pauseCurrent()
        const next = document.getElementById('canvas').lastElementChild
        location.replace(`#${next.id}`)
        preloadSurrounding()
      }

      function preloadSurrounding() {
        // Eagerly load images around current
        const current = document.getElementById(window.location.hash.slice(1))
        const previous = current?.previousElementSibling ? current.previousElementSibling : document.getElementById('canvas').lastElementChild
        previous?.querySelector('img')?.setAttribute('loading', 'eager')
        const next = current?.nextElementSibling ? current.nextElementSibling : document.getElementById('canvas').firstElementChild
        next?.querySelector('img')?.setAttribute('loading', 'eager')
      }

      function highlightThumbnail() {
        // Highlight the thumbnail corresponding to the displayed image
        const current = document.getElementById('thumbnails').querySelector('.current')
        current?.classList.remove('current')
        const next = document.querySelector(`[data-id="${window.location.hash.slice(1)}"]`)
        next?.classList.add('current')
      }

      function pauseCurrent() {
        // Pause a video when navigating to another image
        const current = document.getElementById(window.location.hash.slice(1))
        current?.querySelector('video')?.pause()
      }

      function nextPrevious(event) {
        // Detect clicks on left/right side of currently displayed image to go to next/previous
        if (event.currentTarget.querySelector(':target video')) {
          return false
        }
        const offset = event.offsetX - (event.target.offsetWidth / 2)
        const deadzone = 20
        if (offset > deadzone) {
          rightHandler()
        } else if (offset < -deadzone) {
          leftHandler()
        }
      }

      function toggleFullscreen() {
        // Toggle fullscreen for the canvas
        if (document.fullscreenElement) {
          document.exitFullscreen()
        }
        else {
          const canvas = document.getElementById('canvas')
          canvas.requestFullscreen({navigationUI: 'hide'})
        }
      }

      function keyHandler(event) {
        // Handle navigation by keys
        const callback = {
          'ArrowLeft': leftHandler,
          'ArrowRight': rightHandler,
          'ArrowUp': upHandler,
          'ArrowDown': downHandler,
          'f': toggleFullscreen,
        }[event.key]
        callback?.()
      }

      // Do not add handlers if there is no content
      const canvas = document.getElementById('canvas')
      const fullscreen = document.getElementById('fullscreen')
      const first_entry = canvas.firstElementChild
      if (first_entry) {
        document.addEventListener('keydown', keyHandler)
        window.addEventListener('hashchange', highlightThumbnail)
        canvas.addEventListener('click', nextPrevious)
        fullscreen.addEventListener('click', toggleFullscreen)
        if (!window.location.hash.slice(1)) {
          upHandler()
        }
        highlightThumbnail()
        preloadSurrounding()
      }
    </script>
  </body>
</html>
