import { Component, CUSTOM_ELEMENTS_SCHEMA, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Products } from '../services/products.service';
import { FormsModule } from '@angular/forms';
import { OrderService } from '../services/order.service';

@Component({
  selector: 'app-productconfigpage',
  imports: [FormsModule],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  templateUrl: './productconfigpage.html',
  styleUrl: './productconfigpage.scss',
})
export class Productconfigpage {
  private selectedProduct = inject(ActivatedRoute);
  productService = inject(Products);
  orderService = inject(OrderService);

  productId = this.selectedProduct.snapshot.paramMap.get('id');
  product = this.productService.getProductList().find((p) => p.id === Number(this.productId));

  // Add index signature so template can safely use options[option.key]
  extraBacon: boolean = false;
  saladAmount: 'less' | 'normal' | 'much' = 'normal';

  console = console;
  
  get priceDelta(): number {
    let delta = 0;
    // Greift direkt auf this.extraBacon zu
    if (this.extraBacon) { 
      delta += 1.5;
    }
    // Greift direkt auf this.saladAmount zu
    switch (this.saladAmount) {
      case 'less':
        delta -= 0.5;
        break;
      case 'much':
        delta += 0.5;
        break;
    }
    return delta;
  }
  
  // Wandle die Funktion in einen GETTER um (keine Argumente!)
  get totalPrice(): number {
    // Ruft den Getter this.priceDelta auf
    return (this.product?.basePrice || 0) + this.priceDelta;
  }


  addToCart(isBaconChecked: boolean, selectedSaladAmount: 'less' | 'normal' | 'much') {
        
        // set the variables
        this.extraBacon = isBaconChecked;
        this.saladAmount = selectedSaladAmount;
        
        // save to localStorage
        localStorage.setItem('cart', JSON.stringify({
            product: this.product,
            config: {
                extraBacon: this.extraBacon,
                saladAmount: this.saladAmount,
                priceDelta: this.priceDelta,
            },
            totalPrice: this.totalPrice,
        }));

        this.orderService.updateOrder({
            product: this.product,
            config: {
                extraBacon: this.extraBacon,
                saladAmount: this.saladAmount,
                priceDelta: this.priceDelta,
            },
            totalPrice: this.totalPrice,
        });
    }
}
