import { createContext, useContext, useState, useEffect, ReactNode } from "react"; interface ApiKey { id: string; name: string; key: string; createdAt: string; } interface ApiKeyContextType { apiKeys: ApiKey[]; activeKeyId: string | null; activeKey: string | null; addApiKey: (name: string, key: string) => void; removeApiKey: (id: string) => void; renameApiKey: (id: string, newName: string) => void; setActiveKeyId: (id: string) => void; } const ApiKeyContext = createContext(undefined); export function ApiKeyProvider({ children }: { children: ReactNode }) { const [apiKeys, setApiKeys] = useState(() => { const saved = localStorage.getItem("smartlead_api_keys"); return saved ? JSON.parse(saved) : []; }); const [activeKeyId, setActiveKeyIdState] = useState(() => { return localStorage.getItem("smartlead_active_key_id"); }); useEffect(() => { localStorage.setItem("smartlead_api_keys", JSON.stringify(apiKeys)); }, [apiKeys]); useEffect(() => { if (activeKeyId) { localStorage.setItem("smartlead_active_key_id", activeKeyId); } else { localStorage.removeItem("smartlead_active_key_id"); } }, [activeKeyId]); const addApiKey = (name: string, key: string) => { const newKey: ApiKey = { id: Math.random().toString(36).substring(7), name, key, createdAt: new Date().toISOString() }; setApiKeys((prev) => [...prev, newKey]); if (!activeKeyId) { setActiveKeyIdState(newKey.id); } }; const removeApiKey = (id: string) => { setApiKeys((prev) => prev.filter((k) => k.id !== id)); if (activeKeyId === id) { setActiveKeyIdState(null); } }; const renameApiKey = (id: string, newName: string) => { setApiKeys((prev) => prev.map((k) => k.id === id ? { ...k, name: newName } : k)); }; const activeKey = apiKeys.find((k) => k.id === activeKeyId)?.key || null; return ( {children} ); } export function useApiKey() { const context = useContext(ApiKeyContext); if (context === undefined) { throw new Error("useApiKey must be used within an ApiKeyProvider"); } return context; }