{% liquid
  assign section_name = 'Timeline'
  assign el_id = section_name | handle | append: '-' | append: section.id

  assign section_padding = section.settings.padding
  assign padding_class = 'sp-' | append: section_padding
  if section.settings.top_half_padding
    assign padding_class = padding_class | append: ' spt-' | append: section_padding | append: '-half'
  endif
  if section.settings.bottom_half_padding
    assign padding_class = padding_class | append: ' spb-' | append: section_padding | append: '-half'
  endif
  if section.settings.bg_overlay
    assign bg_overlay = 'bg-overlay'
  endif
%}
<style>
  #{{ el_id }} .timeline__text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
  } 
  #{{ el_id }} .timeline__indicator--mobile {
    position: relative;
    top: 15px;
  }
  #{{ el_id }} .timeline__indicator__line--mobile {
    height: 1px;
    background-color: var(--light-grey);
  }
  #{{ el_id }} .timeline__indicator--mobile::before {
    content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    width: var(--offset-width, 0);
    height: 2px;
    transition: width 0.3s ease;
    transform: translateY(-0.5px);
    background-image: url({{ 'bg-texture.jpg' | asset_url }});
    z-index: 1;
}

  #{{ el_id }} .timeline__indicator__line--mobile::after {
    transition: width 0.3s ease;
    content: "";
    width: var(--percent-timeline, 0%);
    height: 2px;
    position: absolute;
    top: 0;
    left:0;
    background: var(--light-grey);
    transform: translateY(-0.5px);
  }

  #{{ el_id }} .timeline__logo {
    display: inline-block;
    height: 29px;
    width: 29px;
  }
  #{{ el_id }} .swiper-slide.swiper-slide-active {
    opacity: 1;
  }
  #{{ el_id }} .swiper-slide {
    opacity: 0.5;
    transition: opacity 0.5s ease;
  }
  #{{ el_id }} .swiper-slide .timeline__logo.line-bg:before{
    width: 100%;
    content: "";
    height: 1px;
    position: absolute;
    top: 14px;
    left: 24px;
    background-color: var(--light-grey);
  }

  @media screen and (min-width: 1024px) {
    #{{ el_id }} .timeline__text {
      align-self: stretch;
    }
    #{{ el_id }} {
      overflow: unset;
    }
    #{{ el_id }} .global-image-wrapper {
      position: absolute;
      top: 0;
      left: 0;
    }
    #{{ el_id }} .timeline__rows {
      position: sticky;
      overflow: hidden;
    }
    
    [data-timeline-row] .global-image-wrapper {
      transition: transform 0.5s ease;
      transform: translateY(100%);
    }
    [data-timeline-row].is-selected .global-image-wrapper {
      transform: translateY(0);
    }

    [data-timeline-row] .timeline__indicator {
      position: absolute;
      top: 0;
      left: -20px;
      width: 2px;
      height: 100%;

    } 
    [data-timeline-row] .timeline__line {
      position: absolute;
      top: 0;
      left: 0px;
      width: 1px;
      height: 100%;
      background: var(--light-grey);
      opacity: 0.5;
    }
    [data-timeline-rows] .inner:last-of-type .timeline__indicator .timeline__line {
      display: none;
    }

    [data-timeline-row] .timeline__line:before,
    [data-timeline-row] .timeline__indicator:before, 
    [data-timeline-row] .timeline__indicator:after {
      opacity: 0;
      height: var(--percent-desktop, 0%);
      position: absolute;
      top: 0;
      left: 0;
      min-width: 0;
      max-width: 100%;
      min-height: 0;
      max-height: 100%;
      width: 100%;
      background: red;
      content: "";
    }
    [data-timeline-row] .timeline__indicator:before {
      opacity: .2;
    }
    [data-timeline-row].is-selected .timeline__indicator {
      opacity: 1;
    }
    [data-timeline-row].is-selected .text-col  {
      opacity: 1;
      transition: opacity 0.5s ease;
    }
    [data-timeline-row] .text-col {
      opacity: 0.5;
    }
    .timeline__indicator-logo {
      position: absolute;
      top: -10px;
      left: -13px;
      width: 29px;
      height: 29px;
    }


  }
    
  
