{# Header Module - Optimized for PageSpeed #}

{# Menu rendering macros - Only for membership menus that need HubL processing #}
{% macro renderMenuItem(node, level) %}
  <li class="menu-item{% if node.children %} has-children{% endif %}{% if node.activeNode %} active{% endif %}">
    <div class="menu-item-content">
      <a href="{{ node.url }}"
         class="menu-link{% if node.activeNode %} active{% endif %}{% if node.activeBranch %} active-branch{% endif %}"
         {% if node.linkTarget %}target="_blank" rel="noopener"{% endif %}
         {% if node.activeNode %}aria-current="page"{% endif %}>
        {{ node.label }}
      </a>
      {% if node.children %}
        <button class="submenu-toggle" aria-expanded="false" aria-label="Toggle submenu">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      {% endif %}
    </div>
    {% if node.children %}
      <ul class="submenu level-{{ level + 1 }}">
        {% for child in node.children %}
          {{ renderMenuItem(child, level + 1) }}
        {% endfor %}
      </ul>
    {% endif %}
  </li>
{% endmacro %}

{# Skip link for accessibility #}
<a href="#main" class="skip-link">Skip to main content</a>

<header class="site-header{% if module.navigation_group.sticky_header %} sticky{% endif %}" role="banner">
  <div class="header-container">
    <div class="header-grid">

      {# Logo - Brand Kit Integration with proper sizing #}
      <div class="header-brand">
        <a href="{{ request.scheme }}://{{ request.domain }}/" class="logo-link" aria-label="{{ site_settings.company_name or 'Home' }}">

          {# Calculate logo dimensions #}
          {% set logo_height = module.logo_group.logo_height or 50 %}
          {% set mobile_scale = module.logo_group.logo_mobile_scale or 75 %}
          {% set logo_height_mobile = (logo_height * mobile_scale / 100)|round %}

          {# Determine logo sources based on brand kit toggle #}
          {# Brand kit structure: primaryLogo = normal, logo = white/dark variant #}
          {% if module.logo_group.use_brand_kit_logo %}
            {# Use Brand Kit logos #}
            {% set logo_src = brand_settings.primaryLogo.src %}
            {% set logo_alt = brand_settings.primaryLogo.alt or site_settings.company_name ~ " logo" %}
            {% set logo_dark_src = brand_settings.logo.src %}
            {% set logo_meta = brand_settings.primaryLogo %}
            {% set logo_dark_meta = brand_settings.logo %}
          {% else %}
            {# Use custom uploaded logos #}
            {% set logo = module.logo_group.logo_override %}
            {% set logo_dark = module.logo_group.logo_dark_override %}
            {% set logo_src = logo.src %}
            {% set logo_dark_src = logo_dark.src or logo_src %}
            {% set logo_alt = logo.alt or site_settings.company_name ~ " logo" %}
            {% set logo_meta = logo %}
            {% set logo_dark_meta = logo_dark %}
          {% endif %}
          
          {# Render logo if we have a source #}
          {% if logo_src %}
            {# Light mode logo #}
            <img class="logo-light"
                 src="{{ logo_src }}"
                 alt="{{ logo_alt }}"
                 {% if logo_meta.width and logo_meta.height %}width="{{ (logo_height * logo_meta.width / logo_meta.height)|round|int }}" height="{{ logo_height }}"{% endif %}
                 loading="eager"
                 fetchpriority="high"
                 decoding="async"
                 style="height: {{ logo_height }}px; width: auto;">

            {# Dark mode logo (only if different from light) #}
            {% if logo_dark_src and logo_dark_src != logo_src %}
              <img class="logo-dark"
                   src="{{ logo_dark_src }}"
                   alt="{{ logo_alt }}"
                   {% if logo_dark_meta.width and logo_dark_meta.height %}width="{{ (logo_height * logo_dark_meta.width / logo_dark_meta.height)|round|int }}" height="{{ logo_height }}"{% endif %}
                   loading="eager"
                   fetchpriority="high"
                   decoding="async"
                   style="height: {{ logo_height }}px; width: auto;">
            {% endif %}
          {% else %}
            {# Fallback to text if no logo #}
            <span class="text-logo">{{ site_settings.company_name or "Company" }}</span>
          {% endif %}
          
        </a>
      </div>

      {# Main Navigation #}
      <nav class="site-nav align-{{ module.navigation_group.menu_alignment }}" role="navigation" aria-label="Main navigation">
        {% if module.mobile_group.enable_mobile_menu %}
          <button class="menu-toggle" aria-label="Toggle menu" aria-expanded="false" type="button">
            <span></span><span></span><span></span>
          </button>
        {% endif %}

        <div class="nav-overlay"></div>
        <div class="nav-menu">

          {# Unified Menu Container #}
          <div class="unified-menu" aria-label="Main navigation">
            <ul class="menu-list menu-primary">
              
              {# Main Menu Items - Convert HubSpot menu to unified structure #}
              {% if module.navigation_group.main_menu %}
                {% set main_menu_tree = menu(module.navigation_group.main_menu) %}
                {% if main_menu_tree.children %}
                  {% for item in main_menu_tree.children %}
                    {{ renderMenuItem(item, 1) }}
                  {% endfor %}
                {% endif %}
              {% endif %}
              
              {# Membership Menu Items - Concatenated in same list #}
              {% if module.membership_group.enable_membership %}
                {% if request_contact.is_logged_in %}
                  {# Logged In Menu Items #}
                  {% if module.membership_group.logged_in_menu %}
                    {% set membership_menu = menu(module.membership_group.logged_in_menu) %}
                    {% if membership_menu.children %}
                      {% for item in membership_menu.children %}
                        {{ renderMenuItem(item, 1) }}
                      {% endfor %}
                    {% endif %}
                  {% endif %}
                  
                  {# Logout as menu item #}
                  {% if module.membership_group.show_logout %}
                    <li class="menu-item logout-item">
                      <div class="menu-item-content">
                        <a href="{{ request.logout_url }}" class="menu-link">
                          {{ module.membership_group.logout_text }}
                        </a>
                      </div>
                    </li>
                  {% endif %}
                {% else %}
                  {# Logged Out Menu Items #}
                  {% if module.membership_group.logged_out_menu %}
                    {% set membership_menu = menu(module.membership_group.logged_out_menu) %}
                    {% if membership_menu.children %}
                      {% for item in membership_menu.children %}
                        {{ renderMenuItem(item, 1) }}
                      {% endfor %}
                    {% endif %}
                  {% endif %}
                  
                  {# Login/Signup as menu items #}
                  {% if module.membership_group.show_auth_links %}
                    <li class="menu-item login-item">
                      <div class="menu-item-content">
                        <a href="{{ module.membership_group.login_url or request.login_url }}" class="menu-link">
                          {{ module.membership_group.login_text }}
                        </a>
                      </div>
                    </li>
                    {% if module.membership_group.show_signup %}
                      <li class="menu-item signup-item">
                        <div class="menu-item-content">
                          <a href="{{ module.membership_group.signup_url or request.signup_url }}" class="menu-link">
                            {{ module.membership_group.signup_text }}
                          </a>
                        </div>
                      </li>
                    {% endif %}
                  {% endif %}
                {% endif %}
              {% endif %}
            </ul>
          </div>

          {# Header Features #}
          <div class="header-features">
            {# Language selector #}
            {% if content.translated_content.values()|selectattr("published")|length or is_listing_view and group.translations %}
              <div class="language-selector">
                <button class="language-toggle" aria-label="{{ locale_name(locale) }}" aria-expanded="false">
                  <span class="language-current">{{ locale_name(locale) }}</span>
                  <span class="language-chevron">▼</span>
                </button>
                <div class="language-menu" aria-hidden="true">
                  {% for translation in content.translated_content.values()|selectattr("published") %}
                    {% if translation.language != locale %}
                      <a href="{{ translation.url }}" hreflang="{{ translation.language }}" lang="{{ translation.language }}">
                        {{ locale_name(translation.language) }}
                      </a>
                    {% endif %}
                  {% endfor %}
                </div>
              </div>
            {% endif %}

            {# Search #}
            {% if module.features_group.show_search %}
              <button class="search-toggle" aria-label="Open search" type="button">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="11" cy="11" r="8"></circle>
                  <path d="m21 21-4.35-4.35"></path>
                </svg>
              </button>
              <div class="search-overlay" aria-hidden="true">
                <div class="search-overlay-backdrop"></div>
                <div class="search-container">
                  <button class="search-close" type="button" aria-label="Close search">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <path d="M18 6L6 18M6 6l12 12"></path>
                    </svg>
                  </button>
                  <form class="search-form" action="/hs-search-results" method="get" role="search">
                    <div class="search-input-wrapper">
                      <svg class="search-input-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"></circle>
                        <path d="m21 21-4.35-4.35"></path>
                      </svg>
                      <input type="search" name="term" placeholder="Search..." required autocomplete="off">
                    </div>
                    <button type="submit" class="search-submit">Search</button>
                  </form>
                  <p class="search-hint">Press ESC to close</p>
                </div>
              </div>
            {% endif %}

            {# CTA Button #}
            {% if module.features_group.show_cta %}
              <a href="{{ module.features_group.cta_url.url.href or '#' }}"
                 class="header-cta"
                 {% if module.features_group.cta_url.open_in_new_tab %}target="_blank" rel="noopener"{% endif %}>
                {{ module.features_group.cta_text }}
              </a>
            {% endif %}
          </div>
        </div>
      </nav>
    </div>
  </div>
</header>

{# Critical Inline CSS - Minimal for above-fold performance #}
<style data-version="2024-12-14-mobile-menu-v3">
  /* Enhanced mobile menu styling - Version 3 */
  
  /* Desktop: level-2 dropdown + JS-positioned level-3 fly-out */
  @media (min-width: {{ (theme.core.layout.mobile_breakpoint or 992) + 1 }}px) {

    /* ── Toggle buttons: hidden on desktop (mobile-only interaction) ── */
    .submenu-toggle { display: none !important; }
    /* Kill any pseudo-elements that theme or portal CSS might add to the button */
    .submenu-toggle::before,
    .submenu-toggle::after { content: none !important; display: none !important; }

    /* ── Kill any pseudo-elements external CSS might add to .menu-item-content ── */
    .submenu .menu-item-content::before,
    .submenu .menu-item-content::after { content: none !important; display: none !important; }

    /* ── Header ancestors must not clip absolutely-positioned panels ── */
    .site-header,
    .header-container,
    .header-grid,
    .site-nav,
    .nav-menu,
    .unified-menu,
    .menu-primary { overflow: visible; }

    /* ── Level-1: positioning context for level-2 ── */
    .menu-primary > .menu-item { position: relative; }

    /* ── Level-2: dropdown below level-1 ── */
    .submenu.level-2 {
      position: absolute;
      top: 100%;
      left: 0;
      min-width: 12rem;
      padding: 0.25rem 0;
      background: var(--color-bg, #fff);
      border: 1px solid var(--color-border, #e5e7eb);
      border-radius: 6px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.08);
      z-index: 1010;
      opacity: 0;
      visibility: hidden;
      pointer-events: none;
      transition: opacity 0.15s ease, visibility 0.15s ease;
    }
    .menu-primary > .menu-item.has-children:hover > .submenu.level-2 {
      opacity: 1;
      visibility: visible;
      pointer-events: auto;
    }

    /* Level-2 item content layout (flex so toggle arrow aligns right) */
    .submenu.level-2 > .menu-item.has-children > .menu-item-content {
      display: flex;
      align-items: center;
    }
    .submenu.level-2 > .menu-item.has-children > .menu-item-content > .menu-link { flex: 1; }

    /* ── Level-3: shown/hidden and positioned entirely by JS ──────────────
       JS uses position:fixed with exact viewport coords to avoid any
       containing-block or overflow:hidden issues.
    ────────────────────────────────────────────────────────────────────── */
    .submenu.level-3 {
      position: absolute; /* JS overrides this to fixed with inline style */
      min-width: 12rem;
      padding: 0.25rem 0;
      background: var(--color-bg, #fff);
      border: 1px solid var(--color-border, #e5e7eb);
      border-radius: 6px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.08);
      z-index: 9999;
      opacity: 0;
      visibility: hidden;
      pointer-events: none;
      transition: opacity 0.15s ease, visibility 0.15s ease;
    }
    .submenu.level-3.is-open {
      opacity: 1;
      visibility: visible;
      pointer-events: auto;
    }

    /* ── Shared dropdown link styles ── */
    .submenu .menu-item { display: block; }
    .submenu .menu-link { display: block; padding: 0.5rem 1rem; white-space: nowrap; }

    /* ── HubSpot native menu fallback ── */
    .main-menu .hs-menu-children-wrapper {
      position: absolute;
      top: 100%;
      left: 0;
      min-width: 12rem;
      padding: 0.25rem 0;
      background: var(--color-bg, #fff);
      border: 1px solid var(--color-border, #e5e7eb);
      border-radius: 6px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.08);
      z-index: 1010;
      opacity: 0;
      visibility: hidden;
      pointer-events: none;
      transition: opacity 0.15s ease, visibility 0.15s ease;
    }
    .main-menu .hs-item-has-children:hover > .hs-menu-children-wrapper {
      opacity: 1;
      visibility: visible;
      pointer-events: auto;
    }
    .main-menu .hs-menu-children-wrapper > li { display: block; }
    .main-menu .hs-menu-children-wrapper a { display: block; padding: 0.5rem 1rem; white-space: nowrap; }
  }

  /* Mobile: Position arrows properly */
  @media (max-width: {{ theme.core.layout.mobile_breakpoint or 992 }}px) {
    /* Ensure arrows are visible and positioned right */
    .submenu-toggle,
    .menu-arrow {
      display: flex !important;
      position: absolute !important;
      right: 0 !important;
      top: 50% !important;
      transform: translateY(-50%) !important;
      width: 44px !important;
      height: 44px !important;
      align-items: center !important;
      justify-content: center !important;
      z-index: 2 !important;
    }

    /* Prevent text overlap with arrow */
    .menu-link,
    .nav-menu a {
      padding-right: 3rem !important;
    }

    /* Hide submenus by default on mobile */
    .submenu.level-2,
    .submenu.level-3,
    .nav-menu .hs-menu-children-wrapper {
      display: none !important;
    }

    /* Show when toggled - ALL submenu types */
    .menu-item.submenu-open > .submenu.level-2,
    .menu-item.submenu-open > .submenu.level-3,
    .hs-item-has-children.submenu-open > .hs-menu-children-wrapper {
      display: block !important;
    }
  }
  
  .skip-link {
    position: absolute;
    left: -9999px;
    top: -50px;
    z-index: 999;
    padding: 1em;
    background: #000;
    color: #fff;
    text-decoration: none;
  }
  .skip-link:focus {
    left: 50%;
    transform: translateX(-50%);
    top: 0;
  }
  
  .site-header {
    position: relative;
    z-index: 1000;
    /* Use theme CSS variables, with module overrides if set */
    background: {{ module.styles.colors.background_color.color or 'var(--color-bg, #ffffff)' }};
    color: {{ module.styles.colors.text_color.color or 'var(--color-text, #333333)' }};
    {% if module.styles.appearance.border_bottom %}border-bottom: 1px solid {{ module.styles.colors.border_color.color or '#E5E5E5' }};{% endif %}
    {% if module.styles.appearance.header_height %}min-height: {{ module.styles.appearance.header_height }}px;{% endif %}
    --header-height: {{ module.styles.appearance.header_height or 70 }}px;
  }
  
  /* Menu toggle uses the theme text colour (flips in dark mode). Was `inherit`,
     which picked up the wrong colour for the hamburger/X bars. */
  .menu-toggle {
    color: var(--color-text, #333333);
  }
  
  .menu-toggle span {
    background: currentColor;
  }
  
  /* Logo sizing with proper responsive behavior */
  .header-brand img {
    object-fit: contain;
    width: auto;
    height: auto;
  }

  /* Logo visibility - Light mode default */
  .logo-light {
    display: block;
  }
  .logo-dark {
    display: none;
  }
  
  /* Mobile responsive logo sizing */
  @media (max-width: {{ theme.core.layout.mobile_breakpoint or 992 }}px) {
    .header-brand img {
      height: {{ (module.logo_group.logo_height or 50) * (module.logo_group.logo_mobile_scale or 75) / 100 | round }}px !important;
      width: auto !important;
    }
  }
  
  .site-header.sticky { position: sticky; top: 0; }
  .container { padding: 0 16px; }
  .container.boxed { max-width: {{ theme.core.layout.container_width or 1200 }}px; margin: 0 auto; }
  .container.wide { max-width: {{ (theme.core.layout.container_width or 1200) * 1.167 | round }}px; margin: 0 auto; }
  .header-grid { 
    display: flex; 
    align-items: center; 
    justify-content: space-between; 
    gap: 2rem;
    padding-top: {{ module.styles.appearance.header_padding_top or 15 }}px;
    padding-bottom: {{ module.styles.appearance.header_padding_bottom or 15 }}px;
  }
  .header-brand { flex-shrink: 0; }
  .site-nav { flex-grow: 1; display: flex; align-items: center; min-width: 0; }
  .site-nav.align-left { justify-content: flex-start; }
  .site-nav.align-center { justify-content: center; }
  .site-nav.align-right { justify-content: flex-end; }
  .nav-menu { display: flex; align-items: center; gap: 2rem; min-width: 0; }
  .menu-toggle { display: none; }

  {# ~3.5KB of search CSS — only inline it when Show Search is on (global module,
     so this CSS would otherwise ship on every page even though show_search
     defaults to false). The overlay markup is already conditional. #}
  {% if module.features_group.show_search %}
  /* Search toggle - clean icon style matching nav text */
  .search-toggle {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: transparent;
    border: none;
    padding: 0;
    cursor: pointer;
    color: {{ module.styles.colors.link_color.color or 'var(--color-text, #333333)' }};
    transition: color 0.2s ease, opacity 0.2s ease;
  }
  .search-toggle:hover {
    color: {{ module.styles.colors.link_hover_color.color or 'var(--color-primary, #007BFF)' }};
    opacity: 0.8;
  }
  .search-toggle svg {
    width: 20px;
    height: 20px;
  }

  /* Search overlay - fullscreen modal */
  .search-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding-top: 15vh;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.25s ease, visibility 0.25s ease;
  }
  .search-overlay.active {
    opacity: 1;
    visibility: visible;
  }
  .search-overlay-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
  }
  .search-container {
    position: relative;
    width: 90%;
    max-width: 600px;
    background: #fff;
    border-radius: 12px;
    padding: 2rem;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    transform: translateY(-20px);
    transition: transform 0.25s ease;
  }
  .search-overlay.active .search-container {
    transform: translateY(0);
  }
  .search-close {
    position: absolute;
    top: 1rem;
    right: 1rem;
    background: transparent;
    border: none;
    padding: 0.5rem;
    cursor: pointer;
    color: var(--color-text-muted, #666);
    border-radius: 50%;
    transition: background 0.2s ease, color 0.2s ease;
  }
  .search-close:hover {
    background: var(--color-bg-tertiary, #f3f4f6);
    color: var(--color-text, #333);
  }
  .search-form {
    display: flex;
    gap: 0.75rem;
  }
  /* Push the form below the absolutely-positioned close (X) button so the
     Search submit button doesn't overlap it. Scoped to the open overlay. */
  .search-overlay.active .search-form {
    margin-top: 25px;
  }
  .search-input-wrapper {
    flex: 1;
    position: relative;
    display: flex;
    align-items: center;
  }
  .search-input-icon {
    position: absolute;
    left: 1rem;
    color: var(--color-text-muted, #9ca3af);
    pointer-events: none;
  }
  .search-form input[type="search"] {
    width: 100%;
    padding: 1rem 1rem 1rem 3rem;
    font-size: 1.125rem;
    border: 2px solid var(--color-border, #e5e7eb);
    border-radius: 8px;
    outline: none;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
  }
  .search-form input[type="search"]:focus {
    border-color: {{ module.styles.colors.link_hover_color.color or '#007BFF' }};
    box-shadow: 0 0 0 3px {{ module.styles.colors.link_hover_color.color or '#007BFF' }}20;
  }
  .search-form input[type="search"]::placeholder {
    color: var(--color-text-muted, #9ca3af);
  }
  .search-submit {
    padding: 1rem 1.5rem;
    background: {{ module.styles.colors.link_hover_color.color or '#007BFF' }};
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    transition: background 0.2s ease, transform 0.1s ease;
  }
  .search-submit:hover {
    filter: brightness(1.1);
  }
  .search-submit:active {
    transform: scale(0.98);
  }
  .search-hint {
    margin: 1rem 0 0;
    font-size: 0.875rem;
    color: var(--color-text-muted, #9ca3af);
    text-align: center;
  }

  /* Dark mode search overlay */
  @media (prefers-color-scheme: dark) {
    .search-container {
      background: var(--color-bg-secondary);
    }
    .search-close {
      color: var(--color-text-muted);
    }
    .search-close:hover {
      background: var(--color-bg-tertiary);
      color: var(--color-text);
    }
    .search-form input[type="search"] {
      background: var(--color-bg);
      border-color: var(--color-border);
      color: var(--color-text);
    }
    .search-form input[type="search"]:focus {
      border-color: {{ module.styles.colors.link_hover_color.color or '#007BFF' }};
    }
  }
  {% endif %}

  /* CTA Button - uses module color settings with brand color fallback */
  .header-cta {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.625rem 1.25rem;
    font-size: 0.875rem;
    font-weight: 600;
    text-decoration: none;
    border-radius: 6px;
    border: none;
    cursor: pointer;
    transition: background-color 0.2s ease, transform 0.1s ease, box-shadow 0.2s ease;
    white-space: nowrap;
    background-color: {{ module.styles.buttons.cta_background_color.color or 'var(--color-primary, #007BFF)' }};
    color: {{ module.styles.buttons.cta_text_color.color or '#FFFFFF' }} !important;
  }
  .header-cta:hover {
    background-color: {{ module.styles.buttons.cta_hover_background_color.color or 'var(--color-primary-dark, #0056b3)' }};
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    color: {{ module.styles.buttons.cta_text_color.color or '#FFFFFF' }} !important;
  }
  .header-cta:active {
    transform: translateY(0);
    box-shadow: none;
  }

  @media (max-width: {{ theme.core.layout.mobile_breakpoint or 992 }}px) {
    /* Prevent horizontal scroll when mobile menu is present */
    html, body {
      overflow-x: hidden !important;
    }

    .menu-toggle {
      display: inline-flex;
      flex-direction: column;
      gap: 4px;
      background: transparent;
      border: 0;
      padding: 0.5rem;
      cursor: pointer;
      z-index: 1001;
    }
    .menu-toggle span {
      display: block;
      width: 24px;
      height: 2px;
      background: currentColor;
      transition: all 0.3s ease;
    }
    .menu-toggle.active span:nth-child(1) { transform: rotate(45deg) translate(5px, 5px); }
    .menu-toggle.active span:nth-child(2) { opacity: 0; }
    .menu-toggle.active span:nth-child(3) { transform: rotate(-45deg) translate(5px, -5px); }

    .nav-menu {
      position: fixed !important;
      top: 0 !important;
      right: 0 !important;
      width: 100% !important; /* Full width mobile menu */
      height: 100vh !important;
      height: 100dvh !important; /* Dynamic viewport height for mobile */
      background: {{ module.styles.colors.background_color.color or '#ffffff' }} !important;
      color: {{ module.styles.colors.text_color.color or '#333333' }} !important;
      /* Parked off-screen to the RIGHT while closed → closing slides OUT to the
         right. Opening runs the slide-in-from-LEFT keyframe (below). */
      transform: translateX(100%) !important;
      visibility: hidden !important; /* Hide when off-screen */
      pointer-events: none !important; /* Prevent interaction when hidden */
      transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1), visibility 0s 0.35s !important; /* Delay visibility until after transform */
      display: flex !important;
      flex-direction: column !important;
      padding: 4rem 1.5rem 2rem !important;
      overflow-y: auto !important;
      -webkit-overflow-scrolling: touch !important; /* Smooth iOS scrolling */
      overscroll-behavior: contain !important; /* Prevent scroll chaining */
      box-shadow: -4px 0 12px rgba(0,0,0,0.15) !important; /* Enhanced shadow */
      z-index: 1000 !important;
      will-change: transform; /* Optimize for animation */
    }
    .nav-menu.open {
      transform: translateX(0) !important; /* Resting (open) position */
      visibility: visible !important; /* Show when open */
      pointer-events: auto !important; /* Enable interaction when visible */
      /* Slide IN from the left on open; on close the class is removed and it
         transitions back to the parked translateX(100%) → OUT to the right. */
      animation: navMenuSlideInLeft 0.35s cubic-bezier(0.4, 0, 0.2, 1) !important;
      transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1), visibility 0s 0s !important; /* Immediate visibility on open */
    }
    @keyframes navMenuSlideInLeft {
      from { transform: translateX(-100%); }
      to   { transform: translateX(0); }
    }
    
    /* Overlay backdrop */
    .nav-overlay {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100vh;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
      opacity: 0;
      transition: opacity 0.3s ease;
    }
    .nav-overlay.active {
      display: block;
      opacity: 1;
    }
    
    /* Mobile menu accordion styles */
    .nav-menu .hs-menu-wrapper > ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    
    /* Top level menu items */
    .nav-menu .hs-menu-item {
      position: relative;
      border-bottom: 1px solid rgba(127, 131, 139, 0.24);
    }
    
    .nav-menu .hs-menu-item > a {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 1rem 0;
      color: {{ module.styles.colors.link_color.color or '#333333' }};
      text-decoration: none;
      font-weight: 500;
      transition: color 0.2s ease;
    }
    
    .nav-menu .hs-menu-item > a:hover {
      color: {{ module.styles.colors.link_hover_color.color or '#007bff' }};
    }
    
    /* Submenu toggle arrow */
    .nav-menu .hs-menu-item.hs-item-has-children > a::after {
      content: '';
      display: inline-block;
      width: 0;
      height: 0;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-top: 5px solid currentColor;
      margin-left: auto;
      transition: transform 0.3s ease;
    }
    
    .nav-menu .hs-menu-item.hs-item-has-children.submenu-open > a::after {
      transform: rotate(180deg);
    }
    
    /* Submenu items - hidden by default */
    .nav-menu .hs-menu-children-wrapper {
      display: none;
      position: static !important;
      width: 100%;
      background: transparent;
      box-shadow: none;
      border: none;
      padding: 0;
      margin: 0;
      opacity: 1 !important;
      visibility: visible !important;
      transform: none !important;
    }
    
    .nav-menu .hs-menu-item.submenu-open .hs-menu-children-wrapper {
      display: block;
    }
    
    /* Indented submenu items */
    .nav-menu .hs-menu-children-wrapper a {
      display: block;
      padding: 0.75rem 0 0.75rem 1.5rem;
      color: {{ module.styles.colors.link_color.color or '#666666' }};
      text-decoration: none;
      font-size: 0.95em;
      border-bottom: 1px solid rgba(127, 131, 139, 0.18);
      transition: all 0.2s ease;
    }
    
    .nav-menu .hs-menu-children-wrapper a:hover {
      color: {{ module.styles.colors.link_hover_color.color or '#007bff' }};
      padding-left: 1.75rem;
      background: rgba(127, 131, 139, 0.08);
    }
  }
</style>

{% if theme.dark_mode.enabled %}
{# Dark mode styles - only loaded if theme setting is enabled #}
<style>
  @media (prefers-color-scheme: dark) {
    /* Header dark mode - uses CSS variables for automatic switching */
    .site-header {
      background: var(--color-bg);
      border-bottom-color: var(--color-border);
    }

    .menu-link,
    .nav-menu a,
    .nav-menu .menu-link,
    .nav-menu .hs-menu-item > a,
    .nav-menu .hs-menu-children-wrapper a {
      color: var(--color-text) !important;
    }

    .menu-link:hover,
    .nav-menu a:hover,
    .nav-menu .menu-link:hover,
    .nav-menu .hs-menu-item > a:hover,
    .nav-menu .hs-menu-children-wrapper a:hover {
      color: {{ module.styles.colors.link_hover_color.color or 'var(--color-primary, #007BFF)' }} !important;
      opacity: 1;
    }

    /* Logo switching for dark mode */
    .logo-light {
      display: none !important;
    }

    .logo-dark {
      display: block !important;
    }

    /* If no dark logo provided, invert the light one */
    .logo-light:only-child {
      display: block !important;
      filter: brightness(0) invert(1);
      opacity: 0.9;
    }

    /* Mobile slide-in menu only. Scoped to mobile so the DESKTOP horizontal nav
       stays transparent on the dark header — unscoped, this painted a grey bar
       behind the desktop nav. On mobile the dark bg is needed so the light link
       text stays readable. */
    @media (max-width: {{ theme.core.layout.mobile_breakpoint or 992 }}px) {
      .nav-menu {
        background: var(--color-bg-secondary) !important;
        color: var(--color-text) !important;
      }
    }

    .nav-overlay {
      background: rgba(0, 0, 0, 0.7);
    }

    /* Dropdown dark mode */
    .hs-menu-children-wrapper,
    .submenu {
      background: var(--color-bg-secondary);
      border-color: var(--color-border);
    }

    /* Buttons in dark mode */
    .header-cta {
      background: var(--color-primary);
      color: #fff;
      border-color: var(--color-primary);
    }
  }

  /* Manual dark mode toggle — same rules for [data-theme-override="dark"] */
  [data-theme-override="dark"] .site-header {
    background: var(--color-bg);
    border-bottom-color: var(--color-border);
  }

  [data-theme-override="dark"] .menu-link,
  [data-theme-override="dark"] .nav-menu a,
  [data-theme-override="dark"] .nav-menu .menu-link,
  [data-theme-override="dark"] .nav-menu .hs-menu-item > a,
  [data-theme-override="dark"] .nav-menu .hs-menu-children-wrapper a {
    color: var(--color-text) !important;
  }

  [data-theme-override="dark"] .menu-link:hover,
  [data-theme-override="dark"] .nav-menu a:hover,
  [data-theme-override="dark"] .nav-menu .menu-link:hover,
  [data-theme-override="dark"] .nav-menu .hs-menu-item > a:hover,
  [data-theme-override="dark"] .nav-menu .hs-menu-children-wrapper a:hover {
    color: {{ module.styles.colors.link_hover_color.color or 'var(--color-primary, #007BFF)' }} !important;
    opacity: 1;
  }

  [data-theme-override="dark"] .logo-light { display: none !important; }
  [data-theme-override="dark"] .logo-dark { display: block !important; }
  [data-theme-override="dark"] .logo-light:only-child {
    display: block !important;
    filter: brightness(0) invert(1);
    opacity: 0.9;
  }

  /* Mobile slide-in menu only (see the prefers-color-scheme note above). */
  @media (max-width: {{ theme.core.layout.mobile_breakpoint or 992 }}px) {
    [data-theme-override="dark"] .nav-menu {
      background: var(--color-bg-secondary) !important;
      color: var(--color-text) !important;
    }
  }

  [data-theme-override="dark"] .nav-overlay { background: rgba(0, 0, 0, 0.7); }

  [data-theme-override="dark"] .hs-menu-children-wrapper,
  [data-theme-override="dark"] .submenu {
    background: var(--color-bg-secondary);
    border-color: var(--color-border);
  }

  [data-theme-override="dark"] .header-cta {
    background: var(--color-primary);
    color: #fff;
    border-color: var(--color-primary);
  }

</style>
{% endif %}

{# Optimized Mobile Menu JavaScript - Reduced TBT #}
<script>
{% if module.mobile_group.enable_mobile_menu %}
(function() {
  // Defer non-critical initialization to reduce TBT
  const initMobileMenu = function() {
    const toggle = document.querySelector('.menu-toggle');
    const menu = document.querySelector('.nav-menu');
    const overlay = document.querySelector('.nav-overlay');
    
    if (toggle && menu) {
      // Toggle menu on button click
      toggle.addEventListener('click', function(e) {
        e.stopPropagation();
        const isOpen = menu.classList.contains('open');
        
        // Toggle classes
        menu.classList.toggle('open');
        toggle.classList.toggle('active');
        if (overlay) {
          overlay.classList.toggle('active');
        }
        
        // Update ARIA attributes
        toggle.setAttribute('aria-expanded', !isOpen);
        toggle.setAttribute('aria-label', isOpen ? 'Open menu' : 'Close menu');
        
        // Prevent body scroll when menu is open
        if (!isOpen) {
          document.body.style.overflow = 'hidden';
          document.body.style.position = 'fixed';
          document.body.style.width = '100%';
          document.body.style.top = `-${window.scrollY}px`;
          document.body.setAttribute('data-scroll-position', window.scrollY);
        } else {
          const scrollY = document.body.getAttribute('data-scroll-position') || 0;
          document.body.style.overflow = '';
          document.body.style.position = '';
          document.body.style.width = '';
          document.body.style.top = '';
          window.scrollTo(0, parseInt(scrollY));
        }
      });
      
      // (Removed dead .menu-close handler — no such element is rendered; audit L1.)

      // Close menu when clicking overlay
      if (overlay) {
        overlay.addEventListener('click', function() {
          menu.classList.remove('open');
          toggle.classList.remove('active');
          overlay.classList.remove('active');
          toggle.setAttribute('aria-expanded', 'false');
          toggle.setAttribute('aria-label', 'Open menu');

          // Restore body scroll
          const scrollY = document.body.getAttribute('data-scroll-position') || 0;
          document.body.style.overflow = '';
          document.body.style.position = '';
          document.body.style.width = '';
          document.body.style.top = '';
          window.scrollTo(0, parseInt(scrollY));
        });
      }
      
      // Prevent touch scroll from propagating to body when menu is open
      let touchStartY = 0;
      let touchEndY = 0;
      
      menu.addEventListener('touchstart', function(e) {
        touchStartY = e.touches[0].clientY;
      }, { passive: true });
      
      menu.addEventListener('touchmove', function(e) {
        if (!menu.classList.contains('open')) return;
        
        const touch = e.touches[0];
        const scrollTop = menu.scrollTop;
        const scrollHeight = menu.scrollHeight;
        const clientHeight = menu.clientHeight;
        const isScrollingUp = touch.clientY > touchStartY;
        const isScrollingDown = touch.clientY < touchStartY;
        
        // Prevent scroll at boundaries
        if ((scrollTop === 0 && isScrollingUp) || 
            (scrollTop + clientHeight >= scrollHeight && isScrollingDown)) {
          e.preventDefault();
        }
      }, { passive: false });
      
      // Accordion functionality for submenus
      const menuItemsWithChildren = menu.querySelectorAll('.hs-item-has-children > a');
      
      menuItemsWithChildren.forEach(function(item) {
        item.addEventListener('click', function(e) {
          // Only prevent default on mobile
          if (window.innerWidth <= {{ theme.core.layout.mobile_breakpoint or 992 }}) {
            e.preventDefault();
            e.stopPropagation();
            
            const parentItem = this.parentElement;
            const wasOpen = parentItem.classList.contains('submenu-open');
            
            // Close all other open submenus
            menu.querySelectorAll('.hs-item-has-children.submenu-open').forEach(function(openItem) {
              if (openItem !== parentItem) {
                openItem.classList.remove('submenu-open');
              }
            });
            
            // Toggle current submenu
            parentItem.classList.toggle('submenu-open', !wasOpen);
            
            // Update ARIA
            this.setAttribute('aria-expanded', !wasOpen);
          }
        });
      });
      
      // Handle custom menu arrow toggles for mobile
      const submenuToggles = document.querySelectorAll('.submenu-toggle, .menu-arrow');
      submenuToggles.forEach(function(toggle) {
        toggle.addEventListener('click', function(e) {
          e.preventDefault();
          e.stopPropagation();
          
          const parentLi = this.closest('li.menu-item, li.hs-menu-item');
          const submenu = parentLi ? parentLi.querySelector(':scope > .submenu, :scope > .hs-menu-children-wrapper') : null;
          
          if (submenu) {
            const wasOpen = parentLi.classList.contains('submenu-open');
            
            // Close all other open submenus at this level
            const siblingItems = parentLi.parentElement.querySelectorAll(':scope > li.submenu-open');
            siblingItems.forEach(function(item) {
              if (item !== parentLi) {
                item.classList.remove('submenu-open');
                const siblingToggle = item.querySelector(':scope > .menu-item-content > .submenu-toggle, :scope > .submenu-toggle');
                if (siblingToggle) {
                  siblingToggle.setAttribute('aria-expanded', 'false');
                }
              }
            });
            
            // Toggle current submenu
            parentLi.classList.toggle('submenu-open', !wasOpen);
            
            // Update ARIA
            this.setAttribute('aria-expanded', !wasOpen);
          }
        });
      });
      
      // Fix desktop dropdown hover persistence
      if (window.innerWidth > {{ theme.core.layout.mobile_breakpoint or 992 }}) {
        // Add mouse enter/leave handlers for smooth hover transitions
        const desktopMenuItems = document.querySelectorAll('.main-menu li');
        
        desktopMenuItems.forEach(function(item) {
          let hoverTimeout;
          
          item.addEventListener('mouseenter', function() {
            clearTimeout(hoverTimeout);
            this.classList.add('hover');
          });
          
          item.addEventListener('mouseleave', function() {
            const self = this;
            // Add small delay to allow moving cursor to submenu
            hoverTimeout = setTimeout(function() {
              self.classList.remove('hover');
            }, 100);
          });
        });
      }
    }
  };

  // Use requestIdleCallback to reduce TBT
  if ('requestIdleCallback' in window) {
    requestIdleCallback(initMobileMenu, { timeout: 100 });
  } else if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initMobileMenu);
  } else {
    // DOM already loaded
    setTimeout(initMobileMenu, 0);
  }
})();
{% endif %}
</script>

<script>
(function(){
  var BP    = {{ theme.core.layout.mobile_breakpoint or 992 }};
  var MIN_W = 12 * (parseFloat(getComputedStyle(document.documentElement).fontSize) || 16); // 12rem, honors the theme base_size (14–20px)

  function initDesktopL3() {
    if (window.innerWidth <= BP) return;

    document.querySelectorAll('.submenu.level-2 > .menu-item.has-children').forEach(function(item) {
      var sub3 = item.querySelector(':scope > .submenu.level-3');
      if (!sub3) return;

      var hideTimer;

      function show() {
        clearTimeout(hideTimer);
        var rect = item.getBoundingClientRect();
        var vw   = document.documentElement.clientWidth;
        // Fly right unless the REAL panel width would overflow; then fly left.
        // (MIN_W=192 underestimated wide panels e.g. "Incentives Client View",
        // choosing right even when it didn't fit → clipped at edge. Batch 2c.)
        var w    = sub3.offsetWidth || MIN_W;
        var left = (rect.right + w <= vw - 8) ? rect.right : Math.max(8, rect.left - w);
        sub3.style.position = 'fixed';
        sub3.style.top      = rect.top + 'px';
        sub3.style.left     = left + 'px';
        sub3.style.right    = 'auto';
        sub3.classList.add('is-open');
      }

      function hide() {
        // Remove .is-open only — keep the inline fixed coords (they're recomputed
        // on every show(); clearing them repositions the panel mid fade-out, which
        // was a source of the right-side flash). Batch 2d.
        sub3.classList.remove('is-open');
      }

      // Show when entering the level-2 item
      item.addEventListener('mouseenter', show);

      // Hide when leaving the item — unless the cursor moved into sub3
      item.addEventListener('mouseleave', function(e) {
        if (sub3.contains(e.relatedTarget) || e.relatedTarget === sub3) return;
        hideTimer = setTimeout(hide, 80);
      });

      // Keep open while inside sub3
      sub3.addEventListener('mouseenter', function() { clearTimeout(hideTimer); });

      // Hide when leaving sub3 — unless cursor moved back to item
      sub3.addEventListener('mouseleave', function(e) {
        if (item.contains(e.relatedTarget) || e.relatedTarget === item) return;
        hideTimer = setTimeout(hide, 80);
      });
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initDesktopL3);
  } else {
    initDesktopL3();
  }
})();
</script>

{# Deferred Module CSS #}
{% require_css %}
<style>
  {% scope_css %}
    /* Module-specific styles */
    .site-header a { 
      color: {{ module.styles.colors.link_color.color }}; 
      text-decoration: none; 
    }
    .site-header a:hover { 
      color: {{ module.styles.colors.link_hover_color.color }}; 
    }
    
    {% if module.styles.appearance.box_shadow == 'small' %}
      .site-header { box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    {% elif module.styles.appearance.box_shadow == 'medium' %}
      .site-header { box-shadow: 0 2px 6px rgba(0,0,0,0.15); }
    {% elif module.styles.appearance.box_shadow == 'large' %}
      .site-header { box-shadow: 0 4px 12px rgba(0,0,0,0.2); }
    {% endif %}
    
    .site-header { 
      font-family: "{{ theme.core.typography.body_font.font }}", {{ theme.core.typography.body_font.fallback or 'sans-serif' }}; 
      font-size: {{ theme.core.typography.base_size or 16 }}px;
    }
  {% end_scope_css %}
</style>
{% end_require_css %}

{# Non-critical JavaScript - Only load if needed #}
{% set needs_js = module.features_group.show_search or content.translated_content.values()|selectattr("published")|length or (is_listing_view and group.translations) %}
{% if needs_js %}
<script defer>
(function() {
  // Defer non-critical features to reduce TBT
  const initFeatures = function() {
    {% if module.features_group.show_search %}
    // Search overlay
    const searchToggle = document.querySelector('.search-toggle');
    const searchOverlay = document.querySelector('.search-overlay');
    const searchClose = document.querySelector('.search-close');
    const searchBackdrop = document.querySelector('.search-overlay-backdrop');
    const searchInput = searchOverlay ? searchOverlay.querySelector('input[type="search"]') : null;

    function openSearch() {
      if (!searchOverlay) return;
      searchOverlay.classList.add('active');
      searchOverlay.setAttribute('aria-hidden', 'false');
      searchToggle.setAttribute('aria-expanded', 'true');
      document.body.style.overflow = 'hidden';
      if (searchInput) {
        setTimeout(() => searchInput.focus(), 100);
      }
    }

    function closeSearch() {
      if (!searchOverlay) return;
      searchOverlay.classList.remove('active');
      searchOverlay.setAttribute('aria-hidden', 'true');
      searchToggle.setAttribute('aria-expanded', 'false');
      document.body.style.overflow = '';
      if (searchInput) searchInput.value = '';
    }

    if (searchToggle && searchOverlay) {
      // Open search
      searchToggle.addEventListener('click', openSearch);

      // Close via close button
      if (searchClose) {
        searchClose.addEventListener('click', closeSearch);
      }

      // Close via backdrop click
      if (searchBackdrop) {
        searchBackdrop.addEventListener('click', closeSearch);
      }

      // Close via ESC key
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && searchOverlay.classList.contains('active')) {
          closeSearch();
        }
      });
    }
    {% endif %}
    
    // Language selector
    const langToggle = document.querySelector('.language-toggle');
    const langMenu = document.querySelector('.language-menu');
    if (langToggle && langMenu) {
      langToggle.addEventListener('click', (e) => {
        e.stopPropagation();
        const isOpen = langToggle.getAttribute('aria-expanded') === 'true';
        langToggle.setAttribute('aria-expanded', (!isOpen).toString());
        langMenu.setAttribute('aria-hidden', isOpen.toString());
      });
      document.addEventListener('click', () => {
        langToggle.setAttribute('aria-expanded', 'false');
        langMenu.setAttribute('aria-hidden', 'true');
      });
    }
  };

  // Use requestIdleCallback for non-critical features
  if ('requestIdleCallback' in window) {
    requestIdleCallback(initFeatures, { timeout: 200 });
  } else {
    // Fallback to immediate execution
    setTimeout(initFeatures, 50);
  }
})();
</script>
{% endif %}