<!-- OlaBoa Hero Section -->
<section class="olaboa-hero">
  <div class="olaboa-hero__slides">
    {%- assign fallback_images = 'hero-beach.jpg,slide_2.jpg,slide_3.jpg,slide_4.jpg' | split: ',' -%}
    {% for block in section.blocks %}
      {%- liquid
        assign has_mobile_video = false
        assign has_mobile_image = false
        if block.settings.video_mobile != blank
          assign has_mobile_video = true
        endif
        if block.settings.image_mobile != blank
          assign has_mobile_image = true
        endif
        assign has_desktop_video = false
        if block.settings.video != blank
          assign has_desktop_video = true
        endif
      -%}
      <div class="olaboa-hero__slide {% if forloop.first %}active{% endif %}" {{ block.shopify_attributes }} {% if has_desktop_video or has_mobile_video %}data-has-video="true"{% endif %}>

        {%- comment -%} Desktop media {%- endcomment -%}
        {% if block.settings.video %}
          <video class="olaboa-hero__video olaboa-hero__media--desktop" autoplay muted loop playsinline>
            {%- for source in block.settings.video.sources -%}
              <source src="{{ source.url }}" type="{{ source.mime_type }}">
            {%- endfor -%}
          </video>
        {% elsif block.settings.image %}
          {{ block.settings.image | image_url: width: 2000 | image_tag: class: 'olaboa-hero__image olaboa-hero__media--desktop', loading: 'eager' }}
        {% else %}
          {%- assign fb_index = forloop.index0 | modulo: 4 -%}
          <img src="{{ fallback_images[fb_index] | asset_url }}" alt="OlaBoa Hero" class="olaboa-hero__image olaboa-hero__media--desktop" loading="eager">
        {% endif %}

        {%- comment -%} Mobile media (only rendered if set) {%- endcomment -%}
        {% if has_mobile_video %}
          <video class="olaboa-hero__video olaboa-hero__media--mobile" autoplay muted loop playsinline>
            {%- for source in block.settings.video_mobile.sources -%}
              <source src="{{ source.url }}" type="{{ source.mime_type }}">
            {%- endfor -%}
          </video>
        {% elsif has_mobile_image %}
          {{ block.settings.image_mobile | image_url: width: 1000 | image_tag: class: 'olaboa-hero__image olaboa-hero__media--mobile', loading: 'eager' }}
        {% endif %}

      </div>
    {% endfor %}
  </div>
  <div class="olaboa-hero__overlay"></div>
  <div class="olaboa-hero__content">
    <div class="olaboa-hero__logo" data-video-logo-svg data-src="{{ 'logo-sprite.png' | asset_url }}" data-static="{{ 'logo-olaboa-static.png' | asset_url }}" data-video-webm="{{ 'logo-video-alpha.webm' | asset_url }}" data-video-mov="{{ 'logo-video-alpha.mov' | asset_url }}"></div>
    <div class="olaboa-hero__tagline">
      {{ section.settings.tagline }}
    </div>
  </div>

  <div class="olaboa-hero__slide-indicator">
    <span class="olaboa-hero__slide-number">01</span>
    <div class="olaboa-hero__progress">
      {% for block in section.blocks %}
        <div class="olaboa-hero__progress-bar {% if forloop.first %}active{% endif %}">
          <div class="olaboa-hero__progress-fill"></div>
        </div>
      {% endfor %}
    </div>
  </div>

  <a href="#olaboa-wave-hello" class="olaboa-hero__scroll-arrow">
    <img src="{{ 'arrow-down.svg' | asset_url }}" alt="Scroll down">
  </a>
</section>

