'use client';

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

export interface CompareProduct {
  id: string;
  name: string;
  nameAr: string;
  price: number;
  image: string;
  slug: string;
  specs: {
    display: string;
    processor: string;
    ram: string;
    storage: string;
    battery: string;
    camera: string;
    os: string;
  };
}

interface CompareContextType {
  products: CompareProduct[];
  addProduct: (p: CompareProduct) => void;
  removeProduct: (id: string) => void;
  isComparing: (id: string) => boolean;
  clearAll: () => void;
  count: number;
  MAX: number;
}

const CompareContext = createContext<CompareContextType>({} as CompareContextType);
const MAX = 4;

export function CompareProvider({ children }: { children: React.ReactNode }) {
  const [products, setProducts] = useState<CompareProduct[]>([]);

  useEffect(() => {
    const saved = localStorage.getItem('ftp-compare');
    if (saved) setProducts(JSON.parse(saved));
  }, []);

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

  const addProduct = (p: CompareProduct) => {
    setProducts(prev => {
      if (prev.length >= MAX || prev.find(x => x.id === p.id)) return prev;
      return [...prev, p];
    });
  };

  const removeProduct = (id: string) => setProducts(prev => prev.filter(p => p.id !== id));
  const isComparing = (id: string) => products.some(p => p.id === id);
  const clearAll = () => {
    setProducts([]);
    localStorage.removeItem('ftp-compare');
  };

  return (
    <CompareContext.Provider value={{ products, addProduct, removeProduct, isComparing, clearAll, count: products.length, MAX }}>
      {children}
    </CompareContext.Provider>
  );
}

export const useCompare = () => useContext(CompareContext);
