<template>
  <div>
    <div v-if="isOpenSideCart" class="sidecart-overlay" @click="closeSideCart"></div>
    <div :id="'sidecart'" :class="['header__side', { open_sidecart: isOpenSideCart }]">
      <div class="side-cart-header">
        <h4>Meu Carrinho</h4>
        <button class="btn-close-sidecart" @click="closeSideCart">
          <i class="fa-solid fa-x"></i>
        </button>
      </div>
      <div class="side-cart-body">
        <div v-if="localCartItems.length > 0" class="side-cart-content">
          <div class="cart-items-scroll">
            <div v-for="product in localCartItems" :key="product.key" class="cart-item">
              <div class="item-image">
                <a :href="product.href">
                  <img :src="product.thumb" :alt="product.name" :title="product.name" />
                </a>
              </div>
              <div class="item-details">
                <div class="item-title">
                  <a :href="product.href">{{ product.name }}</a>
                </div>
                <div v-if="!hideButtons" class="item-actions">
                  <div class="quantity-controls" :data-product-key="product.key">
                    <button class="btn-decrement" @click="changeQuantity(product, -1)">
                      <i class="fas fa-minus"></i>
                    </button>
                    <input
                      class="quantity-input"
                      type="number"
                      min="1"
                      :value="product.quantity"
                      @input="handleQuantityInput($event)"
                      @keydown="blockInvalidKeys"
                      @change="manualQuantityChange($event, product)"
                    />
                    <button class="btn-increment" @click="changeQuantity(product, 1)">
                      <i class="fas fa-plus"></i>
                    </button>
                  </div>
                  <button
                    class="btn-remove-product-sidecart"
                    @click="removeProductSideCart(product)"
                  >
                    <i class="fas fa-trash" title="Remover"></i>
                  </button>
                </div>
                <div v-else class="quantity-text">
                  Quantidade: <span class="quantity-value">{{ product.quantity }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="action-buttons flex flex-row nowrap-xs">
            <a :href="cartLink" class="button-cart">
              <span>Ver carrinho</span>
            </a>
            <a :href="checkoutLink" class="button-proceed-checkout">
              <span>Finalizar</span>
            </a>
          </div>
        </div>
        <div v-else class="sidecart-empty">
          <p class="empty-text">Seu carrinho de compras está vazio.</p>
          <button type="button" class="empty-button" @click="closeSideCart">
            CONTINUAR COMPRANDO
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  props: {
    cartItems: {
      type: Array,
      default: () => [],
    },
    cartLink: {
      type: String,
      required: true,
    },
    checkoutLink: {
      type: String,
      required: true,
    },
    currentRoute: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      isOpenSideCart: false,
      localCartItems: [],
    };
  },

  computed: {
    hideButtons() {
      return (
        this.currentRoute === "checkout/cart" || this.currentRoute === "checkout/checkout"
      );
    },
  },

  mounted() {
    window.addEventListener("toggle-sidecart", this.toggleSidecartVisibility);
    window.addEventListener("click", this.handleClickOutside);
  },

  beforeUnmount() {
    window.removeEventListener("toggle-sidecart", this.toggleSidecartVisibility);
    window.removeEventListener("click", this.handleClickOutside);
    document.body.classList.remove("no-scroll");
  },

  watch: {
    isOpenSideCart(val) {
      const body = document.body;

      if (val) {
        body.classList.add("no-scroll");
      } else {
        body.classList.remove("no-scroll");
      }
    },
    cartItems: {
      immediate: true,
      handler(newVal) {
        this.localCartItems = [...newVal]; // clona os dados
      },
    },
  },

  methods: {
    toggleCart() {
      this.isOpenSideCart = !this.isOpenSideCart;
    },

    toggleSidecartVisibility() {
      this.isOpenSideCart = !this.isOpenSideCart;

      if (this.isOpenSideCart) {
        this.fetchUpdatedCartItems();
      }
    },

    closeSideCart() {
      this.isOpenSideCart = false;
    },

    handleClickOutside(event) {
      const sidecartEl = this.$el;
      const toggleBtn = document.getElementById("btn-toggle-sidecart");

      if (!this.isOpenSideCart) {
        return;
      }

      if (sidecartEl.contains(event.target)) {
        return;
      }

      if (toggleBtn && toggleBtn.contains(event.target)) {
        return;
      }

      this.closeSideCart();
    },

    async removeProductSideCart(product) {
      const productKey = product.key;

      const formData = new FormData();
      formData.append(`quantity[${productKey}]`, 0);

      try {
        const response = await axios.post(
          "index.php?route=checkout/cart&ajax=1",
          formData,
          {
            headers: { "Content-Type": "multipart/form-data" },
          }
        );

        const data = response.data;

        if (typeof this.fetchUpdatedCartItems === "function") {
          await this.fetchUpdatedCartItems();
        }

        if (typeof handlerNotification === "function") {
          handlerNotification(data);
        }

        this.localCartItems = this.localCartItems.filter((p) => p.key !== productKey);

        if (typeof window.updateFloatingCart === "function") {
          window.updateFloatingCart(-product.quantity);
        }
      } catch (error) {
        console.error("Erro ao remover produto:", error);
      }
    },

    async changeQuantity(product, delta) {
      const productKey = product.key;
      const currentQuantity = product.quantity;
      const newQuantity = currentQuantity + delta;

      if (newQuantity < 1) return;

      await this.updateProductQuantity(productKey, newQuantity);
    },

    async manualQuantityChange(event, product) {
      const input = event.target;
      const productKey = product.key;
      const newQuantity = parseInt(input.value, 10);

      if (isNaN(newQuantity) || newQuantity < 1) {
        input.value = product.quantity;
        return;
      }

      await this.updateProductQuantity(productKey, newQuantity);
    },

    handleQuantityInput(event) {
      this.preventNegativeInput(event);
      this.maxValue(event);
    },

    preventNegativeInput(event) {
      const input = event.target;
      if (parseInt(input.value, 10) < 1) {
        input.value = 1;
      }
    },

    maxValue(event) {
      const input = event.target;
      const value = parseInt(input.value, 10);
      if (value > 9999) {
        input.value = 9999;
      }
    },

    blockInvalidKeys(event) {
      const invalidKeys = ["-", "+", "e", "E"];
      if (invalidKeys.includes(event.key)) {
        event.preventDefault();
      }
    },

    async updateProductQuantity(productKey, newQuantity) {
      const formData = new FormData();
      formData.append(`quantity[${productKey}]`, newQuantity);

      try {
        const response = await axios.post(
          "index.php?route=checkout/cart&ajax=1",
          formData,
          {
            headers: { "Content-Type": "multipart/form-data" },
          }
        );

        const data = response.data;

        // verifica mensagens vindas do backend
        if (data.success || (!data.error_warning && !data.attention)) {
          const item = this.localCartItems.find((p) => p.key === productKey);
          if (item) item.quantity = newQuantity;

          // atualiza contador do carrinho
          setTimeout(() => {
            window.updateFloatingCart();
          }, 300);
        } else {
          // exibe a mensagem real vinda do backend
          if (typeof handlerNotification === "function") {
            handlerNotification(data);
          } else if (typeof window.notificationMsg === "function") {
            const message =
              data.error_warning || data.attention || "Erro ao atualizar a quantidade.";
            const type = data.error_warning ? "warning" : "info";
            window.notificationMsg(message, type);
          }

          console.warn(
            "Erro do backend ao atualizar quantidade:",
            data.error_warning || data.attention
          );
        }
      } catch (error) {
        console.error("Erro na requisição ao atualizar quantidade:", error);
      }
    },

    async fetchUpdatedCartItems() {
      try {
        const response = await axios.get(
          "index.php?route=checkout/cart/onReloadCartList&ajax=1"
        );

        const parser = new DOMParser();
        const doc = parser.parseFromString(response.data, "text/html");

        const items = [...doc.querySelectorAll(".js-order-by-item")];

        const parsedItems = items.map((item, index) => {
          const key = (item.id ? item.id : `item-sem-id-${index}`) + "::";

          const name = item.dataset.name ?? "Produto sem nome";
          const quantity = parseInt(item.dataset.quantity, 10);
          const price = parseFloat(item.dataset.unitPrice);

          // captura da imagem (thumb)
          const imgEl = item.querySelector("img");
          let thumb = "";

          if (imgEl) {
            const srcAttr = imgEl.getAttribute("src");
            if (srcAttr && srcAttr.trim() !== "") {
              thumb = srcAttr;
            } else {
              thumb = "data/sem-imagem-80x80.png"; // fallback manual, só se quebrar
            }
          } else {
            thumb = "data/sem-imagem-80x80.png";
          }

          const hrefElement = item.querySelector("a[href]");
          const href = hrefElement ? hrefElement.getAttribute("href") : "#";

          return {
            key,
            name,
            quantity: isNaN(quantity) ? 0 : quantity,
            price: isNaN(price) ? 0 : price,
            href,
            thumb,
          };
        });

        // verificação de integridade
        const isValid = parsedItems.every((item) => {
          return (
            typeof item.key === "string" &&
            item.key.length > 0 &&
            typeof item.name === "string" &&
            item.name.length > 0 &&
            Number.isInteger(item.quantity) &&
            item.quantity >= 0 &&
            typeof item.price === "number" &&
            item.price >= 0
          );
        });

        if (!isValid) {
          console.warn(
            "%c[SideCart] Falha na validação dos dados do carrinho. O HTML da listagem pode ter sido alterado."
          );
        }

        this.localCartItems = parsedItems;
      } catch (error) {
        console.error("Erro ao buscar/sincronizar carrinho:", error);
      }
    },
  },
};
</script>