<script>
  (() => {
    const W = 560, H = 202, COLS = 28, TOTAL = 766, DUR = 31.9167;

    function mount(node) {
      if (!node || node.dataset.videoLogoMounted === "true") return;
      node.dataset.videoLogoMounted = "true";
      node.style.lineHeight = "0";

      /* Reduced-motion: static image */
      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
        var staticImg = document.createElement("img");
        staticImg.src = node.dataset.static || "";
        staticImg.alt = "OlaBoa";
        staticImg.style.cssText = "display:block;width:100%;height:auto";
        node.replaceChildren(staticImg);
        return;
      }

      /* Mobile: transparent video (WebM for Chrome/FF, MOV HEVC for Safari/iOS) */
      if (window.innerWidth <= 768) {
        var video = document.createElement("video");
        video.autoplay = true;
        video.loop = true;
        video.muted = true;
        video.playsInline = true;
        video.setAttribute("playsinline", "");
        video.setAttribute("webkit-playsinline", "");
        video.style.cssText = "display:block;width:100%;height:auto;background:transparent";

        /* MOV HEVC alpha for Safari/iOS (listed first — browser picks first supported) */
        var srcMov = document.createElement("source");
        srcMov.src = node.dataset.videoMov || "";
        srcMov.type = 'video/quicktime; codecs="hvc1"';
        video.appendChild(srcMov);

        /* WebM VP9 alpha for Chrome/Firefox/Edge */
        var srcWebm = document.createElement("source");
        srcWebm.src = node.dataset.videoWebm || "";
        srcWebm.type = "video/webm";
        video.appendChild(srcWebm);

        node.replaceChildren(video);

        /* Force play — fallback to static image if autoplay blocked (iOS low power mode) */
        var staticSrc = node.dataset.static || "";
        function fallbackToStatic() {
          var img = document.createElement("img");
          img.src = staticSrc;
          img.alt = "OlaBoa";
          img.style.cssText = "display:block;width:100%;height:auto";
          node.replaceChildren(img);
        }

        video.load();
        var playPromise = video.play();
        if (playPromise !== undefined) {
          playPromise.catch(function() { fallbackToStatic(); });
        }

        /* Double-check after 2s: if video hasn't started, show static */
        setTimeout(function() {
          if (video.paused && video.currentTime === 0) { fallbackToStatic(); }
        }, 2000);

        /* Pause off-screen */
        new IntersectionObserver(function(entries) {
          entries[0].isIntersecting ? video.play().catch(function(){}) : video.pause();
        }, { threshold: 0.1 }).observe(node);
        return;
      }

      /* Desktop: canvas sprite animation */
      var canvas = document.createElement("canvas");
      canvas.width = W;
      canvas.height = H;
      canvas.style.cssText = "display:block;width:100%;height:auto;will-change:contents";
      node.replaceChildren(canvas);

      var ctx = canvas.getContext("2d", { alpha: true });
      if (!ctx) return;

      var img = new Image();
      img.decoding = "async";
      img.onload = function() {
        var state = { frame: 0 };
        var last = -1;

        var tween = gsap.to(state, {
          frame: TOTAL - 1,
          duration: DUR,
          ease: "steps(" + (TOTAL - 1) + ")",
          repeat: -1,
          onUpdate: function() {
            var f = state.frame | 0;
            if (f === last) return;
            last = f;
            ctx.clearRect(0, 0, W, H);
            ctx.drawImage(img, (f % COLS) * W, ((f / COLS) | 0) * H, W, H, 0, 0, W, H);
          }
        });

        /* Pause off-screen */
        new IntersectionObserver(function(entries) {
          entries[0].isIntersecting ? tween.play() : tween.pause();
        }, { threshold: 0.1 }).observe(node);
      };
      img.src = node.dataset.src || "";
    }

    function autoMount() {
      document.querySelectorAll("[data-video-logo-svg]").forEach(function(n) { mount(n); });
    }

    if (typeof gsap !== "undefined") {
      autoMount();
    } else {
      document.addEventListener("DOMContentLoaded", function() {
        /* Wait for GSAP defer to load */
        if (typeof gsap !== "undefined") { autoMount(); return; }
        var check = setInterval(function() {
          if (typeof gsap !== "undefined") { clearInterval(check); autoMount(); }
        }, 50);
      });
    }

    window.VideoLogoSvg = { mount };
  })();
</script>

