<template>
  <table class="datatable">
    <thead class="datatable__head">
      <tr class="datatable__row datatable__row--head">
        <th
          class="datatable__heading"
          v-for="(header, idx) in dataset.headers"
          :key="idx"
        >
          {{ header }}
        </th>
      </tr>
    </thead>
    <tbody class="datatable__body">
      <tr class="datatable__row" v-for="(row, idx) in dataset.data" :key="idx">
        <td
          class="datatable__cell"
          v-for="(cell, idx) in row"
          :key="idx"
          :colspan="idx === 1 && !isHexValue(row[1]) ? 2 : 1"
        >
          <template v-if="Array.isArray(cell)">
            <ul
              :class="[
                cell.length > 11 ? 'col-3' : cell.length > 4 ? 'col-2' : '',
              ]"
            >
              <li v-for="(item, idx) in cell" :key="idx">
                {{ item }}
              </li>
            </ul>
          </template>

          <template v-else>
            {{ cell }}
          </template>
        </td>
        <td
          v-if="isHexValue(row[1])"
          class="datatable__cell--colorpick"
          :style="`background-color: ${row[1]}`"
        ></td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  name: "DataTable",
  props: {
    dataset: {
      type: Object,
      required: true,
    },
  },
  methods: {
    isHexValue(value) {
      return /^#[0-9a-f]{6}$/i.test(value) ? value : false;
    },
  },
};
</script>

<style lang="scss">
@import "@/scss/_variables.scss";
@import "@/scss/_mixins.scss";

.datatable {
  border-collapse: collapse;
  width: 100%;
  margin: auto;

  @include mq-desktop {
    max-width: 45rem;
  }

  @include mq-bigscreen {
    max-width: 55rem;
  }

  &__heading,
  &__cell {
    padding: 0.25em 0.5em;

    @media (min-width: 35em) {
      padding: 0.5em 1em;
    }

    ul {
      margin: 0;
      padding: 0;

      @media (min-width: 40em) {
        &.col-2 {
          columns: 2 auto;
        }

        &.col-3 {
          columns: 3 auto;
        }
      }
    }

    li {
      margin: 0 0 0 1em;
      padding: 0;
    }
  }

  &__body {
    .datatable__row {
      background-color: rgba($bg-color-dark, 0.7);

      &:nth-child(odd) {
        background-color: rgba(lighten($bg-color-dark, 15%), 0.7);
      }
    }
  }

  &__row {
    &--head {
      background-color: $bg-color-light;
      color: $copy-color;
    }
  }

  &__cell {
    &:first-child {
      text-align: right;
    }

    &--colorpick {
      margin-top: 0.1em;
      border: 0.1em solid #fff;
    }
  }
}
</style>
