import './view.scss';

import { FadeInSlideUpAnimator } from 'utils/animators/FadeInSlideUpAnimator.js';

Drupal.behaviors.view = {
  attach(context) {
    /**
     * Handles exposed form interactions for topic filtering
     */
    const exposedForm = () => {
      const EXPOSED_FORM = context.querySelector('.form--views-exposed-form');
      if (!EXPOSED_FORM) return;

      const NODE_TOPIC_BUTTONS = context.querySelectorAll('button[data-topic-id]');
      if (!NODE_TOPIC_BUTTONS.length) return;

      const SUBMIT_BUTTON = EXPOSED_FORM.querySelector('input[type="submit"], button[type="submit"]');
      if (!SUBMIT_BUTTON) return;

      NODE_TOPIC_BUTTONS.forEach(topicButton => {
        topicButton.addEventListener('click', () => {
          const TOPIC_ID = topicButton.getAttribute('data-topic-id');
          if (!TOPIC_ID) return;

          const CHECKBOX = EXPOSED_FORM.querySelector(`input[name="topics[${TOPIC_ID}]"]`);
          if (!CHECKBOX) return;

          // Only submit if checkbox is not already checked
          if (!CHECKBOX.checked) {
            CHECKBOX.checked = true;
            SUBMIT_BUTTON.click();
          }
        });
      });
    }

    /**
     * Handles responsive behavior for collapsible filters.
     */
    const collapseFilters = () => {
      const COLLAPSED_FILTERS_MQ = window.matchMedia('(min-width: 768px)');
      const VIEW_DETAIL = context.querySelector('.view details');
      if (!VIEW_DETAIL) return;

      const handleChange = (event) => {
        VIEW_DETAIL.toggleAttribute('open', event.matches);
      }

      COLLAPSED_FILTERS_MQ.addEventListener('change', handleChange, { passive: true });

      handleChange(COLLAPSED_FILTERS_MQ);
    }

    /**
     * Initializes scroll-based animations for view rows and grid items.
     */
    const animate = () => {
      const VIEW_CONTENTS = context.querySelectorAll('.view__content');
      if (!VIEW_CONTENTS.length) return;

      VIEW_CONTENTS.forEach(viewContent => {
        const VIEW_ROWS = viewContent.querySelectorAll(`
          .view__rows > .view__row,
          .view__grid > .view__grid-item
        `);
        if (!VIEW_ROWS.length) return;

        new FadeInSlideUpAnimator(VIEW_ROWS);
      });
    }

    /**
     * **************************************************
     * Initialize
     */

    exposedForm();
    collapseFilters();
    animate();
  }
}
