File size: 15,147 Bytes
e4c7604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import React, { useState } from 'react';
import { GlobalStats } from '../types';

interface AdminViewProps {
  stats: GlobalStats;
}

const AdminView: React.FC<AdminViewProps> = ({ stats }) => {
  const [activeTab, setActiveTab] = useState<'overview' | 'sync' | 'payouts' | 'assistant'>('assistant');
  const [syncTarget, setSyncTarget] = useState<'vercel' | 'huggingface'>('vercel');
  
  const VERCEL_TOKEN = process.env.VITE_VERCEL_TOKEN || '';
  const GEMINI_KEY = process.env.GEMINI_API_KEY || '';

  const [projects, setProjects] = useState<any[]>([]);
  const [selectedProject, setSelectedProject] = useState('');
  const [isSyncing, setIsSyncing] = useState(false);
  const [status, setStatus] = useState({ msg: '', type: 'info' });

  const fetchProjects = async () => {
    if (!VERCEL_TOKEN) {
      setStatus({ 
        msg: 'Vercel Token Missing! Please set VITE_VERCEL_TOKEN in environment variables.', 
        type: 'error' 
      });
      return;
    }
    setIsSyncing(true);
    setStatus({ msg: 'Syncing Vercel Projects...', type: 'info' });
    try {
      const res = await fetch(`https://api.vercel.com/v9/projects`, {
        headers: { 'Authorization': `Bearer ${VERCEL_TOKEN}` }
      });
      const data = await res.json();
      if (data.projects) {
        setProjects(data.projects);
        setStatus({ msg: 'Projects Loaded Successfully!', type: 'success' });
      } else {
        throw new Error(data.error?.message || 'Could not fetch projects.');
      }
    } catch (err: any) {
      setStatus({ msg: err.message, type: 'error' });
    } finally {
      setIsSyncing(false);
    }
  };

  const handleDeploy = async () => {
    if (!VERCEL_TOKEN) {
      setStatus({ msg: 'Vercel Token Missing!', type: 'error' });
      return;
    }
    if (!selectedProject) return;
    setIsSyncing(true);
    setStatus({ msg: 'Phase 1: Injecting API_KEY...', type: 'info' });
    
    try {
      const proj = projects.find(p => p.name === selectedProject);
      if (!proj) throw new Error("Project mismatch.");

      // 1. Upsert Environment Variable (API_KEY)
      const currentEnvRes = await fetch(`https://api.vercel.com/v9/projects/${proj.id}/env`, {
        headers: { 'Authorization': `Bearer ${VERCEL_TOKEN}` }
      });
      const envData = await currentEnvRes.json();
      const existingKey = envData.envs?.find((e: any) => e.key === 'API_KEY');

      if (existingKey) {
        await fetch(`https://api.vercel.com/v9/projects/${proj.id}/env/${existingKey.id}`, {
          method: 'PATCH',
          headers: { 'Authorization': `Bearer ${VERCEL_TOKEN}`, 'Content-Type': 'application/json' },
          body: JSON.stringify({ value: GEMINI_KEY })
        });
      } else {
        await fetch(`https://api.vercel.com/v10/projects/${proj.id}/env`, {
          method: 'POST',
          headers: { 'Authorization': `Bearer ${VERCEL_TOKEN}`, 'Content-Type': 'application/json' },
          body: JSON.stringify({
            key: 'API_KEY', value: GEMINI_KEY, type: 'plain', target: ['production', 'preview', 'development']
          })
        });
      }

      // 2. Direct Redeploy Trigger (Phase 2)
      setStatus({ msg: 'Phase 2: Triggering Production Build...', type: 'info' });
      
      const lastDeployRes = await fetch(`https://api.vercel.com/v6/deployments?projectId=${proj.id}&limit=1&state=READY`, {
        headers: { 'Authorization': `Bearer ${VERCEL_TOKEN}` }
      });
      const lastDeployData = await lastDeployRes.json();
      const deploymentId = lastDeployData.deployments?.[0]?.uid;

      if (!deploymentId) {
        throw new Error("No previous build found. Please deploy manually once.");
      }

      const triggerRes = await fetch(`https://api.vercel.com/v13/deployments`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${VERCEL_TOKEN}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: selectedProject, deploymentId: deploymentId, target: 'production' })
      });

      if (triggerRes.ok) {
        setStatus({ msg: '๐Ÿš€ LAUNCH SUCCESS! Vercel is now building your node.', type: 'success' });
      } else {
        const errorData = await triggerRes.json();
        throw new Error(errorData.error?.message || "Failed to start build.");
      }
    } catch (err: any) {
      setStatus({ msg: err.message || 'System Error', type: 'error' });
    } finally {
      setIsSyncing(false);
    }
  };

  const isDeployed = status.type === 'success';

  return (
    <div className="p-4 md:p-8 max-w-6xl mx-auto min-h-screen font-sans">
      <div className="flex gap-4 mb-12 border-b border-white/5 pb-4 overflow-x-auto no-scrollbar">
        <button onClick={() => setActiveTab('assistant')} className={`px-6 py-2 font-black uppercase text-[10px] tracking-widest whitespace-nowrap transition-all ${activeTab === 'assistant' ? 'text-amber-400 border-b-2 border-amber-400' : 'text-slate-600'}`}>Business Setup ๐Ÿš€</button>
        <button onClick={() => setActiveTab('sync')} className={`px-6 py-2 font-black uppercase text-[10px] tracking-widest whitespace-nowrap transition-all ${activeTab === 'sync' ? 'text-emerald-400 border-b-2 border-emerald-400' : 'text-slate-600'}`}>Node Sync โšก</button>
        <button onClick={() => setActiveTab('overview')} className={`px-6 py-2 font-black uppercase text-[10px] tracking-widest whitespace-nowrap transition-all ${activeTab === 'overview' ? 'text-indigo-400 border-b-2 border-indigo-400' : 'text-slate-600'}`}>Platform Stats</button>
      </div>

      {activeTab === 'assistant' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 animate-in zoom-in duration-300">
           <div className="bg-[#0a0f1e] border border-amber-500/20 p-10 rounded-[50px] shadow-3xl">
              <h3 className="text-3xl font-black text-white italic uppercase tracking-tighter mb-8">Launch Celebration</h3>
              <div className="space-y-6">
                 {[
                   { step: '1', title: 'Node Activation', desc: 'Vercel deployment successfully triggered.', done: isDeployed },
                   { step: '2', title: 'Wallet Setup', desc: 'Exit admin and go to "Vault" to link UPI.', done: false },
                   { step: '3', title: 'Viral Traffic', desc: 'Use AI Ad Manager in Dashboard to share.', done: false },
                   { step: '4', title: 'Passive Royalties', desc: 'Track INR income in real-time.', done: false }
                 ].map((s, i) => (
                   <div key={i} className={`flex items-start gap-4 p-6 rounded-3xl border transition-all ${s.done ? 'bg-emerald-500/5 border-emerald-500/20' : 'bg-black/40 border-white/5'}`}>
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center font-black text-xs ${s.done ? 'bg-emerald-500 text-black' : 'bg-slate-800 text-slate-400'}`}>
                        {s.done ? 'โœ“' : s.step}
                      </div>
                      <div>
                        <p className={`font-black text-sm uppercase ${s.done ? 'text-emerald-400' : 'text-white'}`}>{s.title}</p>
                        <p className="text-slate-500 text-[10px] mt-1 font-medium">{s.desc}</p>
                      </div>
                   </div>
                 ))}
              </div>
           </div>
           <div className={`p-10 rounded-[50px] flex flex-col justify-between shadow-3xl transition-all ${isDeployed ? 'bg-emerald-500 shadow-emerald-500/20' : 'bg-amber-500 shadow-amber-500/20'}`}>
              <div>
                <h3 className={`text-4xl font-black italic uppercase tracking-tighter mb-4 ${isDeployed ? 'text-emerald-950' : 'text-slate-900'}`}>{isDeployed ? 'YOU ARE LIVE!' : 'Setup Assistant'}</h3>
                <p className={`text-sm leading-relaxed font-bold ${isDeployed ? 'text-emerald-900/70' : 'text-slate-900/70'}`}>
                  {isDeployed 
                    ? "Bhai, aapka business live ho chuka hai. Ab aap terminal ko band karke main app par jaayein aur apna pehla UPI payout setup karein!"
                    : "Aapka system automation mode mein hai. Har run par aapko royalty milegi. Node Sync tab mein jaakar deploy trigger karein."}
                </p>
              </div>
              <div className="bg-black/10 p-6 rounded-3xl border border-black/10 mt-8">
                 <button 
                   onClick={() => { window.location.hash = ''; window.location.reload(); }} 
                   className={`w-full py-5 rounded-2xl font-black uppercase text-xs tracking-widest transition-all ${isDeployed ? 'bg-emerald-950 text-white' : 'bg-slate-900 text-white'}`}
                 >
                   Open My Business Storefront
                 </button>
              </div>
           </div>
        </div>
      )}

      {activeTab === 'sync' && (
        <div className="bg-[#0a0f1e] border border-emerald-500/10 p-10 rounded-[50px] shadow-3xl">
          <div className="flex items-center gap-4 mb-10">
            <div className="w-16 h-16 bg-emerald-500/10 rounded-3xl flex items-center justify-center border border-emerald-500/20 text-emerald-500">
              <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>
            </div>
            <div className="flex-1">
              <h3 className="text-2xl font-black text-white italic uppercase tracking-tighter">AI Node Sync</h3>
              <div className="flex gap-4 mt-2">
                <button onClick={() => setSyncTarget('vercel')} className={`text-[8px] font-black uppercase tracking-widest px-3 py-1 rounded-full border transition-all ${syncTarget === 'vercel' ? 'bg-white text-black border-white' : 'text-slate-500 border-slate-800 hover:text-white'}`}>Vercel</button>
                <button onClick={() => setSyncTarget('huggingface')} className={`text-[8px] font-black uppercase tracking-widest px-3 py-1 rounded-full border transition-all ${syncTarget === 'huggingface' ? 'bg-amber-500 text-black border-amber-500' : 'text-slate-500 border-slate-800 hover:text-white'}`}>Hugging Face</button>
              </div>
            </div>
          </div>

          <div className="space-y-6">
            {syncTarget === 'vercel' ? (
              <>
                <div className="p-8 bg-black/50 rounded-[32px] border border-white/5">
                  <label className="text-[10px] font-black text-slate-600 uppercase mb-4 block tracking-widest">1. Scan Vercel Account</label>
                  <button onClick={fetchProjects} disabled={isSyncing} className="w-full bg-white text-black py-4 rounded-2xl font-black uppercase text-xs tracking-widest hover:scale-105 transition-all shadow-xl">
                    {isSyncing && projects.length === 0 ? 'Syncing...' : 'Fetch Projects'}
                  </button>
                </div>

                {projects.length > 0 && (
                  <div className="p-8 bg-black/50 rounded-[32px] border border-white/5 animate-in slide-in-from-top-4">
                    <label className="text-[10px] font-black text-slate-600 uppercase mb-4 block tracking-widest">2. Select Deployment Target</label>
                    <div className="relative mb-6">
                      <select value={selectedProject} onChange={e => setSelectedProject(e.target.value)} className="w-full bg-[#020617] border border-slate-800 p-5 rounded-2xl text-white font-bold outline-none appearance-none">
                        <option value="">Select Project...</option>
                        {projects.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
                      </select>
                    </div>
                    <button onClick={handleDeploy} disabled={isSyncing || !selectedProject} className="w-full bg-emerald-500 text-black py-6 rounded-2xl font-black uppercase text-xs tracking-widest shadow-2xl shadow-emerald-500/20 hover:scale-[1.02] active:scale-95 transition-all">
                       {isSyncing ? 'Building AI Engine...' : 'Redeploy AI Node'}
                    </button>
                  </div>
                )}
              </>
            ) : (
              <div className="p-8 bg-black/50 rounded-[32px] border border-white/5">
                <label className="text-[10px] font-black text-slate-600 uppercase mb-4 block tracking-widest">Hugging Face Auto-Sync</label>
                <div className="space-y-4">
                  <p className="text-slate-400 text-xs leading-relaxed">
                    Bhai, Hugging Face par automatic deploy karne ke liye aapko bas ek baar **Docker Space** banana hoga. 
                  </p>
                  <div className="bg-black/40 p-6 rounded-2xl border border-white/5">
                    <p className="text-[10px] font-black text-amber-400 uppercase mb-2">Setup Steps:</p>
                    <ul className="text-[9px] text-slate-500 space-y-2 list-disc pl-4">
                      <li>Create a new Space on Hugging Face.</li>
                      <li>Select **Docker** as the SDK.</li>
                      <li>Upload all files from this project (including Dockerfile).</li>
                      <li>App will automatically use the built-in API key.</li>
                    </ul>
                  </div>
                  <a 
                    href="https://huggingface.co/new-space" 
                    target="_blank" 
                    rel="noreferrer"
                    className="block w-full bg-amber-500 text-black py-4 rounded-2xl font-black uppercase text-xs tracking-widest text-center hover:scale-105 transition-all shadow-xl"
                  >
                    Open HF Space Creator
                  </a>
                </div>
              </div>
            )}

            {status.msg && (
              <div className={`p-6 rounded-2xl text-center font-black uppercase text-[10px] tracking-widest border transition-all animate-in fade-in ${status.type === 'error' ? 'bg-red-500/10 border-red-500/20 text-red-400' : status.type === 'success' ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' : 'bg-indigo-500/10 border-indigo-500/20 text-indigo-400'}`}>
                {status.msg}
              </div>
            )}
          </div>
        </div>
      )}

      {activeTab === 'overview' && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
          <div className="bg-[#0a0f1e] p-10 rounded-[40px] border border-white/5 shadow-2xl">
            <p className="text-[10px] font-black text-slate-600 uppercase mb-2 tracking-widest">Revenue</p>
            <p className="text-5xl font-black text-white italic">โ‚น{(stats.totalPlatformRevenue / 100).toLocaleString()}k</p>
          </div>
          <div className="bg-[#0a0f1e] p-10 rounded-[40px] border border-white/5 shadow-2xl">
            <p className="text-[10px] font-black text-slate-600 uppercase mb-2 tracking-widest">Nodes</p>
            <p className="text-5xl font-black text-indigo-400 italic">{stats.activeNodes}</p>
          </div>
        </div>
      )}
    </div>
  );
};

export default AdminView;