import constants from "./constants";
export const AccordionsBlock = (bm, category, label, type) => {
  const { accordionsBlock, style } = constants;
  const content = `<div data-gjs-type="${type}"></div>
    ${style ? `<style>${style}</style>` : ""}`;

  accordionsBlock &&
    bm.add(type, {
      label,
      category: category,
      content,
      render: ({ model, className }) => `
      <div class="drapcode-compo-seventeen ${className}-label ${className}__drapcode-wrap">
      <div class="drap-on-six"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" width="32" height="50" style="-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);" preserveAspectRatio="xMidYMid meet" viewBox="0 0 1536 1536"><g transform="translate(0 1536) scale(1 -1)"><path d="M1145 989q-17 35-57 35H448q-40 0-57-35q-18-35 5-66l320-448q19-27 52-27t52 27l320 448q23 31 5 66zm135 259V288q0-13-9.5-22.5T1248 256H288q-13 0-22.5 9.5T256 288v960q0 13 9.5 22.5t22.5 9.5h960q13 0 22.5-9.5t9.5-22.5zm256-960v960q0 119-84.5 203.5T1248 1536H288q-119 0-203.5-84.5T0 1248V288Q0 169 84.5 84.5T288 0h960q119 0 203.5 84.5T1536 288z" fill="#c3cfe9"/></g></svg></div>
      <div class="drapcode-compo-qustion ${className}__info">
        <a
          target="_blank"
          href="https://academy.drapcode.com/docs/app-builder/layout-component-sections"
          draggable="false"
        >
          <i class="bem-Svg ${className}__info-fa fa fa-info-circle" title="Check how to use ${label}?"></i>
        </a>
      </div>
      <div class="drapcode-com-one">${model.get("label")}</div>
    </div>
      `,
      ...accordionsBlock,
    });
};

export default (dc, label, type) => {
  const defaultType = dc.getType("default");
  const defaultModel = defaultType.model;
  const defaultView = defaultType.view;

  const {
    attrAccordions,
    attrAccordion,
    attrAccordionContent,
    attrAccordionContainer,
    classAccordionActive,
    selectorAccordion,
    accordionsProps,
    template,
  } = constants;

  dc.addType(type, {
    model: defaultModel.extend(
      {
        defaults: {
          ...defaultModel.prototype.defaults,
          copyable: false,
          droppable: false,
          name: label,

          "attr-accordions": attrAccordions,
          "attr-accordion": attrAccordion,
          "attr-accordion-content": attrAccordionContent,
          "attr-accordion-container": attrAccordionContainer,
          "class-accordion-active": classAccordionActive,
          "selector-accordion": selectorAccordion,

          script() {
            var i;
            var el = this;
            var attrAccordions = "[" + "{[ attr-accordions ]}" + "]";
            var attrAccordion = "[" + "{[ attr-accordion ]}" + "]";
            var attrAccordionContent =
              "[" + "{[ attr-accordion-content ]}" + "]";
            var attrAccordionContainer =
              "[" + "{[ attr-accordion-container ]}" + "]";
            var classAccordionActive = "{[ class-accordion-active ]}";
            var selectorAccordion = "{[ selector-accordion ]}";
            var body = document.body;
            var matches =
              body.matchesSelector ||
              body.webkitMatchesSelector ||
              body.mozMatchesSelector ||
              body.msMatchesSelector;

            var hideContents = function () {
              var accordionContents =
                el.querySelectorAll(attrAccordionContent) || [];
              for (i = 0; i < accordionContents.length; i++) {
                accordionContents[i].style.display = "none";
              }
            };

            var activeAccordion = function (accordionEl) {
              var accordionContainers =
                el.querySelectorAll(attrAccordionContainer) || [];

              for (i = 0; i < accordionContainers.length; i++) {
                var accordionContainer = accordionContainers[i];
                var newClass = accordionContainer.className
                  .replace(classAccordionActive, "")
                  .trim();

                accordionContainer.className = newClass;
              }

              hideContents();

              accordionEl.className += " " + classAccordionActive;
            };

            var deactiveAccordion = function (accordionEl) {
              var newClass = accordionEl.className
                .replace(classAccordionActive, "")
                .trim();
              accordionEl.className = newClass;
            };

            el.addEventListener("click", function (e) {
              let target = e.target;

              // Handling Link based Component
              const compatibleElements = ["A"];
              if (!compatibleElements.includes(target.tagName.toUpperCase())) {
                target = target.closest("A");
              }

              if (
                el.querySelector(target.getAttribute(selectorAccordion)).style
                  .display === "block"
              ) {
                deactiveAccordion(target.parentElement);
                el.querySelector(
                  target.getAttribute(selectorAccordion)
                ).style.display = "none";
              } else {
                activeAccordion(target.parentElement);
                el.querySelector(
                  target.getAttribute(selectorAccordion)
                ).style.display = "block";
              }
            });
          },
          ...accordionsProps,
        },

        init() {
          const attrs = this.getAttributes();
          attrs[attrAccordions] = 1;
          this.setAttributes(attrs);
        },
      },
      {
        isComponent(el) {
          if (el.hasAttribute && el.hasAttribute(attrAccordions)) {
            return { type };
          }
        },
      }
    ),

    view: defaultView.extend({
      init() {
        const comps = this.model.components();
        !comps.length && comps.add(template);
      },

      onRender() {},
    }),
  });
};