</style>

<div id="{{ el_id }}" class="{{ padding_class }} {{ bg_overlay }} overflow">

  {% if section.settings.title != blank %}    
    <{{ section.settings.title_element }} class="timeline__title h4 w-full tc pb-45 d-pb-60">
    {{ section.settings.title }}
    </{{ section.settings.title_element }}>
  {% endif %}

<div data-timeline-holder class="hide-m show-d container" >
  <div data-timeline-rows class="relative row timeline__rows d-flex flex-column jc-center">
    {% if section.blocks.size > 0 %}
      {% for block in section.blocks %}
      <div class="inner {% if forloop.first %} is-selected pt-10 {% endif %}" data-timeline-row>
        <div class="w-full h-full  col-d-5  push-d-1 push-hd-1  absolute top-0">
          <div class=" w-full h-full">
          {% assign image_alt = block.settings.title |  escape %}
          {% render 'global-image-wrapper' 
            image: block.settings.image, 
            image_alt: image_alt, 
            %}
          </div>
          </div>
    
        <div class="text-col hide-m d-flex flex-column row">
          <div class="flex flex-column col-d-4 col-hd-4 push-d-7 d-pb-45 relative">
            {% if block.settings.title != blank %}
              <p class="p5 pb-15">{{ block.settings.title }}</p> 
            {% endif %}
            {% if block.settings.title_2 != blank %}
              <div class="h6 pb-10">{{ block.settings.title_2 }}</div>
            {% endif %}
            {% if block.settings.text != blank %}
              <div class="p3 timeline__text">{{ block.settings.text }}</div>
            {% endif %} 
            <div class="timeline__indicator">
              <span class="timeline__indicator-logo">
                <img src="{{ 'timeline-logo.svg' | asset_url }}" width="29" height="29" alt="logo">
                </span>
              <span class="timeline__line">&nbsp;</span>
            </div>  
          </div>
         
        </div>
      </div>
    {% endfor %}
    {% endif %}
  </div> 
</div>

{% comment %} START mobile view {% endcomment %}
<div class="show-m hide-d">
  <div class=" timeline__indicator--mobile  flex relative ai-center">
    <span class="timeline__indicator__line--mobile" style="--percent-timeline: 0%;"></span>
  </div>
  <div class="swiper show-m hide-d">
    <div class="swiper-wrapper">
        {% if section.blocks.size > 0 %}
            {% for block in section.blocks %}
                <div class="swiper-slide">
                  <div class="timeline__logo mb-30 {% unless forloop.last %}line-bg{% endunless %}">
                    <img src="{{ 'timeline-logo.svg' | asset_url }}" width="29" height="29" alt="logo">
                    
                    </div>
                    {% assign image_alt = block.settings.title |  escape %}
                    {% render 'global-image-wrapper' image: block.settings.image, image_alt: image_alt  %}
                <p class="p5 pt-25 pb-15">{{ block.settings.title }}</p> 
                <div class="h6 pb-10">{{ block.settings.title_2 }}</div>
                <div class="p3 timeline__text">{{ block.settings.text }}</div>   
                </div>
            {% endfor %}
        {% endif %}
    </div>
  </div>
</div>

{% comment %} END mobile view {% endcomment %}

</div>

