/** Shopify CDN: Minification failed

Line 16:0 Unexpected "{"
Line 16:1 Unexpected "{"
Line 16:3 Expected identifier but found "'component-card.css'"
Line 17:0 Unexpected "{"
Line 17:1 Unexpected "{"
Line 17:3 Expected identifier but found "'component-price.css'"
Line 18:0 Unexpected "{"
Line 18:1 Unexpected "{"
Line 18:3 Expected identifier but found "'component-slider.css'"
Line 19:0 Unexpected "{"
... and 328 more hidden warnings

**/
{{ 'component-card.css' | asset_url | stylesheet_tag }}
{{ 'component-price.css' | asset_url | stylesheet_tag }}
{{ 'component-slider.css' | asset_url | stylesheet_tag }}
{{ 'meal-builder.css' | asset_url | stylesheet_tag }}

{%- unless section.settings.quick_add == 'none' -%}
  {{ 'quick-add.css' | asset_url | stylesheet_tag }}
  <script src="{{ 'product-form.js' | asset_url }}" defer="defer"></script>
{%- endunless -%}

{%- if section.settings.quick_add == 'standard' -%}
  <script src="{{ 'quick-add.js' | asset_url }}" defer="defer"></script>
{%- endif -%}

<script src="{{ 'meal-builder.js' | asset_url }}" defer="defer"></script>

{%- comment -%}
Using system fonts and theme defaults for Poppins family
{%- endcomment -%}