<style scoped>
.side-cart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fefefe;
  padding: 20px;
}

.side-cart-header h4 {
  font-size: 20px;
  font-weight: 500;
  color: #555;
}

.side-cart-header .btn-close-sidecart {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
}

.btn-close-sidecart i {
  font-size: 20px;
  color: #888;
}

.side-cart-body {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 80px); /* ajustar conforme necessário */
}

.side-cart-content {
  display: flex;
  flex-direction: column;
  flex: 1 1 auto;
  overflow: hidden;
}

.cart-items-scroll {
  flex: 1 1 auto;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #919191 transparent;
}

.cart-item {
  display: flex;
  gap: 15px;
  position: relative;
  padding: 20px 15px;
  background-color: #fefefe;
  border: 1px solid #e7e7e7;
  margin: 10px 12px;
  border-radius: 4px;
}

.item-image {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
}

.item-image a {
  display: block;
  width: 100%;
  height: 100%;
}

.item-image img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.item-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
}

.item-title a {
  width: 93%;
  font-size: 16px;
  color: #555;
  text-decoration: none;
  padding-bottom: 10px;
  display: block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.item-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 3px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 0px 8px;
}

.quantity-controls button {
  background: none;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.quantity-controls input {
  width: 55px;
  height: 35px;
  text-align: center;
  font-size: 16px;
  color: #333;
}

.btn-remove-product-sidecart {
  position: absolute;
  top: 15px;
  right: 10px;
  cursor: pointer;
  background: none;
}

.btn-remove-product-sidecart i {
  font-size: 20px;
  color: #555;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  padding: 15px 15px 7px 15px;
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.action-buttons a {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  font-weight: 600;
  border-radius: 4px;
  transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
  text-decoration: none;
  font-family: inherit;
  box-shadow: none;
}

.button-cart {
  background-color: #fff;
  border: 1px solid #e7e7e7;
  color: #333;
}

.button-cart:hover {
  background-color: #f7f7f7;
  border: 1px solid #dadada;
}

.button-proceed-checkout {
  background-color: #22407c;
  color: #fff;
  border: none;
}

.button-proceed-checkout:hover {
  background-color: #1b3261;
}

.quantity-text {
  font-size: 16px;
  color: #333;
  padding-top: 3px;
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .quantity-text {
    font-size: 14px;
  }
}

.quantity-value {
  color: #333;
  padding-left: 5px;
}

/* responsivo */
@media (min-width: 481px) and (max-width: 768px) {
  .item-title a {
    width: 90%;
  }

  .quantity-controls input {
    width: 35px;
    height: 30px;
    font-size: 14px;
  }

  .quantity-controls button {
    padding: 4px 10px;
    font-size: 16px;
  }

  .cart-item {
    padding: 12px 10px;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .item-image img {
    display: block;
    width: 70px;
    height: 70px;
  }

  .item-title a {
    width: 88%;
  }

  .cart-item {
    padding: 10px;
    margin: 8px 8px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }

  .action-buttons a {
    width: 100%;
    font-size: 14px;
    padding: 10px 0;
  }
}

.sidecart-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  min-height: 600px;
}

@media (max-width: 768px) {
  .sidecart-empty {
    min-height: 450px;
  }
}

.empty-text {
  font-size: 16px;
  color: #555;
  margin-bottom: 20px;
}

.empty-button {
  cursor: pointer;
  font-size: 14px;
  background-color: #222;
  color: #fff;
  text-transform: uppercase;
  letter-spacing: 1px;
  padding: 15px 24px;
  border: none;
  border-radius: 4px;
  text-decoration: none;
  transition: background-color 0.3s ease;
}

.empty-button:hover {
  background-color: #000;
}
</style>
