<template>
  <div>
    <Accordion name="cookie-categories" type="boxed" class="wcc-app-box">
      <AccordionItem
        v-for="(category, categoryId) in scanHistoryArray"
        :key="categoryId"
      >
        <template slot="accordion-trigger">
          <label class="wcc-app-accordion-title">
            {{ category.category }}
          </label>
        </template>
        <template slot="accordion-content">
          <!-- Content for each accordion item here -->
          <table class="wcc-custom-table">
            <thead>
              <tr>
                <th>{{ $i18n.__("ID", "webtoffee-cookie-consent") }}</th>
                <th>
                  {{
                    $i18n.__("First Found URL", "webtoffee-cookie-consent")
                  }}
                </th>
                <th>
                  {{ $i18n.__("Duration", "webtoffee-cookie-consent") }}
                </th>
                <th>
                  {{ $i18n.__("Description", "webtoffee-cookie-consent") }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="(cookie, cookieName) in category.cookies"
                :key="cookieName"
              >
                <td>{{ cookie.cookie_id }}</td>
                <td>{{ removeWccBypassParam(cookie.frist_found_url) }}</td>
                <td>{{ cookie.duration }}</td>
                <td>{{ cookie.description }}</td>
              </tr>
            </tbody>
          </table>
        </template>
      </AccordionItem>
    </Accordion>
    <div class="wcc-scanned-urls">
      <h6 style="padding-left: 15px">
        {{ $i18n.__("Pages scanned", "webtoffee-cookie-consent") }}
      </h6>
      <table class="wcc-custom-table">
        <thead>
          <tr>
            <th>{{ $i18n.__("URL", "webtoffee-cookie-consent") }}</th>
            <th>{{ $i18n.__("Cookies", "webtoffee-cookie-consent") }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="page in aggregatedPages" :key="page.Url">
            <td>{{ page.Url }}</td>
            <td>{{ page.cookieCount }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
import Accordion from "@/components/accordion/Accordion.vue";
import AccordionItem from "@/components/accordion/AccordionItem.vue";

export default {
  name: "ScanDetails",
  components: {
    Accordion,
    AccordionItem,
  },
  props: {
    responseData: Object, // Define the prop to receive responseData
  },
  data() {
    return {
      cookie: {},
      category: {},
      categoryCookies: [],
      cookies: [],
      currentTab: "layout",
      cookieCategories: [],
      loading: false,
      currentLanguage: "",
      errors: {
        cookie: {
          id: false,
          domain: false,
          duration: false,
          description: false,
        },
        category: {
          name: false,
          description: false,
        },
      },
      // Parse and store your JSON data
      categories: {}, // Initialize as an empty object
    };
  },
  methods: {
    removeWccBypassParam(url) {
      // Remove wcc_bypass=1 from the URL if it exists
      return url.replace(/(\?|&)wcc_bypass=1/, '');
    },
  },
  computed: {
    cookieGroups() {
      return this.$store.state.cookies.items;
    },
    selectedLanguages() {
      const selected = this.$store.state.languages.selected;
      const available = this.$store.state.languages.available;

      const filtered = available.filter(function (item) {
        return selected.indexOf(item.code) > -1;
      });
      return filtered;
    },
    language: {
      get() {
        return (
          (this.currentLanguage && this.currentLanguage) ||
          this.$store.state.languages.default
        );
      },
      set(value) {
        this.currentLanguage = value;
      },
    },
    scanHistoryArray() {
      // Check if responseData.scan_history is a JSON object
      if (typeof this.responseData.scan_history === "string") {
        // Handle empty string case
        if (this.responseData.scan_history.trim() === "") {
          return [];
        }
        try {
          // Try to parse the JSON string to an array
          return JSON.parse(this.responseData.scan_history);
        } catch (error) {
          // Handle JSON parsing error if necessary
          console.error("Error parsing scan_history JSON:", error);
          return [];
        }
      } else if (Array.isArray(this.responseData.scan_history)) {
        // If it's already an array, return it as is
        return this.responseData.scan_history;
      } else {
        // If it's neither a JSON string nor an array, return an empty array
        return [];
      }
    },
    scannedUrlArray() {
      // Check if responseData.urls_scanned is a JSON object
      if (typeof this.responseData.urls_scanned === "string") {
        try {
          // Try to parse the JSON string to an array
          return JSON.parse(this.responseData.urls_scanned);
        } catch (error) {
          // Handle JSON parsing error if necessary
          console.error("Error parsing urls_scanned JSON:", error);
          return [];
        }
      } else if (Array.isArray(this.responseData.urls_scanned)) {
        // If it's already an array, return it as is
        return this.responseData.urls_scanned;
      } else {
        // If it's neither a JSON string nor an array, return an empty array
        return [];
      }
    },
    aggregatedPages() {
      const aggregated = {};
      for (const categoryId in this.scanHistoryArray) {
        if (
          Object.prototype.hasOwnProperty.call(
            this.scanHistoryArray,
            categoryId
          )
        ) {
          const category = this.scanHistoryArray[categoryId];
          for (const cookieName in category.cookies) {
            if (
              Object.prototype.hasOwnProperty.call(category.cookies, cookieName)
            ) {
              const cookie = category.cookies[cookieName];
              const url = this.removeWccBypassParam(cookie.frist_found_url);
              if (this.scannedUrlArray.includes(url)) {
                if (aggregated[url]) {
                  aggregated[url].cookieCount += 1;
                } else {
                  aggregated[url] = {
                    Url: url,
                    cookieCount: 1,
                  };
                }
              }
            }
          }
        }
      }
      const aggregatedPages = Object.values(aggregated);
      return aggregatedPages;
    },
  },
};
</script>
<style lang="scss" scoped>
.wcc-cookie-list-title {
  margin-bottom: 20px;
  .wcc-add-cookie-button {
    margin-left: 10px;
  }
}
.wcc-nav-tab-section-cookies {
  background: transparent;
}

.wcc-app-modal-cookies {
  .wcc-admin-notice-message p {
    font-size: 12px;
  }
}
.wcc-cookies-title {
  display: flex;
  align-items: center;
  padding: 10px 0;
}
.wcc-cookies-title .wcc-button-no-style {
  margin-left: 11px;
}
.wcc-nav-tab-section-header {
  border: none;
}
.wcc-nav-tab-section-cookies {
  padding: 15px 15px;
  .wcc-nav-tab-section-header {
    h5 {
      font-weight: $font--medium;
      // border-bottom: 1px solid;
      padding-bottom: 2px;
      margin: 0;
    }
  }
}
</style>
<style lang="scss">
@include wrap-class() {
  .wcc-table {
    &.wcc-table-cookies {
      margin-top: 15px;
      border: none;
      tbody tr {
        border-top: none;
        td {
          font-size: 13px;
        }
      }
      tbody td,
      th {
        padding: 15px 10px;
      }
    }
  }
  .wcc-cookie-list-title {
    select {
      margin-left: 10px;
      min-width: 150px; // auto
      height: auto;
      width: auto;
    }
  }
  .wcc-nav-tab-manage-cookies {
    &
      > .wcc-nav-tab-content-container
      > .wcc-nav-tab-section
      > .wcc-nav-tab-section-header {
      padding: 15px 0 15px 0;
    }
    .wcc-nav-tab-button {
      padding: 15px 10px;
    }
  }
  .wcc-app-accordion-title {
    position: relative; // Add relative positioning to the title
    background-color: #fafbfc;
    color: #2a3646;
    border-radius: 0px;
    margin-bottom: 0px;
  }

  .wcc-app-accordion.wcc-app-accordion-boxed .wcc-app-accordion-title::before {
    content: none;
  }

  .wcc-app-accordion.wcc-app-accordion-boxed .wcc-app-accordion-title::after {
    content: "";
    position: absolute; // Add absolute positioning to the ::after pseudo-element
    top: 50%; // Position it vertically in the middle
    right: 20px; // Position it at the end (right)
    transform: translateY(-50%); // Center it vertically
    // Add additional styling for the ::after pseudo-element as needed
  }
}

.wcc-app-rtl {
  input,
  .wcc-cookies-title,
  .wcc-category-description,
  .wcc-rich-text-editor * {
    direction: rtl;
    text-align: right;
  }
}

.wcc-input-error-alert {
  color: #dc3545;
  padding: 5px 0px;
}
.wcc-section-cookies {
  .wcc-rich-text-editor-container {
    margin-top: -30px;
  }
}
.wcc-scanner-container {
  .wcc-app-accordion.wcc-app-accordion-boxed .wcc-app-accordion-title {
    background-color: #fafbfc;
    color: #2a3646;
    border-radius: 0px;
    margin-bottom: 0px;
    border: 1px solid #e9ebf8;
    padding: 13px 15px;
  }
  .wcc-app-accordion.wcc-app-accordion-boxed .wcc-app-accordion-title::before {
    content: none;
  }
  .wcc-app-accordion.wcc-app-accordion-boxed .wcc-app-accordion-title::after {
    content: "";
  }
  .wcc-app-accordion-title::after {
    display: block;
    width: 15px;
    height: 12px;
    opacity: 0.8;
    width: 14px;
    height: 14px;
    transition: -webkit-transform 100ms ease;
    transition: transform 100ms ease;
    transition: transform 100ms ease, -webkit-transform 100ms;
    -webkit-mask-image: url("~@/assets/plus-icon.svg");
    mask-image: url("~@/assets/plus-icon.svg");
    background-color: currentColor;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
    -webkit-mask-size: contain;
    mask-size: contain;
    -webkit-mask-position: center;
    mask-position: center;
  }
  .wcc-app-accordion-open
    > .wcc-app-accordion-trigger
    .wcc-app-accordion-title::after {
    -webkit-mask-image: url("~@/assets/minus-icon.svg");
    mask-image: url("~@/assets/minus-icon.svg");
  }
  .wcc-app-accordion.wcc-app-accordion-boxed
    .wcc-app-accordion-item
    > .wcc-app-accordion-content
    .wcc-app-accordion-content-inner {
    padding: 0px;
  }
  .wcc-app-accordion.wcc-app-accordion-boxed
    .wcc-app-accordion-open
    > .wcc-app-accordion-trigger
    .wcc-app-accordion-title {
    border: none;
    border-bottom: 1px solid #e9ebf8;
  }
}
.wcc-scanned-cookie-details .wcc-custom-table th,
.wcc-scanned-cookie-details .wcc-custom-table td {
  padding: 15px;
}
.wcc-scanned-cookie-details .wcc-custom-table {
  th:first-child,
  td:first-child {
    width: 20%;
  }
}
.wcc-scanned-urls {
  margin-top: 40px;
}
.wcc-scanned-urls .wcc-custom-table {
  th:first-child,
  td:first-child {
    width: 60%;
  }
}
.wcc-scanned-urls .wcc-custom-table > tbody {
  border: 1px solid #e9ebf8;
}
</style>