<script>
  {%- assign func_name_postfix = section.id | replace: '-', '' -%}

  function timeline_{{ func_name_postfix }}() {
   let swiper;
   let swiperInitiated = false;

   function swiper_{{ func_name_postfix }}() {
     if (swiperInitiated) {
       if (swiper) {
         swiper.destroy();
       }
       swiperInitiated = false;
     }

     if (window.innerWidth <= 1024) {
       if (!swiperInitiated) {
         swiperInitiated = true;
         swiper = new Swiper('#{{ el_id }} .swiper', {
           slidesPerView: 1.3,
           spaceBetween: 15,
           slidesOffsetBefore: 15,
           slidesOffsetAfter: 15,
           slideToClickedSlide: true,
           breakpoints: {
             600: {
               slidesOffsetBefore: 20,
               slidesOffsetAfter: 20,
             },
            },
            on: {

              progress: function(swiper, progress) {
                const totalSlides = swiper.slides.length;
                const timelineIndicatorLineWrapper = document.querySelector('#{{ el_id }} .timeline__indicator--mobile');
                const timelineIndicatorLine = document.querySelector('#{{ el_id }} .timeline__indicator__line--mobile');
                const maxProgress = (totalSlides - 1) / totalSlides;
                const clampProgress = Math.min(progress, maxProgress)
                if(progress < 0.018) {
                  timelineIndicatorLineWrapper.style.setProperty("--offset-width", "40px");
                } else {
                  timelineIndicatorLineWrapper.style.setProperty("--offset-width", "0");
                }
                  if(swiper.isEnd){
                  timelineIndicatorLine.style.setProperty("--percent-timeline", `${swiper.params.slidesPerView * 18}%`);
                  } else {
                    timelineIndicatorLine.style.setProperty("--percent-timeline", `${progress * 100}%`);
                  }
                
               

              },
            }
         });
       }
     }
   }


      const selectors = {
        holder: "[data-timeline-holder]",
        rows: "[data-timeline-rows]",
        row: "[data-timeline-row]",
        button: "[data-timeline-button]"
      };

      const classes = {
        selected: "is-selected"
      };

      let requestAnimation = null;
      let rowsHeight = [];
      let rowsWidth = 0;
      let holderTop = 0;
      let holderHeight = (window.innerHeight - $360.headerHeight) * {{ section.blocks.size }};

     function calculateRowsDimensions(holder, rows) {
        rowsHeight = [];
        rowsWidth = 0;

        let prevRowsHeight = 0;
        rows.forEach((row, index) => {
          rowsHeight.push(row.offsetHeight);
          rowsWidth += row.offsetWidth + parseInt(getComputedStyle(row).marginRight);

          // Set CSS variable for row height (Desktop specific behavior if needed)
          // row.style.setProperty("--row-height", `${row.offsetHeight}px`);
          // // You can also add any additional CSS variables for layout adjustments
          // prevRowsHeight += row.offsetHeight;
          // row.style.setProperty("--row-top", `${prevRowsHeight}px`);
        });

        holderTop = holder.getBoundingClientRect().top + window.scrollY;
    }

    function calculatePosition(holder, rows) {
      removeAnimationFrame();
      const elementHeight = holderHeight / rows.length;
      let elementsTop = holderTop;
      const windowMiddle = window.scrollY + window.innerHeight * 1.2; // Adjust middle window trigger

      rows.forEach((row, index) => {
        if (index > 0) {
          const selectedCheck = elementsTop + elementHeight < windowMiddle;
          row.classList.toggle(classes.selected, selectedCheck);

          row.previousElementSibling?.style.setProperty(
            "--percent-desktop",
            `${((windowMiddle - elementsTop) / elementHeight) * 100}%`
          );
        }
        elementsTop += elementHeight;
      });
    }

    function onResize(holder, rows) {
      holderTop = holder.getBoundingClientRect().top + window.scrollY;
      holderHeight = holder.offsetHeight;
      calculateRowsDimensions(holder, rows);
      requestAnimation = requestAnimationFrame(() =>
        calculatePosition(holder, rows)
      );
    }

    function removeAnimationFrame() {
      if (requestAnimation) {
        cancelAnimationFrame(requestAnimation);
        requestAnimation = null;
      }
    }

    function onScrollEvent(holder, rows) {
      if (!requestAnimation) {
        requestAnimation = requestAnimationFrame(() =>
          calculatePosition(holder, rows)
        );
      }
    }

    function initTimeline(section) {
      const holder = document.querySelector(selectors.holder);
      const rows = section.querySelectorAll(selectors.row);
      const buttons = section.querySelectorAll(selectors.button);

      if (rows.length < 2 || !holder) return;

      calculateRowsDimensions(holder, rows);
      requestAnimation = requestAnimationFrame(() =>
        calculatePosition(holder, rows)
      );

      window.addEventListener("scroll", () => onScrollEvent(holder, rows));
      window.addEventListener("resize", () => onResize(holder, rows));

    }

    function initTimelineAnimation() {
      const sections = document.querySelectorAll(selectors.holder);
      
      sections.forEach((section) => initTimeline(section));
    }
    function setTimelineRowsHeight() {
      if(window.innerWidth >= 1024) {
        const headerHeight = $360.headerHeight;
        const image = document.querySelector('#{{ el_id }} .global-image-wrapper');
        const topPadding = 60;
        const imageHeight = image.offsetHeight;
        const rowsElement = document.querySelector('#{{ el_id }} [data-timeline-rows]');
        rowsElement.style.top = `${headerHeight + topPadding}px`;
        rowsElement.style.minHeight = `${imageHeight}px`;
        document.querySelector('#{{ el_id }} [data-timeline-holder]').style.minHeight = holderHeight + 'px';
        


      }      
    }

    if(window.innerWidth >= 1024) {

      initTimelineAnimation()
    }


   document.addEventListener('DOMContentLoaded', function() {
     swiper_{{ func_name_postfix }}();
     setTimelineRowsHeight();
     window.addEventListener('resize', function() {

       setTimelineRowsHeight();
       swiper_{{ func_name_postfix }}();
     });
   });

   document.addEventListener('shopify:section:load', function() {
     setTimelineRowsHeight();
     swiper_{{ func_name_postfix }}();
   });
  }

  timeline_{{ func_name_postfix }}();
