import{composeMemo as e,template as t,DEVICES as s,getResponsiveValueByScreen as i,isLocalEnv as a,baseAssetURL as o}from"@gem-sdk/core";import n from"../../../text/components/Text.liquid.js";import r from"./components/variants/index.liquid.js";import p from"./components/dropdown-swatches/Dropdown.liquid.js";import l from"./components/dropdown-group/DropdownGroup.liquid.js";import{getSettingPreloadData as m}from"../../../helpers.js";import{mappingVariantStyles as d}from"./utils/mappingVariantStyles.js";import{createClass as c,createStyle as u,createStateOrContext as g,createAttr as $,Liquid as v,LiquidFor as f,LiquidIf as y,If as _}from"@gem-sdk/system";import{getAttrs as h}from"./common/main/getAttr.js";import{getVariantOptionGroupStyle as S,getWrapperStyle as V}from"./common/main/styles.js";import{getVariantOptionGroupClass as j,getWrapDropdownClass as I}from"./common/main/classes.js";import{getTextVariantTitleData as b,getDropdownGroupData as w}from"./common/main/getData.js";import{getWrapVariantOptionClass as A}from"./common/variants/classes.js";import{getStyleOfObject as P}from"../../helpers/function.js";import{getMarginBottomStyle as T}from"./common/variants/styles.js";let DEFAULT_ADVANCED_DISPLAY_SETTING={desktop:!0,tablet:!0,mobile:!0},ProductVariants=N=>{let{builderProps:D,styles:x,setting:E,advanced:O}=N,{align:U,swatchItemWidth:C,dropdownItemWidth:K,swatchSpacing:q,optionTypo:k,marginBottom:F}=x??{},{label:G,optionType:J,showAsSwatches:L,layout:R,hasPreSelected:W}=E??{},z=O?.d??DEFAULT_ADVANCED_DISPLAY_SETTING,{uid:H}=D??{},M="groupOption"===J,Q=()=>{let e={};return s.forEach(t=>{let s=i(C,t);e[t]="auto"===s}),e},Y=()=>{let e={};return s.forEach(t=>{e[t]=K?.[t]==="fill"}),e},B=e(()=>{let e=d(E?.variantPresets,x);return{...E,variantPresets:e}},[E?.variantPresets,x]),X=e=>{let t={"'":"&apos;",'"':"&quot;"},s=e;for(let i in t)e.indexOf(i)>=0&&(s=s.replaceAll(i,t[i]));return s},Z=()=>E?.variantPresets?.map(e=>`${X(e.optionName)}($2)${e.optionType}`).join("($1)"),ee=()=>E?.variantPresets?.filter(e=>!!e?.hide)?.map(e=>e.optionName).join(","),et=c(j(U)),es=u(S(q,q)),ei=b(N,"Liquid"),ea=c(A(R,U)),eo=()=>t`
      ${v(`{%- assign presets = "${Z()}" | split: '($1)' -%}`)}
      ${v(`{% assign hiddenPresetOptions = "${ee()}" | split: ',' %}`)}
      
      ${v(`{% assign all_option_names = options | map: 'name' %}
      {% assign filtered_options_string = '' %}
      {% assign delimiter = '||' %}
      
      {% for item_name in all_option_names %}
        {% assign is_excluded = false %}
        {% for exclude_name in hiddenPresetOptions %}
          {% if item_name == exclude_name %}
            {% assign is_excluded = true %}
          {% endif %}
        {% endfor %}
        
        {% unless is_excluded %}
          {% if filtered_options_string == '' %}
            {% assign filtered_options_string = item_name %}
          {% else %}
            {% assign filtered_options_string = filtered_options_string | append: delimiter | append: item_name %}
          {% endif %}
        {% endunless %}
      {% endfor %}
      
      {% assign filtered_options_array = filtered_options_string | split: delimiter %}`)}
      
      ${v("{% assign last_option_name = filtered_options_array | last %}")}
      
      ${f("option in options",`
        <div
        option-name="{{option.name | escape}}"
        class="${ea} ${y("hiddenPresetOptions contains option.name","gp-hidden")}"
        style="${P(T(F))}${v("{% if forloop.last or option.name == last_option_name %}--mb:0;--mb-mobile:0;--mb-tablet:0;{% endif %}")}"
        >
          ${v("{%- assign showVariantClass = 'variant-display' -%}")}
          ${v("{%- assign optionName = option.name  -%}")}
          ${f("preset in presets",`
            ${v("{%- assign presetDetail = preset | split: '($2)' -%}")}
            ${y("presetDetail[1] == 'dropdown' and presetDetail[0] == optionName",`${v("{%- assign showVariantClass = '' -%}")} ${v("{%- break -%}")}`)}
          `)}
          ${_(G,n(ei)," ")}
          <div
              variant-option-name="{{option.name | escape}}"
              class="${et}"
              style="${P(es)}"
            >
              ${v("{%- assign values = option.values -%}")}
              ${v("{%- assign rootForloop = forloop.index0 -%}")}
              ${v(`
                {%- if option.position == 1 -%}
                  {%- assign selectedValue = variant.option1 -%}
                {%- elsif option.position == 2 -%}
                  {%- assign selectedValue = variant.option2 -%}
                {%- else -%}
                  {%- assign selectedValue = variant.option3 -%}
                {%- endif -%}
              `)}
              ${_(!W,v("{%- assign selectedValue = null -%}"),"")}
              ${_(L,er(),ep())}
          </div>
      </div>`)}
    `,en=E?.variantPresets?.map(e=>({name:X(e.optionName),type:e.optionType})).map(e=>`${e.name}($1)${e.type}`).join("($2)").toString(),er=()=>t`
    ${v("{%- assign optionRendered = false -%}")}
    ${v("{%- assign swatches = shop.metafields.GEMPAGES.swatches -%}")}
    ${v("{%- assign swatchesItems = swatches | split: '($1)' -%}")}

    ${f("swatchesItem in swatchesItems",`
      ${v('{%- assign colorArraysString = "" -%}')}
      ${v('{%- assign labelsString = "" -%}')}
      ${v('{%- assign imageUrlsString = "" -%}')}
      ${v("{%- assign attrItems = swatchesItem | split: '($3)' -%}")}

      ${f("attrItem in attrItems",`${v("{%- assign attrs = attrItem | split: '($2)' -%}")}
          ${v("{%- assign optionKey = attrs[0] -%}")}
          ${v("{%- assign optionValue = attrs[1] -%}")}
          ${v(`
            {% if optionKey == 'optionTitle' %}
            {% assign optionTitle = optionValue %}
            {% elsif optionKey == 'optionType' %}
              {% assign optionType = optionValue %}
            {% endif %}
          `)}

          ${y("optionKey == 'optionValues'",`${v("{%- assign opValueItems = optionValue | split: '($4)' -%}")}
            ${f("opValueItem in opValueItems",`${v("{%- assign opValueItemAttrs = opValueItem | split: '($6)' -%}")}
              ${f("opValueItemAttr in opValueItemAttrs",`${v("{%- assign attrs = opValueItemAttr | split: '($5)' -%}")}
                ${v("{%- assign opValueItemKey = attrs[0] -%}")}
                ${v("{%- assign opValueItemValue = attrs[1] -%}")}

                ${y("opValueItemKey == 'label'",`${v("{%- assign labelsString = labelsString | append: opValueItemValue -%}")}${v('{%- assign labelsString = labelsString | append: "($8)" -%}')}`)}

                ${y("opValueItemKey == 'colors'",`${v("{%- assign colorArraysString = colorArraysString | append: opValueItemValue -%}")}${v('{%- assign colorArraysString = colorArraysString | append: "($8)" -%}')}`)}

                ${y("opValueItemKey == 'imageUrl'",`${v("{%- assign imageUrlsString = imageUrlsString | append: opValueItemValue -%}")}${v('{%- assign imageUrlsString = imageUrlsString | append: "($8)" -%}')}`)}`)}`)}`)}
        `)}

      ${v("{%- assign labels = labelsString | split: '($8)' -%}")}
      ${v("{%- assign colorStrings = colorArraysString | split: '($8)' -%}")}
      ${v("{%- assign imageUrls = imageUrlsString | split: '($8)' -%}")}

      ${y("optionTitle == option.name",`
        ${v(`{%- assign variantPresetString = "${en}" -%}`)}
        ${v('{%- assign optionName = option.name | replace: "\'", "&apos;" | replace: \'"\', "&quot;" -%}')}
        ${v("{%- assign items = variantPresetString | split:'($2)' -%}")}
        ${v("{%- assign type = 'dropdown' -%}")}
        ${f("item in items",`
          ${v("{%- assign itemPreset = item | split:'($1)' -%}")}
          ${y("itemPreset[0] == optionName",v("{%- assign type = itemPreset[1] -%}"))}
          ${y('itemPreset[0] == "base"',v("{%- assign type = itemPreset[1] -%}"))}
          `)}
        ${v("{%- assign optionRendered = true -%}")}
        ${f("value in values",r({id:"{{option.name | escape}}-{{value | escape}}",variantKey:"{{option.name | escape}}-{{option.position}}-{{ forloop.index }}",showAsSwatches:L,uid:H,name:"{{option.name | escape}}",value:{label:"{{value | escape}}"},checked:W?"{%- if option.selected_value == value -%}true{% else %}false{%- endif -%}":"false",optionPosition:"rootForloop",optionType:"optionType",activeClass:W?"{%- if option.selected_value == value -%}option-item-active{%- endif -%}":"",...x,...B,swatchAutoWidth:Q(),optionTypo:k}))}
        ${y("type == 'dropdown'",p({...x,...B,swatchAutoWidth:Y(),optionTypo:k}))}
      `)}
    `)}

    ${y("optionRendered == false",ep())}
    `,ep=()=>f("value in values",r({id:"{{option.name | escape}}-{{value | escape}}",variantKey:"{{option.name | escape}}-{{option.position}}-{{ forloop.index }}",showAsSwatches:L,uid:H,name:"{{option.name | escape}}",value:{label:"{{value | escape}}"},checked:W?"{%- if option.selected_value == value -%}true{% else %}false{%- endif -%}":"false",optionPosition:"rootForloop",typeOfOption:"optionType",activeClass:W?"{%- if option.selected_value == value -%}option-item-active{%- endif -%}":"",...x,...B,swatchAutoWidth:Q(),optionTypo:k,isRenderDefault:!0})),el=c(I(U)),em=w(N),ed=()=>`
      <div className="${el}">
        ${l(em)}
      </div>
    `;g({setting:B,styles:JSON.stringify(x),variants:"{{ product.variants | json | escape }}",optionsWithValues:"{{ product.options_with_values | json | escape }}",variantSelected:"{{ variant | json | escape }}",variantInventoryQuantity:"{{ product.variants | map: 'inventory_quantity' | json | escape }}",variantInventoryPolicy:"{{ product.variants | map: 'inventory_policy' | json | escape }}",moneyFormat:"{{ shop.money_format | json | escape }}",productId:"{{ product.id | json | escape }}",productUrl:"{{ product.url | json | escape }}",productHandle:"{{ product.handle | json | escape }}",displayState:`${JSON.stringify(z)}`,totalVariantCombinations:"{{ total_combinations }}",firstAvailableVariant:"{{ product.selected_or_first_available_variant | json | escape }}"});let ec=$(h({uid:H,hasPreSelected:W,cssClass:O?.cssClass})),eu=u(V(N)),eg=c({"gp-flex gp-flex-col !gp-ml-0":!0}),e$=()=>{let e=a?"{{ 'gp-product-variant-v7-5.js' | asset_url }}":`${o}/assets-v2/gp-product-variant-v7-5.js?v={{ shop.metafields.GEMPAGES.ASSETS_VERSION }}`;return`<script ${m('class="gps-link" delay',"src")}="${e}" defer="defer"></script>`};return t`
    ${v("{%- assign total_combinations = 1 -%}")}
    ${f("option in product.options_with_values","{%- assign total_combinations = total_combinations | times: option.values.size -%}")}
    <gp-product-variants
      ${ec}
      gp-data='{
        "setting":${JSON.stringify(B)?.replaceAll("'","&#039;")},
        "styles":${JSON.stringify(x)},
        "variants":{{product.variants | json | escape}},
        "optionsWithValues": {{product.options_with_values | json | escape}},
        "variantSelected": {{ variant | json | escape }},
        "variantInventoryQuantity": {{product.variants | map: 'inventory_quantity' | json | escape}},
        "variantInventoryPolicy": {{product.variants | map: 'inventory_policy' | json | escape}},
        "moneyFormat": {{shop.money_format | json | escape}},
        "productId": {{product.id | json | escape}},
        "productUrl": {{product.url | json | escape}},
        "productHandle": {{product.handle | json | escape}},
        "displayState": ${JSON.stringify(z)},
        "totalVariantCombinations": {{total_combinations}},
        "firstAvailableVariant": {{product.selected_or_first_available_variant | json | escape}}
      }
    '>
      <div class="gp-hidden" style="--hvr-shadow: none; --hvr-shadow-tablet: none; --hvr-shadow-mobile: none"></div>
      ${v("{%- assign options = product.options_with_values -%}")}
      ${v("{%- assign variants = product.variants -%}")}
      ${y("options.size == 0 or options.size == 1 and variants.size == 1 and variants[0].title == 'Default Title' and variants[0].option1 == 'Default Title'","<div></div>",t`<div
            class="${eg}"
            style="${eu}"
          >
          ${_(M,ed(),eo())}
        </div>`)}
    </gp-product-variants>

    ${e$()}
  `};export{ProductVariants as default};