{%- style -%}
  /* Design tokens from provided JSON */
  :root {
    --bg: #FBF7F0;
    --panel: #F6F1EA;
    --panel-border: #E5DBCF;
    --ink: #1E1E1E;
    --muted: #6E6B67;
    --brand-green: #2F7A59;
    --brand-orange: #FF7A33;
    --brand-orange-hover: #FF6A1A;
    --badge-new: #2F7A59;
    --badge-sale: #FF7A33;
    --white: #FFFFFF;
    --price-old: #B7B1A9;
    --pill-border: #D9D3CB;
    --radius-xl: 18px;
    --radius-lg: 14px;
    --radius-md: 10px;
    --radius-round: 999px;
    --shadow-soft: 0 6px 16px rgba(0,0,0,0.06);
  }

  .meal-builder {
    font-family: 'Poppins', sans-serif;
    background-color: var(--bg);
    position: relative;
  }

  .meal-builder-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 48px 24px;
    box-sizing: border-box;
    display: grid;
    grid-template-columns: 1fr 380px;
    gap: 40px;
  }

  .meal-builder-main {
    min-width: 0;
  }

  .meal-builder-header {
    margin-bottom: 40px;
  }

  .meal-builder-title {
    font-size: 48px;
    font-weight: 800;
    color: var(--brand-green);
    margin: 0 0 16px 0;
    position: relative;
    display: inline-block;
    line-height: 1.06;
    letter-spacing: -0.5px;
  }

  .meal-builder-title::after {
    content: '';
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: -6px;
    width: 240px;
    height: 8px;
    background: var(--brand-orange);
    border-radius: 4px;
  }

  .meal-builder-subtitle {
    font-size: 16px;
    font-weight: 400;
    color: var(--muted);
    margin: 0;
    line-height: 1.6;
  }

  /* Main Tabs */
  .main-tabs {
    display: flex;
    gap: 8px;
    margin-bottom: 32px;
    border-bottom: 2px solid var(--panel-border);
    padding-bottom: 0;
  }

  .main-tab {
    padding: 14px 24px;
    background: transparent;
    border: none;
    border-bottom: 3px solid transparent;
    font-weight: 600;
    font-size: 16px;
    color: var(--muted);
    cursor: pointer;
    transition: all 0.2s ease;
    font-family: 'Poppins', sans-serif;
  }

  .main-tab.active {
    color: var(--brand-green);
    border-bottom-color: var(--brand-green);
  }

  .main-tab:hover {
    color: var(--brand-green);
  }

  /* Meal Count Target Chips */
  .meal-count-section {
    margin-bottom: 24px;
  }

  .meal-count-label {
    font-size: 16px;
    font-weight: 600;
    color: var(--ink);
    margin-bottom: 12px;
    display: block;
  }

  .meal-count-chips {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .meal-count-chip {
    height: 40px;
    padding: 0 16px;
    border-radius: var(--radius-round);
    border: 1px solid var(--pill-border);
    background-color: var(--white);
    color: var(--brand-green);
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.18s ease;
    font-family: 'Poppins', sans-serif;
  }

  .meal-count-chip.active {
    background-color: var(--brand-green);
    color: var(--white);
    border-color: transparent;
  }

  .meal-count-chip.disabled {
    background-color: #f3f4f6;
    color: #9ca3af;
    border-color: #e5e7eb;
    cursor: not-allowed;
    opacity: 0.6;
  }

  .meal-count-chip.disabled:hover {
    transform: none;
  }

  /* Tooltip styles */
  .meal-builder-tooltip {
    position: absolute;
    background: var(--ink);
    color: var(--white);
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
    z-index: 1000;
    white-space: nowrap;
    opacity: 0;
    transition: opacity 0.2s ease;
    pointer-events: none;
    font-family: 'Poppins', sans-serif;
  }

  .meal-builder-tooltip::before {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    border: 4px solid transparent;
    border-top-color: var(--ink);
  }

  /* Delivery Day Selection */
  .delivery-section {
    margin-bottom: 24px;
  }

  .delivery-label {
    font-size: 16px;
    font-weight: 600;
    color: var(--ink);
    margin-bottom: 12px;
    display: block;
  }

  .delivery-options {
    display: flex;
    gap: 12px;
  }

  .delivery-option {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    border: 1px solid var(--pill-border);
    border-radius: var(--radius-md);
    background: var(--white);
    cursor: pointer;
    transition: all 0.18s ease;
  }

  .delivery-option.active {
    background-color: var(--brand-green);
    color: var(--white);
    border-color: transparent;
  }

  .delivery-option input[type="radio"] {
    appearance: none;
    width: 16px;
    height: 16px;
    border: 2px solid currentColor;
    border-radius: 50%;
    position: relative;
  }

  .delivery-option.active input[type="radio"]:checked::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 6px;
    height: 6px;
    background: var(--white);
    border-radius: 50%;
  }

  /* Meal Type Filters */
  .meal-type-section {
    margin-bottom: 32px;
  }

  .meal-type-label {
    font-size: 16px;
    font-weight: 600;
    color: var(--ink);
    margin-bottom: 12px;
    display: block;
  }

  .meal-type-filters {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .meal-type-filter {
    height: 36px;
    padding: 0 16px;
    border-radius: var(--radius-round);
    border: 1px solid var(--pill-border);
    background-color: var(--white);
    color: var(--brand-green);
    font-weight: 500;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.18s ease;
    font-family: 'Poppins', sans-serif;
  }

  .meal-type-filter.active {
    background-color: var(--brand-green);
    color: var(--white);
    border-color: transparent;
  }

  .meal-type-filter:hover {
    transform: translateY(-1px);
  }

  /* Meals Grid */
  .meals-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 24px;
    margin-bottom: 40px;
  }

  .meal-card {
    background: var(--panel);
    border-radius: var(--radius-xl);
    overflow: hidden;
    box-shadow: var(--shadow-soft);
    transition: transform 0.28s ease, box-shadow 0.28s ease;
    position: relative;
    border: 1px solid var(--panel-border);
    padding: 22px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .meal-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 10px 26px rgba(0,0,0,0.08);
  }

  .meal-image-container {
    position: relative;
    width: calc(100% + 44px);
    left: -22px;
    height: 200px;
    overflow: hidden;
    border-top-left-radius: var(--radius-lg);
    border-top-right-radius: var(--radius-lg);
    margin: -22px 0 16px 0;
    box-sizing: border-box;
  }

  .meal-image-link {
    display: block;
    width: 100%;
    height: 100%;
    text-decoration: none;
  }

  .meal-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
    display: block;
    border-top-left-radius: var(--radius-lg);
    border-top-right-radius: var(--radius-lg);
    transition: transform 0.28s ease;
  }

  .meal-image-link:hover .meal-image {
    transform: scale(1.05);
  }

  .meal-badge {
    position: absolute;
    top: 12px;
    left: 12px;
    padding: 4px 8px;
    border-radius: var(--radius-round);
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .badge-new { background: var(--badge-new); color: var(--white); }
  .badge-sale { background: var(--badge-sale); color: var(--white); }

  .meal-content {
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  .meal-title {
    font-size: 18px;
    font-weight: 700;
    color: var(--brand-green);
    margin: 0 0 8px 0;
    text-align: center;
    line-height: 1.3;
  }

  .meal-title-link {
    color: inherit;
    text-decoration: none;
    transition: color 0.2s ease;
  }

  .meal-title-link:hover {
    color: var(--brand-orange);
  }

  .meal-price {
    text-align: center;
    margin-bottom: 16px;
  }

  .price-current {
    font-size: 18px;
    font-weight: 700;
    color: var(--brand-orange);
  }

  /* Meal Options */
  .meal-options {
    margin-bottom: 16px;
  }

  .option-group {
    margin-bottom: 12px;
  }

  .option-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--ink);
    margin-bottom: 6px;
    display: block;
  }

  .option-pills {
    display: flex;
    gap: 6px;
  }

  .option-pill {
    padding: 6px 12px;
    border: 1px solid var(--pill-border);
    border-radius: var(--radius-round);
    background: var(--white);
    color: var(--brand-green);
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.15s ease;
    font-family: 'Poppins', sans-serif;
  }

  .option-pill.active {
    background: var(--brand-green);
    color: var(--white);
    border-color: transparent;
  }

  .add-meal-button {
    width: 100%;
    height: 42px;
    background: var(--brand-orange);
    color: var(--white);
    border: none;
    border-radius: var(--radius-round);
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.15s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    margin-top: auto;
  }

  .add-meal-button:hover {
    background: var(--brand-orange-hover);
    transform: translateY(-1px);
  }

  .add-meal-button:disabled {
    background: var(--muted);
    cursor: not-allowed;
    transform: none;
  }

  /* Summary Panel */
  .summary-panel {
    background: var(--white);
    border-radius: var(--radius-xl);
    box-shadow: var(--shadow-soft);
    padding: 24px;
    position: sticky;
    top: 24px;
    height: fit-content;
    border: 1px solid var(--panel-border);
  }

  .summary-title {
    font-size: 20px;
    font-weight: 700;
    color: var(--brand-green);
    margin: 0 0 20px 0;
    text-align: center;
  }

  .summary-target {
    background: var(--panel);
    border-radius: var(--radius-md);
    padding: 16px;
    margin-bottom: 20px;
    text-align: center;
  }

  .target-count {
    font-size: 24px;
    font-weight: 800;
    color: var(--brand-green);
    margin: 0;
  }

  .target-label {
    font-size: 12px;
    color: var(--muted);
    margin: 4px 0 0 0;
  }

  .summary-items {
    margin-bottom: 20px;
    max-height: 300px;
    overflow-y: auto;
  }

  .summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid var(--panel-border);
    font-size: 14px;
  }

  .item-name {
    font-weight: 500;
    color: var(--ink);
    flex: 1;
    margin-right: 8px;
  }

  .item-controls {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-right: 8px;
  }

  .qty-controls {
    display: flex;
    align-items: center;
    gap: 4px;
    background: var(--panel);
    border-radius: var(--radius-round);
    padding: 2px;
  }

  .qty-btn {
    width: 20px;
    height: 20px;
    border: none;
    background: var(--white);
    color: var(--brand-green);
    border-radius: 50%;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.15s ease;
    font-family: 'Poppins', sans-serif;
  }

  .qty-btn:hover:not(:disabled) {
    background: var(--brand-green);
    color: var(--white);
    transform: scale(1.1);
  }

  .qty-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .item-qty {
    font-weight: 600;
    color: var(--ink);
    min-width: 20px;
    text-align: center;
    font-size: 12px;
  }

  .item-price {
    font-weight: 600;
    color: var(--brand-orange);
    min-width: 50px;
    text-align: right;
  }

  .summary-totals {
    border-top: 2px solid var(--panel-border);
    padding-top: 16px;
    margin-bottom: 20px;
  }

  .total-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .total-label {
    font-size: 14px;
    color: var(--muted);
  }

  .total-amount {
    font-weight: 600;
    color: var(--ink);
  }

  .total-row.estimate .total-label {
    font-weight: 600;
    color: var(--brand-green);
  }

  .total-row.estimate .total-amount {
    font-size: 18px;
    font-weight: 800;
    color: var(--brand-green);
  }

  .delivery-warning {
    background: #FEF3CD;
    color: #92400E;
    padding: 12px;
    border-radius: var(--radius-md);
    font-size: 13px;
    margin-bottom: 16px;
    text-align: center;
  }

  .checkout-button {
    width: 100%;
    height: 48px;
    background: var(--brand-green);
    color: var(--white);
    border: none;
    border-radius: var(--radius-round);
    font-family: 'Poppins', sans-serif;
    font-weight: 700;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.2s ease;
  }

  .checkout-button:hover:not(:disabled) {
    background: #1F5A3F;
    transform: translateY(-1px);
  }

  .checkout-button:disabled {
    background: var(--muted);
    cursor: not-allowed;
    transform: none;
  }

  /* Hidden tabs content */
  .tab-content {
    display: none;
  }

  .tab-content.active {
    display: block;
  }

  /* Mobile Responsive */
  @media screen and (max-width: 1024px) {
    .meal-builder-container {
      grid-template-columns: 1fr;
      gap: 24px;
      padding: 24px 24px 140px 24px; /* Bottom space for taller sticky cart */
    }

    .summary-panel {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      border-radius: var(--radius-xl) var(--radius-xl) 0 0;
      margin: 0;
      z-index: 1000;
      transform: translateY(calc(100% - 130px)); /* Show 130px of the cart (checkout button visible) */
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      max-height: calc(100vh - env(safe-area-inset-top, 20px));
      max-height: calc(100dvh - env(safe-area-inset-top, 20px));
      overflow: hidden;
      box-shadow: 0 -8px 32px rgba(0,0,0,0.12);
      bottom: env(safe-area-inset-bottom, 0px);
      height: auto;
      display: flex;
      flex-direction: column;
    }

    .summary-panel:not(.expanded) {
      transform: translateY(calc(100% - 130px)); /* Always show 130px including checkout button */
    }

    .summary-panel.expanded {
      transform: translateY(0); /* Fully expanded to top */
      background: var(--white);
      height: calc(100vh - 20px);
      height: calc(100dvh - 20px);
    }

    /* Mobile cart header */
    .mobile-cart-header {
      display: flex;
      flex-direction: column;
      background: var(--white);
      position: relative;
      flex-shrink: 0;
      z-index: 10;
    }

    .mobile-cart-main {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 20px 12px;
    }

    .mobile-cart-info {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .mobile-cart-meals {
      display: flex;
      align-items: center;
      background: var(--brand-green);
      color: var(--white);
      padding: 6px 14px;
      border-radius: var(--radius-round);
      font-weight: 600;
      font-size: 14px; /* Reduced from 16px */
      gap: 2px;
    }

    .mobile-meals-target {
      opacity: 0.8;
    }

    .mobile-meals-text {
      margin-left: 6px;
    }

    .mobile-cart-total {
      font-size: 20px; /* Reduced from 24px */
      font-weight: 800;
      color: var(--brand-green);
    }

    .mobile-cart-expand {
      width: 36px;
      height: 36px;
      border: none;
      background: var(--panel);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s ease;
    }

    .mobile-cart-expand:hover {
      background: var(--brand-green);
      color: var(--white);
    }

    .mobile-cart-expand svg {
      width: 18px;
      height: 18px;
      transition: transform 0.3s ease;
    }

    .summary-panel.expanded .mobile-cart-expand svg {
      transform: rotate(180deg);
    }

    .mobile-checkout-btn {
      background: var(--brand-orange);
      color: var(--white);
      border: none;
      padding: 14px 20px;
      margin: 0 20px 16px;
      border-radius: var(--radius-round);
      font-weight: 600;
      font-size: 16px;
      cursor: pointer;
      transition: all 0.2s ease;
      width: calc(100% - 40px);
    }

    .mobile-checkout-btn:hover:not(:disabled) {
      background: var(--brand-orange-hover);
    }

    .mobile-checkout-btn:disabled {
      background: var(--muted);
      cursor: not-allowed;
    }

    /* Mobile cart body */
    .mobile-cart-body {
      flex: 1;
      overflow-y: auto;
      padding: 0;
      background: var(--white);
      -webkit-overflow-scrolling: touch;
      max-height: 0;
      transition: all 0.3s ease;
    }

    .summary-panel.expanded .mobile-cart-body {
      max-height: calc(100vh - 130px - env(safe-area-inset-top, 20px));
      max-height: calc(100dvh - 130px - env(safe-area-inset-top, 20px));
      padding: 20px;
    }

    /* Hide desktop elements on mobile */
    .summary-toggle {
      display: none;
    }

    .summary-title {
      display: none;
    }

    /* Adjust mobile cart content */
    .summary-target {
      margin-top: 0;
      margin-bottom: 16px;
    }

    .summary-items {
      max-height: none;
      margin-bottom: 16px;
    }

    .summary-totals {
      margin-bottom: 16px;
    }

    .checkout-button {
      display: none; /* Hide desktop checkout button */
    }

    /* Mobile cart overlay */
    .mobile-cart-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.3);
      z-index: 99;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
      backdrop-filter: blur(2px);
    }

    .summary-panel.expanded ~ .mobile-cart-overlay,
    .mobile-cart-overlay.visible {
      opacity: 1;
      visibility: visible;
    }

    /* Progress indicator */
    .mobile-cart-progress {
      width: 100%;
      height: 3px;
      background: var(--panel-border);
      border-radius: 2px;
      overflow: hidden;
      margin-bottom: 16px;
    }

    .mobile-cart-progress-bar {
      height: 100%;
      background: linear-gradient(90deg, var(--brand-green) 0%, var(--brand-orange) 100%);
      border-radius: 2px;
      transition: width 0.3s ease;
      width: 0%;
    }
  }

  @media screen and (max-width: 768px) {
    .meal-builder-title {
      font-size: 32px;
      text-align: center;
    }

    .meal-builder-title::after {
      width: 160px;
    }

    .meal-builder-subtitle {
      text-align: center;
    }

    .meal-count-label,
    .delivery-label,
    .meal-type-label {
      text-align: center;
    }

    .meals-grid {
      grid-template-columns: 1fr;
    }

    .main-tabs {
      overflow-x: auto;
      gap: 4px;
      justify-content: center;
    }

    .main-tab {
      white-space: nowrap;
      padding: 12px 16px;
    }

    .meal-count-chips {
      justify-content: center;
    }

    .meal-type-filters {
      justify-content: center;
    }

    .delivery-options {
      flex-direction: column;
      gap: 8px;
      align-items: center;
    }

    .summary-item {
      flex-wrap: wrap;
      gap: 8px;
      padding: 12px 0;
    }

    .item-name {
      flex-basis: 100%;
      margin-bottom: 4px;
    }

    .item-controls {
      margin-right: 0;
    }

    .qty-controls {
      padding: 4px;
    }

    .qty-btn {
      width: 24px;
      height: 24px;
      font-size: 14px;
    }
  }

  .section-{{ section.id }}-padding {
    padding-top: {{ section.settings.padding_top | times: 0.75 | round: 0 }}px;
    padding-bottom: {{ section.settings.padding_bottom | times: 0.75 | round: 0 }}px;
  }

  @media screen and (min-width: 750px) {
    .section-{{ section.id }}-padding {
      padding-top: {{ section.settings.padding_top }}px;
      padding-bottom: {{ section.settings.padding_bottom }}px;
    }
  }
{%- endstyle -%}

