File size: 2,567 Bytes
e66d96b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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<ApiKeyContextType | undefined>(undefined);

export function ApiKeyProvider({ children }: { children: ReactNode }) {
  const [apiKeys, setApiKeys] = useState<ApiKey[]>(() => {
    const saved = localStorage.getItem("smartlead_api_keys");
    return saved ? JSON.parse(saved) : [];
  });
  
  const [activeKeyId, setActiveKeyIdState] = useState<string | null>(() => {
    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 (
    <ApiKeyContext.Provider

      value={{

        apiKeys,

        activeKeyId,

        activeKey,

        addApiKey,

        removeApiKey,

        renameApiKey,

        setActiveKeyId: setActiveKeyIdState,

      }}

    >

      {children}

    </ApiKeyContext.Provider>
  );
}

export function useApiKey() {
  const context = useContext(ApiKeyContext);
  if (context === undefined) {
    throw new Error("useApiKey must be used within an ApiKeyProvider");
  }
  return context;
}