</script>

{% schema %}
    {
      "name": "Timeline",
      "settings": [
        {
          "type": "header",
          "content": "Section Padding"
        },
        {
          "type": "select",
          "id": "padding",
          "label": "Padding",
          "options": [
            {
              "value": "no",
              "label": "No"
            },
            {
              "value": "sm",
              "label": "Small"
            },
            {
              "value": "md",
              "label": "Med"
            },
            {
              "value": "lg",
              "label": "Large"
            }
          ],
          "default": "md"
        },
        {
          "type": "checkbox",
          "id": "top_half_padding",
          "label": "Top half padding",
          "default": false
        },
        {
          "type": "checkbox",
          "id": "bottom_half_padding",
          "label": "Bottom half padding",
          "default": false
        },
        {
            "type": "checkbox",
            "id": "bg_overlay",
            "label": "Background Overlay",
            "default": false
        },
        {
          "type": "header",
          "content": "General Settings"
        },
        {
            "type": "text",
            "id": "title",
            "label": "Title"
        },
        {
            "type": "select",
            "id": "title_element",
            "label": "Title Element",
            "options": [
                {
                "value": "h1",
                "label": "h1"
                },
                {
                "value": "h2",
                "label": "h2"
                },
                {
                "value": "h3",
                "label": "h3"
                },
                {
                "value": "h4",
                "label": "h4"
                },
                {
                "value": "h5",
                "label": "h5"
                },
                {
                "value": "h6",
                "label": "h6"
                }
            ],
            "default": "h1"
            }
      ],
      "blocks": [
        {
          "type": "story",
          "name": "Story",    
          "settings": [
            {
              "type": "text",
              "id": "title",
              "label": "Year"
            },
            {
              "type": "text",
              "id": "title_2",
              "label": "Title"
            },
            {
              "type": "textarea",
              "id": "text",
              "label": "Text"
            },
            {
              "type": "image_picker",
              "id": "image",
              "label": "Image"
            }
          ]
        }
      ],
      "presets": [
        {
          "name": "Timeline",
          "blocks": []
        }
      ]
    }
{% endschema %}