<div class="meal-builder section-{{ section.id }}-padding">
  <div class="meal-builder-container">
    <div class="meal-builder-main">
      <div class="meal-builder-header">
        {%- if section.settings.title != blank -%}
          <h1 class="meal-builder-title">{{ section.settings.title }}</h1>
        {%- endif -%}
        
        {%- if section.settings.subtitle != blank -%}
          <p class="meal-builder-subtitle">{{ section.settings.subtitle }}</p>
        {%- endif -%}
      </div>

      <!-- Main Tabs -->
      <div class="main-tabs">
        <button class="main-tab active" data-tab="meal-prep">
          {{ section.settings.meal_prep_text | default: 'Meal Prep' }}
        </button>
        <button class="main-tab" data-tab="packages">
          {{ section.settings.packages_text | default: 'Packages' }}
        </button>
        <button class="main-tab" data-tab="by-the-pound">
          {{ section.settings.by_pound_text | default: 'By the Pound' }}
        </button>
      </div>

      <!-- Meal Prep Tab Content -->
      <div class="tab-content active" id="meal-prep-content">
        <!-- Meal Count Target -->
        <div class="meal-count-section">
          <label class="meal-count-label">Select your meal count target:</label>
          <div class="meal-count-chips">
            {%- assign min_count = section.settings.min_meal_count | default: 5 -%}
            {%- assign max_count = section.settings.max_meal_count | default: 25 -%}
            {%- assign default_target = section.settings.default_target | default: 10 -%}
            {%- for i in (min_count..max_count) -%}
              {%- if i <= 15 or i == 20 or i == 25 -%}
                <button class="meal-count-chip{% if i == default_target %} active{% endif %}" data-count="{{ i }}">
                  {{ i }}
                </button>
              {%- endif -%}
            {%- endfor -%}
          </div>
        </div>

        <!-- Delivery Day Selection -->
        <div class="delivery-section">
          <label class="delivery-label">Choose your delivery day:</label>
          <div class="delivery-options">
            <label class="delivery-option">
              <input type="radio" name="delivery_day" value="Sunday">
              <span>Sunday</span>
            </label>
            <label class="delivery-option">
              <input type="radio" name="delivery_day" value="Monday">
              <span>Monday</span>
            </label>
          </div>
        </div>

        <!-- Meal Type Filters -->
        <div class="meal-type-section">
          <label class="meal-type-label">Filter by meal type:</label>
          <div class="meal-type-filters">
            <button class="meal-type-filter active" data-meal-type="all">All</button>
            {%- assign meal_types = section.settings.meal_types | split: ',' -%}
            {%- for meal_type in meal_types -%}
              {%- assign trimmed_type = meal_type | strip -%}
              {%- unless trimmed_type == blank -%}
                <button class="meal-type-filter" data-meal-type="{{ trimmed_type | downcase | replace: ' ', '_' }}">
                  {{ trimmed_type }}
                </button>
              {%- endunless -%}
            {%- endfor -%}
          </div>
        </div>

        <!-- Meals Grid -->
        <div class="meals-grid">
          {%- if section.settings.meal_prep_collection.products.size > 0 -%}
            {%- for product in section.settings.meal_prep_collection.products limit: section.settings.products_to_show -%}
              <div class="meal-card" 
                   data-tags="{{ product.tags | join: ',' }}"
                   data-product-id="{{ product.id }}"
                   data-variant-id="{{ product.selected_or_first_available_variant.id }}"
                   data-price-base="{{ product.selected_or_first_available_variant.price }}"
                   data-product-variants="{{ product.variants | json | escape }}">
                
                <div class="meal-image-container">
                  <a href="{{ product.url }}" class="meal-image-link">
                    {%- if product.featured_image -%}
                      <img
                        src="{{ product.featured_image | image_url: width: 600 }}"
                        alt="{{ product.featured_image.alt | escape }}"
                        class="meal-image"
                        loading="lazy"
                        width="600"
                        height="400"
                      >
                    {%- else -%}
                      <div class="meal-image" style="background-color: #f3f4f6; display: flex; align-items: center; justify-content: center; color: #9ca3af;">
                        No image
                      </div>
                    {%- endif -%}
                  </a>
                  
                  {%- if product.tags contains 'new' -%}
                    <span class="meal-badge badge-new">New</span>
                  {%- endif -%}
                  
                  {%- if product.compare_at_price > product.price -%}
                    <span class="meal-badge badge-sale">Sale</span>
                  {%- endif -%}
                </div>
                
                <div class="meal-content">
                  <h3 class="meal-title">
                    <a href="{{ product.url }}" class="meal-title-link">{{ product.title }}</a>
                  </h3>
                  
                  <div class="meal-price">
                    <span class="price-current">{{ product.selected_or_first_available_variant.price | money }}</span>
                  </div>

                  <div class="meal-options">
                    {%- unless product.has_only_default_variant -%}
                      {%- for option in product.options_with_values -%}
                        <div class="option-group">
                          <label class="option-label">{{ option.name }}:</label>
                          <div class="option-pills">
                            {%- for value in option.values -%}
                              <button class="option-pill{% if forloop.first %} active{% endif %}" 
                                      data-option="{{ option.name | downcase | replace: ' ', '_' }}" 
                                      data-option-index="{{ option.position0 }}"
                                      data-value="{{ value }}">
                                {{ value }}
                              </button>
                            {%- endfor -%}
                          </div>
                        </div>
                      {%- endfor -%}
                    {%- endunless -%}
                  </div>
                  
                  <button type="button" class="add-meal-button" 
                          data-variant-id="{{ product.selected_or_first_available_variant.id }}"
                          {%- unless product.available %} disabled{%- endunless %}>
                    {%- if product.available -%}
                      Add Meal
                    {%- else -%}
                      Out of Stock
                    {%- endif -%}
                  </button>
                </div>
              </div>
            {%- endfor -%}
          {%- else -%}
            <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: var(--muted);">
              No meal prep products found. Please configure the meal prep collection in section settings.
            </div>
          {%- endif -%}
        </div>
      </div>

      <!-- Packages Tab Content -->
      <div class="tab-content" id="packages-content">
        <div class="meals-grid">
          {%- if section.settings.packages_collection.products.size > 0 -%}
            {%- for product in section.settings.packages_collection.products limit: section.settings.products_to_show -%}
              <div class="meal-card"
                   data-product-id="{{ product.id }}"
                   data-variant-id="{{ product.selected_or_first_available_variant.id }}"
                   data-price-base="{{ product.selected_or_first_available_variant.price }}"
                   data-product-variants="{{ product.variants | json | escape }}">
                <div class="meal-image-container">
                  <a href="{{ product.url }}" class="meal-image-link">
                    {%- if product.featured_image -%}
                      <img
                        src="{{ product.featured_image | image_url: width: 600 }}"
                        alt="{{ product.featured_image.alt | escape }}"
                        class="meal-image"
                        loading="lazy"
                        width="600"
                        height="400"
                      >
                    {%- endif -%}
                  </a>
                </div>
                
                <div class="meal-content">
                  <h3 class="meal-title">
                    <a href="{{ product.url }}" class="meal-title-link">{{ product.title }}</a>
                  </h3>
                  <div class="meal-price">
                    <span class="price-current">{{ product.selected_or_first_available_variant.price | money }}</span>
                  </div>

                  <div class="meal-options">
                    {%- unless product.has_only_default_variant -%}
                      {%- for option in product.options_with_values -%}
                        <div class="option-group">
                          <label class="option-label">{{ option.name }}:</label>
                          <div class="option-pills">
                            {%- for value in option.values -%}
                              <button class="option-pill{% if forloop.first %} active{% endif %}" 
                                      data-option="{{ option.name | downcase | replace: ' ', '_' }}" 
                                      data-option-index="{{ option.position0 }}"
                                      data-value="{{ value }}">
                                {{ value }}
                              </button>
                            {%- endfor -%}
                          </div>
                        </div>
                      {%- endfor -%}
                    {%- endunless -%}
                  </div>
                  
                  <button type="button" class="add-meal-button" 
                          data-variant-id="{{ product.selected_or_first_available_variant.id }}"
                          data-is-package="true"
                          {%- unless product.available %} disabled{%- endunless %}>
                    {%- if product.available -%}
                      Add Package
                    {%- else -%}
                      Out of Stock
                    {%- endif -%}
                  </button>
                </div>
              </div>
            {%- endfor -%}
          {%- endif -%}
        </div>
      </div>

      <!-- By the Pound Tab Content -->
      <div class="tab-content" id="by-the-pound-content">
        <div class="meals-grid">
          {%- if section.settings.by_pound_collection.products.size > 0 -%}
            {%- for product in section.settings.by_pound_collection.products limit: section.settings.products_to_show -%}
              <div class="meal-card"
                   data-product-id="{{ product.id }}"
                   data-variant-id="{{ product.selected_or_first_available_variant.id }}"
                   data-price-base="{{ product.selected_or_first_available_variant.price }}"
                   data-product-variants="{{ product.variants | json | escape }}">
                <div class="meal-image-container">
                  <a href="{{ product.url }}" class="meal-image-link">
                    {%- if product.featured_image -%}
                      <img
                        src="{{ product.featured_image | image_url: width: 600 }}"
                        alt="{{ product.featured_image.alt | escape }}"
                        class="meal-image"
                        loading="lazy"
                        width="600"
                        height="400"
                      >
                    {%- endif -%}
                  </a>
                </div>
                
                <div class="meal-content">
                  <h3 class="meal-title">
                    <a href="{{ product.url }}" class="meal-title-link">{{ product.title }}</a>
                  </h3>
                  <div class="meal-price">
                    <span class="price-current">{{ product.selected_or_first_available_variant.price | money }}</span>
                  </div>

                  <div class="meal-options">
                    {%- unless product.has_only_default_variant -%}
                      {%- for option in product.options_with_values -%}
                        <div class="option-group">
                          <label class="option-label">{{ option.name }}:</label>
                          <div class="option-pills">
                            {%- for value in option.values -%}
                              <button class="option-pill{% if forloop.first %} active{% endif %}" 
                                      data-option="{{ option.name | downcase | replace: ' ', '_' }}" 
                                      data-option-index="{{ option.position0 }}"
                                      data-value="{{ value }}">
                                {{ value }}
                              </button>
                            {%- endfor -%}
                          </div>
                        </div>
                      {%- endfor -%}
                    {%- endunless -%}
                  </div>
                  
                  <button type="button" class="add-meal-button" 
                          data-variant-id="{{ product.selected_or_first_available_variant.id }}"
                          data-is-by-pound="true"
                          {%- unless product.available %} disabled{%- endunless %}>
                    {%- if product.available -%}
                      Add Item
                    {%- else -%}
                      Out of Stock
                    {%- endif -%}
                  </button>
                </div>
              </div>
            {%- endfor -%}
          {%- endif -%}
        </div>
      </div>
    </div>

    <!-- Summary Panel -->
    <div class="summary-panel">
      <!-- Mobile Cart Header (only visible on mobile) -->
      <div class="mobile-cart-header">
        <div class="mobile-cart-main">
          <div class="mobile-cart-info">
            <div class="mobile-cart-meals">
              <span class="mobile-meals-count">0</span>/<span class="mobile-meals-target">10</span>
              <span class="mobile-meals-text">meals</span>
            </div>
            <div class="mobile-cart-total">$0.00</div>
          </div>
          <button class="mobile-cart-expand" type="button">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="18,15 12,9 6,15"></polyline>
            </svg>
          </button>
        </div>
        <button class="mobile-checkout-btn" disabled>
          Checkout
        </button>
      </div>

      <!-- Mobile Cart Body -->
      <div class="mobile-cart-body">
        <button class="summary-toggle" style="display: none;">
          <span>Cart Summary</span>
        </button>
        
        <h3 class="summary-title">Your Order</h3>
        
        <!-- Progress Indicator -->
        <div class="mobile-cart-progress">
          <div class="mobile-cart-progress-bar"></div>
        </div>
        
        <div class="summary-target" style="display: none;">
          <div class="target-count">{{ section.settings.default_target | default: 10 }}</div>
          <div class="target-label">Meal Target</div>
        </div>

        <div class="summary-items">
          <div class="summary-item" style="display: none;">
            <span class="item-name">Sample Meal</span>
            <div class="item-controls">
              <div class="qty-controls">
                <button class="qty-btn">−</button>
                <span class="item-qty">1</span>
                <button class="qty-btn">+</button>
              </div>
            </div>
            <span class="item-price">$12.99</span>
          </div>
        </div>

        <div class="summary-totals">
          <div class="total-row estimate">
            <span class="total-label">Estimated Total:</span>
            <span class="total-amount">$127.50</span>
          </div>
          <div class="total-row">
            <span class="total-label">Cart Subtotal:</span>
            <span class="total-amount">$0.00</span>
          </div>
          <div class="total-row packages-count" style="display: none;">
            <span class="total-label">Packages:</span>
            <span class="total-amount">0</span>
          </div>
          <div class="total-row by-pound-count" style="display: none;">
            <span class="total-label">By the Pound Items:</span>
            <span class="total-amount">0</span>
          </div>
        </div>

        <div class="delivery-warning">
          Please select a delivery day and add meals to continue
        </div>

        <button class="checkout-button" disabled>
          Checkout
        </button>
      </div>
    </div>

    <!-- Mobile Cart Overlay -->
    <div class="mobile-cart-overlay"></div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Pricing tiers configuration
  const pricingTiers = [
    {"min": 5, "max": 9, "price_per_meal": 13.50},
    {"min": 10, "max": 14, "price_per_meal": 12.75},
    {"min": 15, "max": 19, "price_per_meal": 11.99},
    {"min": 20, "max": 30, "price_per_meal": 10.99}
  ];

  // State
  let selectedTarget = {{ section.settings.default_target | default: 10 }};
  let selectedDelivery = null;
  let selectedMealType = 'all';
  let cart = { items: [], attributes: {}, total_price: 0 };

  // DOM elements
  const mainTabs = document.querySelectorAll('.main-tab');
  const tabContents = document.querySelectorAll('.tab-content');
  const mealCountChips = document.querySelectorAll('.meal-count-chip');
  const deliveryOptions = document.querySelectorAll('.delivery-option');
  const mealTypeFilters = document.querySelectorAll('.meal-type-filter');
  const summaryPanel = document.querySelector('.summary-panel');
  const checkoutButton = document.querySelector('.checkout-button');

  // Helper functions
  function tierPriceFor(count) {
    const tier = pricingTiers.find(t => count >= t.min && count <= t.max) || pricingTiers[pricingTiers.length - 1];
    return tier.price_per_meal;
  }

  function formatMoney(cents) {
    return '$' + (cents / 100).toFixed(2);
  }

  function mealCount(cartData) {
    return cartData.items.reduce((sum, item) => {
      const isMeal = item.properties && item.properties.meal_item === "1";
      return isMeal ? sum + item.quantity : sum;
    }, 0);
  }

  function packageCount(cartData) {
    return cartData.items.reduce((sum, item) => {
      const isPackage = item.properties && item.properties.package_item === "1";
      return isPackage ? sum + item.quantity : sum;
    }, 0);
  }

  function byPoundCount(cartData) {
    return cartData.items.reduce((sum, item) => {
      const isByPound = item.properties && item.properties.by_pound_item === "1";
      return isByPound ? sum + item.quantity : sum;
    }, 0);
  }

  async function fetchCart() {
    try {
      const response = await fetch('/cart.js');
      return await response.json();
    } catch (error) {
      console.error('Error fetching cart:', error);
      return { items: [], attributes: {}, total_price: 0 };
    }
  }

  async function addToCart(variantId, properties = {}) {
    try {
      const formData = new FormData();
      formData.append('id', variantId);
      formData.append('quantity', '1');
      
      Object.keys(properties).forEach(key => {
        formData.append(`properties[${key}]`, properties[key]);
      });

      const response = await fetch('/cart/add.js', {
        method: 'POST',
        body: formData
      });

      if (response.ok) {
        await syncUI();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Error adding to cart:', error);
      return false;
    }
  }

  async function updateDeliveryDay(day) {
    try {
      const formData = new FormData();
      formData.append('note', `Delivery Day: ${day}`);
      
      const response = await fetch('/cart/update.js', {
        method: 'POST',
        body: formData
      });

      if (response.ok) {
        selectedDelivery = day;
        await syncUI();
      }
    } catch (error) {
      console.error('Error updating delivery day:', error);
    }
  }

  async function updateQuantity(lineIndex, newQuantity) {
    try {
      const body = JSON.stringify({
        line: lineIndex,
        quantity: newQuantity,
        sections: ['cart-items'],
        sections_url: window.location.pathname
      });

      const response = await fetch(window.routes.cart_change_url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: body
      });

      if (response.ok) {
        const result = await response.json();
        if (result.errors) {
          console.error('Cart update errors:', result.errors);
          return false;
        }
        await syncUI();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Error updating quantity:', error);
      return false;
    }
  }

  function updateSummaryPanel() {
    const targetElement = document.querySelector('.target-count');
    const summaryItems = document.querySelector('.summary-items');
    const estimateElement = document.querySelector('.total-row.estimate .total-amount');
    const subtotalElement = document.querySelector('.total-row:not(.estimate) .total-amount');
    const deliveryWarning = document.querySelector('.delivery-warning');

    // Mobile elements
    const mobileMealsCount = document.querySelector('.mobile-meals-count');
    const mobileMealsTarget = document.querySelector('.mobile-meals-target');
    const mobileCartTotal = document.querySelector('.mobile-cart-total');
    const mobileCheckoutBtn = document.querySelector('.mobile-checkout-btn');
    const mobileProgressBar = document.querySelector('.mobile-cart-progress-bar');

    // Update target
    if (targetElement) {
      targetElement.textContent = selectedTarget;
    }

    // Update meal count chips disabled state
    const currentMealCount = mealCount(cart);
    mealCountChips.forEach(chip => {
      const chipCount = parseInt(chip.dataset.count);
      const isDisabled = chipCount < currentMealCount;
      chip.classList.toggle('disabled', isDisabled);
      
      // Only allow active state if not disabled
      if (isDisabled && chip.classList.contains('active')) {
        chip.classList.remove('active');
        // Find the next available chip that matches current count or higher
        const availableChip = Array.from(mealCountChips).find(c => 
          parseInt(c.dataset.count) >= currentMealCount && !c.classList.contains('disabled')
        );
        if (availableChip) {
          availableChip.classList.add('active');
          selectedTarget = parseInt(availableChip.dataset.count);
        }
      }
    });

    // Update mobile meal count and target
    if (mobileMealsCount) {
      mobileMealsCount.textContent = currentMealCount;
    }

    if (mobileMealsTarget) {
      mobileMealsTarget.textContent = selectedTarget;
    }

    // Update mobile cart total
    if (mobileCartTotal) {
      mobileCartTotal.textContent = formatMoney(cart.total_price);
    }

    // Update progress bar
    if (mobileProgressBar) {
      const progress = Math.min((currentMealCount / selectedTarget) * 100, 100);
      mobileProgressBar.style.width = progress + '%';
    }

    // Update items list
    if (summaryItems) {
      summaryItems.innerHTML = '';
      
      // First, add meal prep items
      const mealItems = cart.items.filter(item => item.properties && item.properties.meal_item === "1");
      const packageItems = cart.items.filter(item => item.properties && item.properties.package_item === "1");
      const byPoundItems = cart.items.filter(item => item.properties && item.properties.by_pound_item === "1");
      
      // Meal prep items
      mealItems.forEach((item, index) => {
        const actualIndex = cart.items.indexOf(item);
        const lineNumber = actualIndex + 1;
        const itemDiv = document.createElement('div');
        itemDiv.className = 'summary-item';
        itemDiv.innerHTML = `
          <span class="item-name">${item.product_title}</span>
          <div class="item-controls">
            <div class="qty-controls">
              <button class="qty-btn" data-line-index="${lineNumber}" data-action="decrease">−</button>
              <span class="item-qty">${item.quantity}</span>
              <button class="qty-btn" data-line-index="${lineNumber}" data-action="increase">+</button>
            </div>
          </div>
          <span class="item-price">${formatMoney(item.line_price)}</span>
        `;
        summaryItems.appendChild(itemDiv);
      });
      
      // Add separator if there are both meal items and other items
      if (mealItems.length > 0 && (packageItems.length > 0 || byPoundItems.length > 0)) {
        const separator = document.createElement('div');
        separator.className = 'summary-separator';
        separator.innerHTML = '<hr style="border: none; border-top: 2px solid var(--panel-border); margin: 16px 0;">';
        summaryItems.appendChild(separator);
        
        const sectionLabel = document.createElement('div');
        sectionLabel.className = 'summary-section-label';
        sectionLabel.innerHTML = '<span style="font-weight: 600; color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px;">Additional Items</span>';
        summaryItems.appendChild(sectionLabel);
      }
      
      // Package items
      packageItems.forEach((item, index) => {
        const actualIndex = cart.items.indexOf(item);
        const lineNumber = actualIndex + 1;
        const itemDiv = document.createElement('div');
        itemDiv.className = 'summary-item summary-item-package';
        itemDiv.innerHTML = `
          <span class="item-name">${item.product_title} <span style="color: var(--muted); font-size: 11px;">(Package)</span></span>
          <div class="item-controls">
            <div class="qty-controls">
              <button class="qty-btn" data-line-index="${lineNumber}" data-action="decrease">−</button>
              <span class="item-qty">${item.quantity}</span>
              <button class="qty-btn" data-line-index="${lineNumber}" data-action="increase">+</button>
            </div>
          </div>
          <span class="item-price">${formatMoney(item.line_price)}</span>
        `;
        summaryItems.appendChild(itemDiv);
      });
      
      // By the pound items
      byPoundItems.forEach((item, index) => {
        const actualIndex = cart.items.indexOf(item);
        const lineNumber = actualIndex + 1;
        const itemDiv = document.createElement('div');
        itemDiv.className = 'summary-item summary-item-by-pound';
        itemDiv.innerHTML = `
          <span class="item-name">${item.product_title} <span style="color: var(--muted); font-size: 11px;">(By the Pound)</span></span>
          <div class="item-controls">
            <div class="qty-controls">
              <button class="qty-btn" data-line-index="${lineNumber}" data-action="decrease">−</button>
              <span class="item-qty">${item.quantity}</span>
              <button class="qty-btn" data-line-index="${lineNumber}" data-action="increase">+</button>
            </div>
          </div>
          <span class="item-price">${formatMoney(item.line_price)}</span>
        `;
        summaryItems.appendChild(itemDiv);
      });
    }

    // Update estimated total
    const estimatedTotal = tierPriceFor(selectedTarget) * selectedTarget;
    if (estimateElement) {
      estimateElement.textContent = '$' + estimatedTotal.toFixed(2);
    }

    // Update cart subtotal
    if (subtotalElement) {
      subtotalElement.textContent = formatMoney(cart.total_price);
    }

    // Update package and by-pound counts
    const currentPackageCount = packageCount(cart);
    const currentByPoundCount = byPoundCount(cart);
    
    const packagesCountRow = document.querySelector('.packages-count');
    const byPoundCountRow = document.querySelector('.by-pound-count');
    
    if (packagesCountRow) {
      if (currentPackageCount > 0) {
        packagesCountRow.style.display = 'flex';
        packagesCountRow.querySelector('.total-amount').textContent = currentPackageCount;
      } else {
        packagesCountRow.style.display = 'none';
      }
    }
    
    if (byPoundCountRow) {
      if (currentByPoundCount > 0) {
        byPoundCountRow.style.display = 'flex';
        byPoundCountRow.querySelector('.total-amount').textContent = currentByPoundCount;
      } else {
        byPoundCountRow.style.display = 'none';
      }
    }

    // Update delivery warning and checkout button
    // New logic: If no meal prep items but has packages/by-the-pound, only require delivery day
    // If has meal prep items, require both delivery day and meeting target
    const hasMealPrepItems = currentMealCount > 0;
    const hasOtherItems = currentPackageCount > 0 || currentByPoundCount > 0;
    const hasAnyItems = hasMealPrepItems || hasOtherItems;
    
    let canCheckout = false;
    
    if (!hasAnyItems) {
      // No items at all - can't checkout
      canCheckout = false;
    } else if (!hasMealPrepItems && hasOtherItems) {
      // Only packages/by-the-pound items, just need delivery day
      canCheckout = selectedDelivery;
    } else if (hasMealPrepItems) {
      // Has meal prep items, need delivery day AND to meet target
      canCheckout = selectedDelivery && currentMealCount >= selectedTarget;
    }

    if (deliveryWarning) {
      if (!selectedDelivery && hasAnyItems) {
        deliveryWarning.textContent = 'Please select a delivery day to continue';
        deliveryWarning.style.display = 'block';
      } else if (hasMealPrepItems && currentMealCount < selectedTarget) {
        deliveryWarning.textContent = `Add ${selectedTarget - currentMealCount} more meals to reach your target`;
        deliveryWarning.style.display = 'block';
      } else if (!hasAnyItems) {
        deliveryWarning.textContent = 'Add items to your cart to continue';
        deliveryWarning.style.display = 'block';
      } else {
        deliveryWarning.style.display = 'none';
      }
    }

    if (checkoutButton) {
      checkoutButton.disabled = !canCheckout;
    }

    if (mobileCheckoutBtn) {
      mobileCheckoutBtn.disabled = !canCheckout;
    }
  }

  // Tooltip functions
  function showTooltip(element, text) {
    hideTooltip(); // Hide any existing tooltip
    
    const tooltip = document.createElement('div');
    tooltip.className = 'meal-builder-tooltip';
    tooltip.textContent = text;
    
    document.body.appendChild(tooltip);

    const rect = element.getBoundingClientRect();
    tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
    tooltip.style.top = rect.top - tooltip.offsetHeight - 8 + 'px';

    setTimeout(() => tooltip.style.opacity = '1', 10);
    
    window.currentTooltip = tooltip;
    
    // Auto-hide after 3 seconds
    setTimeout(() => {
      hideTooltip();
    }, 3000);
  }

  function hideTooltip() {
    if (window.currentTooltip) {
      window.currentTooltip.remove();
      window.currentTooltip = null;
    }
  }

  async function syncUI() {
    cart = await fetchCart();
    
    // Auto-bump target if needed
    const currentMealCount = mealCount(cart);
    if (currentMealCount > selectedTarget) {
      // Find the next available target that can accommodate the current count
      const availableTargets = Array.from(mealCountChips)
        .map(chip => parseInt(chip.dataset.count))
        .filter(count => count >= currentMealCount)
        .sort((a, b) => a - b);
      
      if (availableTargets.length > 0) {
        selectedTarget = availableTargets[0];
      } else {
        selectedTarget = currentMealCount;
      }
      
      // Update active chip
      mealCountChips.forEach(chip => {
        chip.classList.toggle('active', parseInt(chip.dataset.count) === selectedTarget);
      });
    }

    // Check for existing delivery day
    if (cart.note && cart.note.includes('Delivery Day:') && !selectedDelivery) {
      const deliveryMatch = cart.note.match(/Delivery Day:\s*(Sunday|Monday)/);
      if (deliveryMatch) {
        selectedDelivery = deliveryMatch[1];
        const deliveryInput = document.querySelector(`input[value="${selectedDelivery}"]`);
        if (deliveryInput) {
          deliveryInput.checked = true;
          deliveryInput.closest('.delivery-option').classList.add('active');
        }
      }
    }

    updateSummaryPanel();
  }

  // Event listeners
  mainTabs.forEach(tab => {
    tab.addEventListener('click', function() {
      const targetTab = this.dataset.tab;
      
      // Update active tab
      mainTabs.forEach(t => t.classList.remove('active'));
      this.classList.add('active');
      
      // Show corresponding content
      tabContents.forEach(content => {
        content.classList.toggle('active', content.id === `${targetTab}-content`);
      });
    });
  });

  mealCountChips.forEach(chip => {
    chip.addEventListener('click', function() {
      const targetCount = parseInt(this.dataset.count);
      const currentMealCount = mealCount(cart);
      
      // If chip is disabled (target is less than current meal count), show tooltip
      if (targetCount < currentMealCount) {
        const mealsToRemove = currentMealCount - targetCount;
        showTooltip(this, `Remove ${mealsToRemove} meal${mealsToRemove > 1 ? 's' : ''} from your cart`);
        return;
      }
      
      selectedTarget = targetCount;
      
      mealCountChips.forEach(c => c.classList.remove('active'));
      this.classList.add('active');
      
      updateSummaryPanel();
    });
  });

  deliveryOptions.forEach(option => {
    option.addEventListener('click', function() {
      const radio = this.querySelector('input[type="radio"]');
      const day = radio.value;
      
      deliveryOptions.forEach(opt => opt.classList.remove('active'));
      this.classList.add('active');
      radio.checked = true;
      
      updateDeliveryDay(day);
    });
  });

  mealTypeFilters.forEach(filter => {
    filter.addEventListener('click', function() {
      selectedMealType = this.dataset.mealType;
      
      mealTypeFilters.forEach(f => f.classList.remove('active'));
      this.classList.add('active');
      
      // Filter meal cards
      const mealCards = document.querySelectorAll('#meal-prep-content .meal-card');
      mealCards.forEach(card => {
        const tags = card.dataset.tags || '';
        const shouldShow = selectedMealType === 'all' || 
                          tags.includes(`meal_type_${selectedMealType}`) ||
                          tags.toLowerCase().includes(selectedMealType);
        
        card.style.display = shouldShow ? 'block' : 'none';
      });
    });
  });

  // Option pill handlers
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('option-pill')) {
      const group = e.target.closest('.option-group');
      const pills = group.querySelectorAll('.option-pill');
      
      pills.forEach(pill => pill.classList.remove('active'));
      e.target.classList.add('active');
      
      // Update variant and price when options change
      const card = e.target.closest('.meal-card');
      updateVariantForCard(card);
    }
  });

  // Function to update variant based on selected options
  function updateVariantForCard(card) {
    const productData = getProductData(card);
    if (!productData || !productData.variants) return;

    // Get selected options
    const selectedOptions = [];
    const optionGroups = card.querySelectorAll('.option-group');
    
    optionGroups.forEach((group, index) => {
      const activeOption = group.querySelector('.option-pill.active');
      if (activeOption) {
        selectedOptions[index] = activeOption.dataset.value;
      }
    });

    // Find matching variant
    let matchingVariant = productData.variants.find(variant => {
      return selectedOptions.every((option, index) => {
        return !option || variant.options[index] === option;
      });
    });

    // Fallback to first available variant
    if (!matchingVariant) {
      matchingVariant = productData.variants[0];
    }

    // Update card with new variant data
    if (matchingVariant) {
      const addButton = card.querySelector('.add-meal-button');
      const priceElement = card.querySelector('.price-current');
      
      if (addButton) {
        addButton.dataset.variantId = matchingVariant.id;
        addButton.disabled = !matchingVariant.available;
        addButton.textContent = matchingVariant.available ? 'Add Meal' : 'Out of Stock';
      }
      
      if (priceElement && matchingVariant.price !== undefined) {
        priceElement.textContent = formatMoney(matchingVariant.price);
      }
    }
  }

  // Function to get product data (would need to be populated with actual product data)
  function getProductData(card) {
    try {
      const variantsData = card.dataset.productVariants;
      if (variantsData) {
        const variants = JSON.parse(variantsData);
        return {
          id: card.dataset.productId,
          variants: variants
        };
      }
    } catch (error) {
      console.error('Error parsing product variants:', error);
    }
    
    return null;
  }

  // Add meal button handlers
  document.addEventListener('click', async function(e) {
    if (e.target.classList.contains('add-meal-button')) {
      e.preventDefault();
      
      const button = e.target;
      const card = button.closest('.meal-card');
      const variantId = button.dataset.variantId;
      const isPackage = button.dataset.isPackage;
      const isByPound = button.dataset.isByPound;
      
      // Get selected options for meal prep items
      let properties = {};
      
      // This is a meal prep item
      if (!isPackage && !isByPound) {
        properties.meal_item = "1";
        
        // Add selected variant option values as properties for reference
        const optionGroups = card.querySelectorAll('.option-group');
        optionGroups.forEach(group => {
          const activeOption = group.querySelector('.option-pill.active');
          if (activeOption) {
            const optionName = activeOption.dataset.option;
            const optionValue = activeOption.dataset.value;
            properties[optionName] = optionValue;
          }
        });
      } else if (isPackage) {
        properties.package_item = "1";
        
        // Add selected variant option values as properties for reference
        const optionGroups = card.querySelectorAll('.option-group');
        optionGroups.forEach(group => {
          const activeOption = group.querySelector('.option-pill.active');
          if (activeOption) {
            const optionName = activeOption.dataset.option;
            const optionValue = activeOption.dataset.value;
            properties[optionName] = optionValue;
          }
        });
      } else if (isByPound) {
        properties.by_pound_item = "1";
        
        // Add selected variant option values as properties for reference
        const optionGroups = card.querySelectorAll('.option-group');
        optionGroups.forEach(group => {
          const activeOption = group.querySelector('.option-pill.active');
          if (activeOption) {
            const optionName = activeOption.dataset.option;
            const optionValue = activeOption.dataset.value;
            properties[optionName] = optionValue;
          }
        });
      }
      
      // Update button state
      const originalText = button.innerHTML;
      button.innerHTML = 'Adding...';
      button.disabled = true;
      
      const success = await addToCart(variantId, properties);
      
      // Reset button
      setTimeout(() => {
        button.innerHTML = originalText;
        button.disabled = false;
      }, 1000);
      
      if (!success) {
        alert('Sorry, there was an error adding this item to your cart.');
      }
    }

    // Quantity control handlers
    if (e.target.classList.contains('qty-btn')) {
      e.preventDefault();
      
      const button = e.target;
      const lineIndex = parseInt(button.dataset.lineIndex);
      const action = button.dataset.action;
      const qtyElement = button.closest('.qty-controls').querySelector('.item-qty');
      const currentQty = parseInt(qtyElement.textContent);
      
      let newQty = currentQty;
      if (action === 'increase') {
        newQty = currentQty + 1;
      } else if (action === 'decrease') {
        newQty = currentQty - 1;
        // If quantity would go to 0, remove the item completely
        if (newQty < 1) {
          newQty = 0;
        }
      }
      
      // Update button state
      button.disabled = true;
      const originalText = button.innerHTML;
      button.innerHTML = '⋯';
      
      const success = await updateQuantity(lineIndex, newQty);
      
      // Reset button state (will be updated by syncUI if successful)
      if (!success) {
        setTimeout(() => {
          button.innerHTML = originalText;
          button.disabled = false;
        }, 500);
        alert('Sorry, there was an error updating the quantity. Please try again.');
      }
    }
  });

  // Checkout button handler
  if (checkoutButton) {
    checkoutButton.addEventListener('click', function() {
      if (!this.disabled) {
        window.location.href = '/checkout';
      }
    });
  }

  // Mobile checkout button handler
  const mobileCheckoutBtn = document.querySelector('.mobile-checkout-btn');
  if (mobileCheckoutBtn) {
    mobileCheckoutBtn.addEventListener('click', function() {
      if (!this.disabled) {
        window.location.href = '/checkout';
      }
    });
  }

  // Mobile cart expand/collapse functionality
  const mobileCartMain = document.querySelector('.mobile-cart-main');
  const mobileCartOverlay = document.querySelector('.mobile-cart-overlay');
  const mobileCartExpand = document.querySelector('.mobile-cart-expand');
  
  if (mobileCartMain) {
    mobileCartMain.addEventListener('click', function(e) {
      // Don't toggle if clicking directly on expand button
      if (e.target.closest('.mobile-cart-expand')) {
        return;
      }
      
      summaryPanel.classList.toggle('expanded');
    });
  }

  if (mobileCartExpand) {
    mobileCartExpand.addEventListener('click', function(e) {
      e.stopPropagation();
      summaryPanel.classList.toggle('expanded');
    });
  }

  if (mobileCartOverlay) {
    mobileCartOverlay.addEventListener('click', function() {
      summaryPanel.classList.remove('expanded');
    });
  }

  // Close mobile cart on escape key
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && summaryPanel.classList.contains('expanded')) {
      summaryPanel.classList.remove('expanded');
    }
  });

  // Mobile summary panel toggle (legacy)
  const summaryToggle = document.querySelector('.summary-toggle');
  if (summaryToggle) {
    summaryToggle.addEventListener('click', function() {
      summaryPanel.classList.toggle('expanded');
    });
  }

  // Initialize
  syncUI();

  // Initialize variant selection for all meal cards
  document.querySelectorAll('.meal-card').forEach(card => {
    updateVariantForCard(card);
  });

  // Hide tooltip when clicking anywhere
  document.addEventListener('click', function(e) {
    if (!e.target.classList.contains('meal-count-chip') || !e.target.classList.contains('disabled')) {
      hideTooltip();
    }
  });

  // Responsive handling
  function handleResize() {
    const isMobile = window.innerWidth <= 1024;
    const summaryToggle = document.querySelector('.summary-toggle');
    const mobileCartHeader = document.querySelector('.mobile-cart-header');
    const summaryTitle = document.querySelector('.summary-title');
    const checkoutButton = document.querySelector('.checkout-button');
    
    if (summaryToggle) {
      summaryToggle.style.display = 'none'; // Always hide legacy toggle
    }

    if (mobileCartHeader) {
      mobileCartHeader.style.display = isMobile ? 'flex' : 'none';
    }

    if (summaryTitle) {
      summaryTitle.style.display = isMobile ? 'none' : 'block';
    }

    if (checkoutButton) {
      checkoutButton.style.display = isMobile ? 'none' : 'block';
    }

    // Close mobile cart if switching to desktop
    if (!isMobile && summaryPanel) {
      summaryPanel.classList.remove('expanded');
    }
  }

  // Handle iOS viewport changes
  function handleViewportChange() {
    if (window.innerWidth <= 1024) {
      // Set CSS custom property for current viewport height
      document.documentElement.style.setProperty('--actual-vh', `${window.innerHeight}px`);
      
      // Adjust mobile cart body height dynamically
      const mobileCartBody = document.querySelector('.mobile-cart-body');
      if (mobileCartBody && summaryPanel && summaryPanel.classList.contains('expanded')) {
        mobileCartBody.style.height = `${window.innerHeight * 0.9 - 120}px`;
      }
    }
  }

  // iOS-specific viewport handling
  function setupIOSViewportHandling() {
    // Initial setup
    handleViewportChange();

    // Listen for viewport changes (keyboard show/hide, orientation change)
    window.addEventListener('resize', handleViewportChange);
    window.addEventListener('orientationchange', () => {
      setTimeout(handleViewportChange, 100); // Delay to ensure accurate measurements
    });

    // Listen for visual viewport changes (iOS Safari)
    if (window.visualViewport) {
      window.visualViewport.addEventListener('resize', handleViewportChange);
    }
  }

  window.addEventListener('resize', handleResize);
  handleResize();
  setupIOSViewportHandling();
});
</script>

