{# Tabs Module - Desktop Tabs / Mobile Accordion #}

{% set tabs_id = "tabs-" ~ name %}
{% set mobile_behavior = module.behavior_settings.mobile_behavior|default('accordion') %}
{% set desktop_layout = module.layout_settings.desktop_layout|default('horizontal-top') %}
{% set tab_style = module.style.tab_style|default('pills') %}
{% set tab_alignment = module.layout_settings.tab_alignment|default('start') %}
{% set default_tab = 0 %}

{# Find default tab #}
{% for tab in module.tabs %}
  {% if tab.is_open_by_default %}
    {% set default_tab = loop.index0 %}
  {% endif %}
{% endfor %}

{# Module Styles - Using CSS Variables from settings #}
<style>
  .{{ tabs_id }} {
    --tab-bg: {{ module.style.tab_background.color|default('var(--color-bg-secondary, #f8f9fa)', true) }};
    --tab-color: {{ module.style.tab_text_color.color|default('var(--color-text, #495057)', true) }};
    --active-bg: {{ module.style.active_tab_background.color|default('var(--color-primary, #007bff)', true) }};
    --active-color: {{ module.style.active_tab_text_color.color|default('var(--color-primary-contrast, #ffffff)', true) }};
    --content-bg: {{ module.style.content_background.color|default('var(--color-bg, #ffffff)', true) }};
    --content-padding: {{ module.style.content_padding|default(30) }}px;
    --radius: {{ module.style.border_radius|default(8) }}px;
    --min-height: {{ module.layout_settings.content_min_height|default(200) }}px;
    --animation-duration: {{ module.behavior_settings.animation_duration|default(300) }}ms;
    position: relative;
    width: 100%;
  }

  /* ========================================
     DESKTOP TABS (above the mobile breakpoint)
     ======================================== */
  @media (min-width: {{ (theme.core.layout.mobile_breakpoint or 992) + 1 }}px) {
    /* Hide accordion on desktop */
    .{{ tabs_id }} .tabs-accordion {
      display: none !important;
    }

    /* Show desktop tab container */
    .{{ tabs_id }} .tabs-desktop-container {
      display: {% if 'vertical' in desktop_layout %}flex{% else %}block{% endif %};
      {% if 'vertical' in desktop_layout %}
        gap: 2rem;
        {% if 'right' in desktop_layout %}flex-direction: row-reverse;{% endif %}
      {% endif %}
    }

    /* Tab Navigation */
    .{{ tabs_id }} .tabs-nav {
      display: flex;
      {% if 'vertical' in desktop_layout %}
        flex-direction: column;
        width: 220px;
        flex-shrink: 0;
      {% else %}
        flex-direction: row;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-bottom: 1rem;
        {% if tab_alignment == 'center' %}justify-content: center;{% endif %}
        {% if tab_alignment == 'end' %}justify-content: flex-end;{% endif %}
        {% if tab_alignment == 'stretch' %}gap: 0;{% endif %}
      {% endif %}
      {% if 'bottom' in desktop_layout %}
        order: 2;
        margin-bottom: 0;
        margin-top: 1rem;
      {% endif %}
    }

    /* Tab Buttons - Base Styles */
    .{{ tabs_id }} .tab-button {
      display: inline-flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.75rem 1.5rem;
      background: var(--tab-bg);
      color: var(--tab-color);
      border: none;
      font-size: 1rem;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;
      white-space: nowrap;
      {% if tab_alignment == 'stretch' %}flex: 1; justify-content: center;{% endif %}
      {% if 'vertical' in desktop_layout %}
        width: 100%;
        text-align: left;
        justify-content: flex-start;
      {% endif %}
    }

    .{{ tabs_id }} .tab-button:hover {
      filter: brightness(0.95);
    }

    .{{ tabs_id }} .tab-button.active {
      background: var(--active-bg);
      color: var(--active-color);
    }

    /* Tab Style: Pills */
    {% if tab_style == 'pills' %}
      .{{ tabs_id }} .tab-button {
        border-radius: 50px;
      }
    {% endif %}

    /* Tab Style: Underline */
    {% if tab_style == 'underline' %}
      .{{ tabs_id }} .tabs-nav {
        border-bottom: 2px solid rgba(127, 131, 139, 0.25);
        gap: 0;
        padding-bottom: 0;
      }
      .{{ tabs_id }} .tab-button {
        background: transparent;
        border-radius: 0;
        position: relative;
        padding-bottom: 1rem;
        margin-bottom: -2px;
      }
      .{{ tabs_id }} .tab-button::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: var(--active-bg);
        transform: scaleX(0);
        transition: transform 0.2s ease;
      }
      .{{ tabs_id }} .tab-button.active {
        background: transparent;
        color: var(--active-bg);
      }
      .{{ tabs_id }} .tab-button.active::after {
        transform: scaleX(1);
      }
    {% endif %}

    /* Tab Style: Boxed */
    {% if tab_style == 'boxed' %}
      .{{ tabs_id }} .tabs-nav {
        background: var(--tab-bg);
        padding: 4px;
        border-radius: var(--radius);
        gap: 4px;
      }
      .{{ tabs_id }} .tab-button {
        border-radius: calc(var(--radius) - 2px);
        background: transparent;
      }
      .{{ tabs_id }} .tab-button.active {
        background: var(--content-bg);
        color: var(--tab-color);
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
      }
    {% endif %}

    /* Tab Style: Minimal */
    {% if tab_style == 'minimal' %}
      .{{ tabs_id }} .tab-button {
        background: transparent;
        padding: 0.5rem 1rem;
      }
      .{{ tabs_id }} .tab-button:hover {
        color: var(--active-bg);
      }
      .{{ tabs_id }} .tab-button.active {
        background: transparent;
        color: var(--active-bg);
        font-weight: 600;
      }
    {% endif %}

    /* Tab Content Container */
    .{{ tabs_id }} .tabs-content-container {
      display: block;
      background: var(--content-bg);
      border-radius: var(--radius);
      min-height: var(--min-height);
      position: relative;
      {% if 'vertical' in desktop_layout %}flex: 1;{% endif %}
      {% if tab_style != 'underline' and tab_style != 'minimal' %}
        border: 1px solid rgba(127, 131, 139, 0.25);
      {% endif %}
    }

    /* Tab Panels */
    .{{ tabs_id }} .tab-panel {
      display: none;
      padding: var(--content-padding);
    }

    .{{ tabs_id }} .tab-panel.active {
      display: block;
      animation: tabFadeIn var(--animation-duration) ease;
    }

    @keyframes tabFadeIn {
      from { opacity: 0; transform: translateY(5px); }
      to { opacity: 1; transform: translateY(0); }
    }
  }

  /* ========================================
     MOBILE ACCORDION (at/below the mobile breakpoint)
     ======================================== */
  @media (max-width: {{ theme.core.layout.mobile_breakpoint or 992 }}px) {
    /* Hide desktop tabs on mobile */
    .{{ tabs_id }} .tabs-desktop-container {
      display: none !important;
    }

    /* Show accordion */
    .{{ tabs_id }} .tabs-accordion {
      display: block;
      border: 1px solid rgba(127, 131, 139, 0.25);
      border-radius: var(--radius);
      overflow: hidden;
    }

    .{{ tabs_id }} .tab-accordion-item {
      border-bottom: 1px solid rgba(127, 131, 139, 0.25);
    }

    .{{ tabs_id }} .tab-accordion-item:last-child {
      border-bottom: none;
    }

    .{{ tabs_id }} .tab-accordion-button {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 1rem;
      background: var(--tab-bg);
      color: var(--tab-color);
      border: none;
      font-size: 1rem;
      font-weight: 500;
      text-align: left;
      cursor: pointer;
      transition: background 0.2s ease;
    }

    .{{ tabs_id }} .tab-accordion-button:hover {
      filter: brightness(0.95);
    }

    .{{ tabs_id }} .tab-accordion-button.active {
      background: var(--active-bg);
      color: var(--active-color);
    }

    .{{ tabs_id }} .tab-accordion-icon {
      margin-right: 0.5rem;
    }

    .{{ tabs_id }} .tab-accordion-arrow {
      margin-left: auto;
      font-size: 0.75rem;
      transition: transform 0.2s ease;
    }

    .{{ tabs_id }} .tab-accordion-button.active .tab-accordion-arrow {
      transform: rotate(180deg);
    }

    .{{ tabs_id }} .tab-accordion-content {
      max-height: 0;
      overflow: hidden;
      background: var(--content-bg);
      transition: max-height 0.3s ease;
    }

    .{{ tabs_id }} .tab-accordion-content.active {
      max-height: 2000px;
    }

    .{{ tabs_id }} .tab-accordion-content-inner {
      padding: var(--content-padding);
    }
  }

  /* Tab Icon */
  .{{ tabs_id }} .tab-icon {
    font-size: 1.125rem;
  }

  /* Focus styles for accessibility */
  .{{ tabs_id }} .tab-button:focus-visible,
  .{{ tabs_id }} .tab-accordion-button:focus-visible {
    outline: 2px solid var(--active-bg);
    outline-offset: 2px;
  }

  /* Reduced motion */
  @media (prefers-reduced-motion: reduce) {
    .{{ tabs_id }} .tab-panel,
    .{{ tabs_id }} .tab-accordion-content,
    .{{ tabs_id }} .tab-accordion-arrow {
      transition: none !important;
      animation: none !important;
    }
  }
</style>

<div class="tabs-module {{ tabs_id }}"
     role="region"
     aria-label="Content tabs"
     data-tabs-id="{{ tabs_id }}"
     data-default-tab="{{ default_tab }}"
     data-deep-linking="{{ module.behavior_settings.enable_deep_linking|default(true) }}"
     data-remember="{{ module.behavior_settings.remember_last_tab|default(false) }}"
     data-auto-rotate="{{ module.behavior_settings.auto_rotate|default(false) }}"
     data-rotation-interval="{{ module.behavior_settings.rotation_interval|default(5000) }}"
     data-pause-on-hover="{{ module.behavior_settings.pause_on_hover|default(true) }}">

  {# ========================================
     MOBILE ACCORDION
     ======================================== #}
  <div class="tabs-accordion" role="presentation">
    {% for tab in module.tabs %}
      <div class="tab-accordion-item">
        <button class="tab-accordion-button {% if loop.index0 == default_tab %}active{% endif %}"
                role="tab"
                aria-expanded="{% if loop.index0 == default_tab %}true{% else %}false{% endif %}"
                aria-controls="accordion-panel-{{ tabs_id }}-{{ loop.index0 }}"
                data-tab-index="{{ loop.index0 }}">
          {% if tab.icon_type and tab.icon_type != 'none' %}
            <span class="tab-accordion-icon" aria-hidden="true">
              {% if tab.icon_type == 'home' %}🏠
              {% elif tab.icon_type == 'star' %}⭐
              {% elif tab.icon_type == 'heart' %}❤️
              {% elif tab.icon_type == 'check' %}✅
              {% elif tab.icon_type == 'info' %}ℹ️
              {% elif tab.icon_type == 'gear' %}⚙️
              {% elif tab.icon_type == 'chart' %}📊
              {% elif tab.icon_type == 'lock' %}🔒
              {% elif tab.icon_type == 'mail' %}✉️
              {% elif tab.icon_type == 'phone' %}📱
              {% endif %}
            </span>
          {% endif %}
          <span>{{ tab.tab_label }}</span>
          <span class="tab-accordion-arrow" aria-hidden="true">▼</span>
        </button>
        <div class="tab-accordion-content {% if loop.index0 == default_tab %}active{% endif %}"
             id="accordion-panel-{{ tabs_id }}-{{ loop.index0 }}"
             role="tabpanel">
          <div class="tab-accordion-content-inner">
            {{ tab.content }}
          </div>
        </div>
      </div>
    {% endfor %}
  </div>

  {# ========================================
     DESKTOP TABS
     ======================================== #}
  <div class="tabs-desktop-container">
    {# Tab Navigation #}
    <nav class="tabs-nav" role="tablist" aria-label="Tab navigation">
      {% for tab in module.tabs %}
        <button class="tab-button {% if loop.index0 == default_tab %}active{% endif %}"
                role="tab"
                aria-selected="{% if loop.index0 == default_tab %}true{% else %}false{% endif %}"
                aria-controls="panel-{{ tabs_id }}-{{ loop.index0 }}"
                id="tab-{{ tabs_id }}-{{ loop.index0 }}"
                data-tab-index="{{ loop.index0 }}"
                tabindex="{% if loop.index0 == default_tab %}0{% else %}-1{% endif %}">
          {% if tab.icon_type and tab.icon_type != 'none' %}
            <span class="tab-icon" aria-hidden="true">
              {% if tab.icon_type == 'home' %}🏠
              {% elif tab.icon_type == 'star' %}⭐
              {% elif tab.icon_type == 'heart' %}❤️
              {% elif tab.icon_type == 'check' %}✅
              {% elif tab.icon_type == 'info' %}ℹ️
              {% elif tab.icon_type == 'gear' %}⚙️
              {% elif tab.icon_type == 'chart' %}📊
              {% elif tab.icon_type == 'lock' %}🔒
              {% elif tab.icon_type == 'mail' %}✉️
              {% elif tab.icon_type == 'phone' %}📱
              {% endif %}
            </span>
          {% endif %}
          {{ tab.tab_label }}
        </button>
      {% endfor %}
    </nav>

    {# Tab Content Panels #}
    <div class="tabs-content-container">
      {% for tab in module.tabs %}
        <div class="tab-panel {% if loop.index0 == default_tab %}active{% endif %}"
             id="panel-{{ tabs_id }}-{{ loop.index0 }}"
             role="tabpanel"
             aria-labelledby="tab-{{ tabs_id }}-{{ loop.index0 }}"
             tabindex="0">
          {{ tab.content }}
        </div>
      {% endfor %}
    </div>
  </div>
</div>

{# JavaScript for Tab Switching — deferred to footer so it isn't parser-blocking. #}
{% require_js position="footer" %}
<script>
(function() {
  const container = document.querySelector('.{{ tabs_id }}');
  if (!container) return;

  const isDeepLinking = container.dataset.deepLinking === 'true';
  const rememberTab = container.dataset.remember === 'true';
  const autoRotate = container.dataset.autoRotate === 'true';
  const rotationInterval = parseInt(container.dataset.rotationInterval) || 5000;
  const pauseOnHover = container.dataset.pauseOnHover === 'true';
  const defaultTab = parseInt(container.dataset.defaultTab) || 0;

  let currentTab = defaultTab;
  let rotationTimer = null;

  // Get all tab elements
  const accordionButtons = container.querySelectorAll('.tab-accordion-button');
  const accordionPanels = container.querySelectorAll('.tab-accordion-content');
  const tabButtons = container.querySelectorAll('.tab-button');
  const tabPanels = container.querySelectorAll('.tab-panel');

  // Get tab labels for deep linking
  const tabLabels = [{% for tab in module.tabs %}'{{ tab.tab_label|replace("'", "\\'") }}'{% if not loop.last %}, {% endif %}{% endfor %}];

  // Function to switch tab
  function switchTab(index, updateHash = true) {
    if (index < 0 || index >= tabButtons.length) return;

    currentTab = index;

    // Update accordion (mobile)
    accordionButtons.forEach((btn, i) => {
      const panel = accordionPanels[i];
      const isActive = i === index;

      btn.classList.toggle('active', isActive);
      btn.setAttribute('aria-expanded', isActive);
      panel.classList.toggle('active', isActive);
    });

    // Update tabs (desktop)
    tabButtons.forEach((btn, i) => {
      const panel = tabPanels[i];
      const isActive = i === index;

      btn.classList.toggle('active', isActive);
      btn.setAttribute('aria-selected', isActive);
      btn.setAttribute('tabindex', isActive ? '0' : '-1');
      panel.classList.toggle('active', isActive);
    });

    // Save to session storage if remember is enabled
    if (rememberTab) {
      sessionStorage.setItem('{{ tabs_id }}-active', index);
    }
  }

  // Accordion button clicks (mobile)
  accordionButtons.forEach((btn, index) => {
    btn.addEventListener('click', () => {
      switchTab(index);
      stopRotation();
    });
  });

  // Tab button clicks (desktop)
  tabButtons.forEach((btn, index) => {
    btn.addEventListener('click', () => {
      switchTab(index);
      stopRotation();
    });
  });

  // Keyboard navigation
  container.addEventListener('keydown', (e) => {
    if (!e.target.classList.contains('tab-button')) return;

    let newIndex = currentTab;

    if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
      newIndex = currentTab > 0 ? currentTab - 1 : tabButtons.length - 1;
    } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
      newIndex = currentTab < tabButtons.length - 1 ? currentTab + 1 : 0;
    } else if (e.key === 'Home') {
      newIndex = 0;
    } else if (e.key === 'End') {
      newIndex = tabButtons.length - 1;
    }

    if (newIndex !== currentTab) {
      e.preventDefault();
      switchTab(newIndex);
      tabButtons[newIndex].focus();
      stopRotation();
    }
  });

  // Auto-rotation — only runs when module is in the viewport
  let isVisible = false;

  function startRotation() {
    if (!autoRotate || rotationTimer || !isVisible) return;
    rotationTimer = setInterval(() => {
      const nextIndex = currentTab < tabButtons.length - 1 ? currentTab + 1 : 0;
      switchTab(nextIndex);
    }, rotationInterval);
  }

  function stopRotation() {
    if (rotationTimer) {
      clearInterval(rotationTimer);
      rotationTimer = null;
    }
  }

  if (autoRotate) {
    const visibilityObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        isVisible = entry.isIntersecting;
        if (isVisible) {
          startRotation();
        } else {
          stopRotation();
        }
      });
    }, { threshold: 0.1 });

    visibilityObserver.observe(container);

    if (pauseOnHover) {
      container.addEventListener('mouseenter', stopRotation);
      container.addEventListener('mouseleave', () => {
        if (isVisible) startRotation();
      });
    }
  }

  // Deep linking support
  if (isDeepLinking && window.location.hash) {
    const hash = window.location.hash.substring(1);
    const index = tabLabels.findIndex(label =>
      label.toLowerCase().replace(/\s+/g, '-') === hash
    );

    if (index !== -1) {
      switchTab(index, false);
    }
  }

  // Remember last tab
  if (rememberTab) {
    const savedTab = sessionStorage.getItem('{{ tabs_id }}-active');
    if (savedTab !== null) {
      switchTab(parseInt(savedTab), false);
    }
  }
})();
</script>
{% end_require_js %}