<script>
  (function() {
    var section = document.querySelector('.olaboa-hero');
    var slides = section.querySelectorAll('.olaboa-hero__slide');
    var bars = section.querySelectorAll('.olaboa-hero__progress-bar');
    var fills = section.querySelectorAll('.olaboa-hero__progress-fill');
    var numberEl = section.querySelector('.olaboa-hero__slide-number');
    var current = 0;
    var total = slides.length;
    var imageDuration = 7000;
    var timer = null;
    var progressAnim = null;

    function getVisibleVideo(slide) {
      var videos = slide.querySelectorAll('video');
      for (var i = 0; i < videos.length; i++) {
        if (videos[i].offsetParent !== null || getComputedStyle(videos[i]).display !== 'none') return videos[i];
      }
      return videos[0] || null;
    }

    function getSlideDuration(index) {
      var video = getVisibleVideo(slides[index]);
      if (video && video.duration && isFinite(video.duration)) {
        return video.duration * 1000;
      }
      return imageDuration;
    }

    function isMobile() {
      return window.innerWidth <= 900;
    }

    function animateProgress(index, dur) {
      var fill = fills[index];
      var mobile = isMobile();
      var axis = mobile ? 'Y' : 'X';
      var origin = mobile ? 'top center' : 'left center';
      fill.style.animation = 'none';
      fill.style.transition = 'none';
      fill.style.transformOrigin = origin;
      fill.style.transform = 'scale' + axis + '(0)';
      fill.offsetHeight; /* force reflow */
      requestAnimationFrame(function() {
        fill.style.transition = 'transform ' + dur + 'ms linear';
        fill.style.transform = 'scale' + axis + '(1)';
      });
    }

    function resetFill(index) {
      var fill = fills[index];
      var mobile = isMobile();
      fill.style.animation = 'none';
      fill.style.transition = 'none';
      fill.style.transformOrigin = mobile ? 'top center' : 'left center';
      fill.style.transform = mobile ? 'scaleY(0)' : 'scaleX(0)';
    }

    function scheduleNext(dur) {
      clearTimeout(timer);
      timer = setTimeout(function() {
        goTo(current + 1);
      }, dur);
    }

    function goTo(index) {
      var prev = current;
      current = index % total;
      // Pause all videos on previous slide
      slides[prev].querySelectorAll('video').forEach(function(v) { v.pause(); });
      // Reset previous fill
      resetFill(prev);
      // Keep old slide visible underneath while new one fades in
      slides[prev].classList.remove('active');
      slides[prev].classList.add('prev');
      bars[prev].classList.remove('active');
      slides[current].classList.add('active');
      bars[current].classList.add('active');
      numberEl.textContent = String(current + 1).padStart(2, '0');
      // Play visible video on current slide
      var curVideo = getVisibleVideo(slides[current]);
      if (curVideo) { curVideo.currentTime = 0; curVideo.play().catch(function(){}); }
      // Remove prev after transition completes
      setTimeout(function() {
        slides[prev].classList.remove('prev');
      }, 1300);

      // Start progress + timer for current slide
      startSlide();
    }

    var TRANSITION_LEAD = 600; /* ms to start next slide before video ends */

    function startSlide() {
      clearTimeout(timer);
      var video = getVisibleVideo(slides[current]);
      if (video) {
        // Wait for video metadata to get accurate duration
        function onReady() {
          var dur = getSlideDuration(current);
          var next = Math.max(500, dur - TRANSITION_LEAD);
          animateProgress(current, next);
          scheduleNext(next);
        }
        if (video.readyState >= 1) {
          onReady();
        } else {
          video.addEventListener('loadedmetadata', function handler() {
            video.removeEventListener('loadedmetadata', handler);
            onReady();
          });
        }
      } else {
        animateProgress(current, imageDuration);
        scheduleNext(imageDuration);
      }
    }

    bars.forEach(function(bar, i) {
      bar.addEventListener('click', function() {
        goTo(i);
      });
    });

    // Force play first slide visible video
    var firstVideo = slides[0] && getVisibleVideo(slides[0]);
    if (firstVideo) {
      firstVideo.muted = true;
      firstVideo.playsInline = true;
      firstVideo.play().catch(function(){});
      firstVideo.addEventListener('loadedmetadata', function() {
        firstVideo.play().catch(function(){});
      });
    }

    if (total > 1) startSlide();

    // Wave animation for tagline characters
    var tagline = section.querySelector('.olaboa-hero__tagline');
    if (tagline) {
      var delay = 600; // ms before wave starts
      var charIndex = 0;
      var stagger = 40; // ms between each character

      function wrapTextNodes(el) {
        var nodes = Array.prototype.slice.call(el.childNodes);
        nodes.forEach(function(node) {
          if (node.nodeType === 3) { // text node
            var text = node.textContent;
            var frag = document.createDocumentFragment();
            for (var i = 0; i < text.length; i++) {
              if (text[i] === ' ') {
                var space = document.createElement('span');
                space.className = 'olaboa-wave-space';
                space.textContent = ' ';
                frag.appendChild(space);
                charIndex++;
              } else {
                var span = document.createElement('span');
                span.className = 'olaboa-wave-char';
                span.textContent = text[i];
                span.style.animationDelay = (delay + charIndex * stagger) + 'ms';
                frag.appendChild(span);
                charIndex++;
              }
            }
            node.parentNode.replaceChild(frag, node);
          } else if (node.nodeType === 1) { // element node
            wrapTextNodes(node);
          }
        });
      }
      wrapTextNodes(tagline);
    }
  })();
</script>

{% schema %}
{
  "name": "OlaBoa Hero",
  "settings": [
    {
      "type": "video",
      "id": "logo_video",
      "label": "Logo Video"
    },
    {
      "type": "richtext",
      "id": "tagline",
      "label": "Tagline",
      "default": "<p>The new <strong>wave</strong> of seafood.</p>"
    }
  ],
  "blocks": [
    {
      "type": "slide",
      "name": "Slide",
      "settings": [
        {
          "type": "header",
          "content": "Desktop"
        },
        {
          "type": "image_picker",
          "id": "image",
          "label": "Slide Image"
        },
        {
          "type": "video",
          "id": "video",
          "label": "Slide Video (overrides image)"
        },
        {
          "type": "header",
          "content": "Mobile (optional)"
        },
        {
          "type": "image_picker",
          "id": "image_mobile",
          "label": "Mobile Image"
        },
        {
          "type": "video",
          "id": "video_mobile",
          "label": "Mobile Video (overrides mobile image)"
        }
      ]
    }
  ],
  "presets": [
    {
      "name": "OlaBoa Hero",
      "blocks": [
        { "type": "slide" },
        { "type": "slide" },
        { "type": "slide" },
        { "type": "slide" }
      ]
    }
  ]
}
{% endschema %}
