"use client";

import React, { createContext, useContext, useState, useEffect } from "react";
import { Property } from "@/data/properties";

interface CompareContextType {
    compareList: Property[];
    addToCompare: (property: Property) => void;
    removeFromCompare: (propertyId: number) => void;
    clearCompare: () => void;
    isInCompare: (propertyId: number) => boolean;
}

const CompareContext = createContext<CompareContextType | undefined>(undefined);

export function CompareProvider({ children }: { children: React.ReactNode }) {
    const [compareList, setCompareList] = useState<Property[]>([]);

    // Load from localStorage on mount
    useEffect(() => {
        const saved = localStorage.getItem("compareProperties");
        if (saved) {
            try {
                setCompareList(JSON.parse(saved));
            } catch (e) {
                console.error("Failed to load compare list:", e);
            }
        }
    }, []);

    // Save to localStorage whenever compareList changes
    useEffect(() => {
        localStorage.setItem("compareProperties", JSON.stringify(compareList));
    }, [compareList]);

    const addToCompare = (property: Property) => {
        if (compareList.length >= 4) {
            alert("You can compare up to 4 properties at a time");
            return;
        }
        if (!compareList.find(p => p.id === property.id)) {
            setCompareList([...compareList, property]);
        }
    };

    const removeFromCompare = (propertyId: number) => {
        setCompareList(compareList.filter(p => p.id !== propertyId));
    };

    const clearCompare = () => {
        setCompareList([]);
    };

    const isInCompare = (propertyId: number) => {
        return compareList.some(p => p.id === propertyId);
    };

    return (
        <CompareContext.Provider value={{ compareList, addToCompare, removeFromCompare, clearCompare, isInCompare }}>
            {children}
        </CompareContext.Provider>
    );
}

export function useCompare() {
    const context = useContext(CompareContext);
    if (context === undefined) {
        throw new Error("useCompare must be used within a CompareProvider");
    }
    return context;
}
