<template>
  <div class="fl-collapse-item"
    :class="{'is-active': isActive, 'is-disabled': disabled }">
    <div
      role="tab"
      :aria-expanded="isActive"
      :aria-controls="`fl-collapse-content-${id}`"
      :aria-describedby ="`fl-collapse-content-${id}`"
    >
      <div
        class="fl-collapse-item__header"
        @click="handleHeaderClick"
        role="button"
        :id="`fl-collapse-head-${id}`"
        :tabindex="disabled ? undefined : 0"
        @keyup.space.enter.stop="handleEnterClick"
        :class="{
          'focusing': focusing,
          'is-active': isActive
        }"
        @focus="handleFocus"
        @blur="focusing = false"
      >
        <slot name="title">{{title}}</slot>
        <i
          class="fl-collapse-item__arrow fl-icon-arrow-right"
          :class="{'is-active': isActive}">
        </i>
      </div>
    </div>
    <fl-collapse-transition>
      <div
        class="fl-collapse-item__wrap"
        v-show="isActive"
        role="tabpanel"
        :aria-hidden="!isActive"
        :aria-labelledby="`fl-collapse-head-${id}`"
        :id="`fl-collapse-content-${id}`"
      >
        <div class="fl-collapse-item__content">
          <slot></slot>
        </div>
      </div>
    </fl-collapse-transition>
  </div>
</template>
<script>
  import FlCollapseTransition from 'flames-ui/src/transitions/collapse-transition';
  import Emitter from 'flames-ui/src/mixins/emitter';
  import { generateId } from 'flames-ui/src/utils/util';

  export default {
    name: 'FlCollapseItem',

    componentName: 'FlCollapseItem',

    mixins: [Emitter],

    components: { FlCollapseTransition },

    data() {
      return {
        contentWrapStyle: {
          height: 'auto',
          display: 'block'
        },
        contentHeight: 0,
        focusing: false,
        isClick: false,
        id: generateId()
      };
    },

    inject: ['collapse'],

    props: {
      title: String,
      name: {
        type: [String, Number],
        default() {
          return this._uid;
        }
      },
      disabled: Boolean
    },

    computed: {
      isActive() {
        return this.collapse.activeNames.indexOf(this.name) > -1;
      }
    },

    methods: {
      handleFocus() {
        setTimeout(() => {
          if (!this.isClick) {
            this.focusing = true;
          } else {
            this.isClick = false;
          }
        }, 50);
      },
      handleHeaderClick() {
        if (this.disabled) return;
        this.dispatch('FlCollapse', 'item-click', this);
        this.focusing = false;
        this.isClick = true;
      },
      handleEnterClick() {
        this.dispatch('FlCollapse', 'item-click', this);
      }
    }
  };
</script>