{% schema %}
{
  "name": "Meal Builder",
  "tag": "section",
  "class": "section",
  "disabled_on": {
    "groups": ["header", "footer"]
  },
  "settings": [
    {
      "type": "header",
      "content": "Content"
    },
    {
      "type": "text",
      "id": "title",
      "default": "Build Your Meal Plan",
      "label": "Heading"
    },
    {
      "type": "textarea",
      "id": "subtitle",
      "default": "Choose your meals, select your delivery day, and enjoy healthy eating made simple.",
      "label": "Subtitle"
    },
    {
      "type": "header",
      "content": "Tab Labels"
    },
    {
      "type": "text",
      "id": "meal_prep_text",
      "default": "Meal Prep",
      "label": "Meal Prep tab text"
    },
    {
      "type": "text",
      "id": "packages_text",
      "default": "Packages",
      "label": "Packages tab text"
    },
    {
      "type": "text",
      "id": "by_pound_text",
      "default": "By the Pound",
      "label": "By the Pound tab text"
    },
    {
      "type": "header",
      "content": "Collections"
    },
    {
      "type": "collection",
      "id": "meal_prep_collection",
      "label": "Meal Prep collection",
      "info": "Collection with meal_prep tag"
    },
    {
      "type": "collection",
      "id": "packages_collection",
      "label": "Packages collection",
      "info": "Collection with package tag"
    },
    {
      "type": "collection",
      "id": "by_pound_collection",
      "label": "By the Pound collection",
      "info": "Collection with by_the_pound tag"
    },
    {
      "type": "range",
      "id": "products_to_show",
      "min": 6,
      "max": 24,
      "step": 3,
      "default": 12,
      "label": "Products to show per tab"
    },
    {
      "type": "header",
      "content": "Meal Count Settings"
    },
    {
      "type": "range",
      "id": "min_meal_count",
      "min": 5,
      "max": 15,
      "step": 1,
      "default": 5,
      "label": "Minimum meal count"
    },
    {
      "type": "range",
      "id": "max_meal_count",
      "min": 15,
      "max": 30,
      "step": 5,
      "default": 25,
      "label": "Maximum meal count"
    },
    {
      "type": "range",
      "id": "default_target",
      "min": 5,
      "max": 20,
      "step": 1,
      "default": 10,
      "label": "Default target count"
    },
    {
      "type": "header",
      "content": "Meal Type Filters"
    },
    {
      "type": "text",
      "id": "meal_types",
      "default": "Lifestyle, Performance, Keto, Chef's Choice, Plant-Based",
      "label": "Meal types (comma separated)",
      "info": "These should match the meal_type_ tags on your products"
    },
    {
      "type": "header",
      "content": "Section padding"
    },
    {
      "type": "range",
      "id": "padding_top",
      "min": 0,
      "max": 100,
      "step": 4,
      "unit": "px",
      "label": "Top padding",
      "default": 60
    },
    {
      "type": "range",
      "id": "padding_bottom",
      "min": 0,
      "max": 100,
      "step": 4,
      "unit": "px",
      "label": "Bottom padding",
      "default": 60
    }
  ],
  "presets": [
    {
      "name": "Meal Builder"
    }
  ]
}
{% endschema %}
