"use client"; import React, { useMemo, useState } from "react"; import { addToWatchlist, removeFromWatchlist } from "@/lib/actions/watchlist.actions"; import { toast } from "sonner"; interface WatchlistButtonProps { symbol: string; company: string; isInWatchlist: boolean; showTrashIcon?: boolean; type?: "button" | "icon"; userId?: string; // Made optional for backward compat, but required for actions onWatchlistChange?: (symbol: string, added: boolean) => void; } const WatchlistButton = ({ symbol, company, isInWatchlist, showTrashIcon = false, type = "button", userId, onWatchlistChange, }: WatchlistButtonProps) => { const [added, setAdded] = useState(!!isInWatchlist); const [loading, setLoading] = useState(false); const label = useMemo(() => { if (type === "icon") return added ? "" : ""; return added ? "Remove from Watchlist" : "Add to Watchlist"; }, [added, type]); const handleClick = async (e: React.MouseEvent) => { e.preventDefault(); // Prevent link navigation if inside a link if (!userId && !onWatchlistChange) { console.error("WatchlistButton: userId or onWatchlistChange is required"); toast.error("Please sign in to modify watchlist"); return; } const next = !added; setAdded(next); // Optimistic update setLoading(true); try { if (userId) { if (next) { await addToWatchlist(userId, symbol, company); toast.success(`${symbol} added to watchlist`); } else { await removeFromWatchlist(userId, symbol); toast.success(`${symbol} removed from watchlist`); } } // Call external handler if provided (e.g. for UI refresh) onWatchlistChange?.(symbol, next); } catch (error) { console.error("Watchlist action failed:", error); setAdded(!next); // Revert on error toast.error("Failed to update watchlist"); } finally { setLoading(false); } }; if (type === "icon") { return ( ); } return ( ); }; export default WatchlistButton;