'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';

export interface CartItem {
  id: string;
  name: string;
  nameAr: string;
  price: number;
  image: string;
  quantity: number;
  slug: string;
}

interface CartContextType {
  items: CartItem[];
  addItem: (item: Omit<CartItem, 'quantity'>) => void;
  removeItem: (id: string) => void;
  updateQuantity: (id: string, quantity: number) => void;
  clearCart: () => void;
  total: number;
  itemCount: number;
  coupon: string | null;
  couponDiscount: number;
  applyCoupon: (code: string) => boolean;
  removeCoupon: () => void;
}

const CartContext = createContext<CartContextType>({} as CartContextType);

const VALID_COUPONS: Record<string, number> = {
  'FASTTIME10': 10,
  'KUWAIT20': 20,
  'NEWUSER15': 15,
  'RAMADAN25': 25,
};

export function CartProvider({ children }: { children: React.ReactNode }) {
  const [items, setItems] = useState<CartItem[]>([]);
  const [coupon, setCoupon] = useState<string | null>(null);
  const [couponDiscount, setCouponDiscount] = useState(0);

  useEffect(() => {
    const saved = localStorage.getItem('ftp-cart');
    if (saved) setItems(JSON.parse(saved));
    const savedCoupon = localStorage.getItem('ftp-coupon');
    if (savedCoupon) {
      setCoupon(savedCoupon);
      setCouponDiscount(VALID_COUPONS[savedCoupon] || 0);
    }
  }, []);

  useEffect(() => {
    localStorage.setItem('ftp-cart', JSON.stringify(items));
  }, [items]);

  const addItem = (item: Omit<CartItem, 'quantity'>) => {
    setItems(prev => {
      const existing = prev.find(i => i.id === item.id);
      if (existing) {
        return prev.map(i => i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i);
      }
      return [...prev, { ...item, quantity: 1 }];
    });
  };

  const removeItem = (id: string) => {
    setItems(prev => prev.filter(i => i.id !== id));
  };

  const updateQuantity = (id: string, quantity: number) => {
    if (quantity <= 0) { removeItem(id); return; }
    setItems(prev => prev.map(i => i.id === id ? { ...i, quantity } : i));
  };

  const clearCart = () => {
    setItems([]);
    setCoupon(null);
    setCouponDiscount(0);
    localStorage.removeItem('ftp-cart');
    localStorage.removeItem('ftp-coupon');
  };

  const applyCoupon = (code: string): boolean => {
    const discount = VALID_COUPONS[code.toUpperCase()];
    if (discount) {
      setCoupon(code.toUpperCase());
      setCouponDiscount(discount);
      localStorage.setItem('ftp-coupon', code.toUpperCase());
      return true;
    }
    return false;
  };

  const removeCoupon = () => {
    setCoupon(null);
    setCouponDiscount(0);
    localStorage.removeItem('ftp-coupon');
  };

  const subtotal = items.reduce((sum, i) => sum + i.price * i.quantity, 0);
  const discountAmount = (subtotal * couponDiscount) / 100;
  const total = Math.max(0, subtotal - discountAmount);
  const itemCount = items.reduce((sum, i) => sum + i.quantity, 0);

  return (
    <CartContext.Provider value={{
      items, addItem, removeItem, updateQuantity, clearCart,
      total, itemCount, coupon, couponDiscount, applyCoupon, removeCoupon,
    }}>
      {children}
    </CartContext.Provider>
  );
}

export const useCart = () => useContext(CartContext);
