import { Component } from '@angular/core';
import { BreadcrumbComponent } from '../../../components/breadcrumb.component';
import { RouterLink } from '@angular/router';
import { BodyClassDirective } from "../../../directive/body-class.directive";

type productListType = {
  image: string;
  name: string;
  price: string;
  subtotal: string;
  quantity: number;
};

@Component({
  selector: 'app-cart',
  imports: [BreadcrumbComponent, RouterLink, BodyClassDirective],
  templateUrl: './cart.component.html',
  styles: ``,
})
export class CartComponent {
  cartHeadData: string[] = ['Product', 'Price', 'Quantity', 'Subtotal'];

  productList: productListType[] = [
    {
      image: 'assets/img/shop/product1.png',
      name: 'solar panel drill',
      price: '$180.00',
      quantity: 1,
      subtotal: '$180.00',
    },
    {
      image: 'assets/img/shop/product2.png',
      name: 'Solar bulbs',
      price: '$120.00',
      quantity: 2,
      subtotal: '$240.00',
    },
    {
      image: 'assets/img/shop/product3.png',
      name: 'Wind turbine tool',
      price: '$150.00',
      quantity: 1,
      subtotal: '$150.00',
    },
  ];

  

  cartTotals = {
  subTotal: 570,
  shipping: 10,
  total: 580
};

  incrementQuantity(index: number): void {
    const item = this.productList[index];
    item.quantity += 1;
    this.updateSubtotal(index);
  }

  decrementQuantity(index: number): void {
    const item = this.productList[index];
    if (item.quantity > 1) {
      item.quantity -= 1;
      this.updateSubtotal(index);
    }
  }

updateSubtotal(index: number): void {
  const item = this.productList[index];
  const unitPrice = parseFloat(item.price.replace('$', ''));
  const newSubtotal = unitPrice * item.quantity;
  item.subtotal = `$${newSubtotal.toFixed(2)}`;
  this.calculateCartTotals();
}

calculateCartTotals(): void {
  let subTotal = 0;

  for (const item of this.productList) {
    const cleanSubtotal = parseFloat(item.subtotal.replace('$', ''));
    subTotal += cleanSubtotal;
  }

  this.cartTotals.subTotal = subTotal;
  this.cartTotals.total = subTotal + this.cartTotals.shipping;
}

}
