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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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import React, { useState, useEffect } from 'react';
import { api, NexusLogo } from '@nexus/shared';
import styles from './WorkerLab.module.css';

interface Job {
  id: string;
  task_name: string;
  status: string;
  duration_ms: number;
  queued_at: string;
  started_at: string;
  finished_at: string;
  args: any[];
  kwargs: Record<string, any>;
  result: any;
  error?: string;
  metadata?: Record<string, any>;
}

interface Stats {
  status_counts: Record<string, number>;
  avg_duration_ms: number;
  total_jobs: number;
}

export const WorkerLab: React.FC = () => {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [activeJobs, setActiveJobs] = useState<any[]>([]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [selectedJob, setSelectedJob] = useState<Job | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  // Pagination & Filtering State
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [statusFilter, setStatusFilter] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [liveMode, setLiveMode] = useState(false);

  const fetchData = async (targetPage = page) => {
    try {
      setRefreshing(true);
      const params = {
        limit: 10,
        page: targetPage,
        status: statusFilter || undefined,
        search: searchTerm || undefined
      };

      const [histRes, statsRes, activeRes] = await Promise.all([
        api.get('worker/history/', { params }),
        api.get('worker/stats/'),
        api.get('worker/active/')
      ]);

      const history = histRes.data;
      setJobs(history.items);
      setTotalCount(history.total);
      setTotalPages(history.pages);
      setPage(history.page);

      setStats(statsRes.data);
      setActiveJobs(activeRes.data);
      
      if (!selectedJob && history.items.length > 0) {
        setSelectedJob(history.items[0]);
      }
    } catch (err) {
      console.error('Failed to fetch worker data:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchData(1);
  }, [statusFilter, searchTerm]);

  useEffect(() => {
    if (!liveMode) return;
    const interval = setInterval(() => fetchData(page), 15000); // 15s refresh in live mode
    return () => clearInterval(interval);
  }, [liveMode, page, statusFilter, searchTerm]);

  if (loading) return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: '16px' }}>
      <NexusLogo subtitle="CALIBRATING WORKER TELEMETRY..." />
      <div className="nexus-loading-bar" style={{ width: '200px' }}><div className="nexus-loading-progress" /></div>
    </div>
  );

  const formatTime = (ts: string) => {
    if (!ts) return '-';
    return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  };

  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || newPage > totalPages) return;
    fetchData(newPage);
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    // Simple alert for feedback, could be a toast
    alert('Copied to clipboard!');
  };

  const calculateWaitTime = (queued: string, started: string) => {
    if (!queued || !started) return 0;
    const q = new Date(queued).getTime();
    const s = new Date(started).getTime();
    return Math.max(0, s - q);
  };

  return (
    <div className={styles.container}>
      {/* Telemetry Stats */}
      <div className={styles.statsGrid}>
        <div className={styles.statCard}>
          <span className={styles.statLabel}>Throughput</span>
          <span className={styles.statValue}>{stats?.total_jobs || 0}</span>
          <span className={styles.statTrend}>Platform-wide executions</span>
        </div>
        <div className={styles.statCard} style={{ '--accent': '#10b981' } as any}>
          <span className={styles.statLabel}>Success Rate</span>
          <span className={styles.statValue}>
            {stats?.total_jobs ? Math.round(((stats.status_counts.success || 0) / stats.total_jobs) * 100) : 0}%
          </span>
          <span className={styles.statTrend}>Operational Stability</span>
        </div>
        <div className={styles.statCard} style={{ '--accent': '#3b82f6' } as any}>
          <span className={styles.statLabel}>Active Queues</span>
          <span className={styles.statValue}>{activeJobs.length}</span>
          <span className={styles.statTrend}>Live background tasks</span>
        </div>
        <div className={styles.statCard} style={{ '--accent': '#a855f7' } as any}>
          <span className={styles.statLabel}>Avg Latency</span>
          <span className={styles.statValue}>{Math.round(stats?.avg_duration_ms || 0)}ms</span>
          <span className={styles.statTrend}>System responsiveness</span>
        </div>
      </div>

      <div className={styles.mainPanel}>
        {/* History Table */}
        <div className={styles.jobTableContainer}>
          <div className={styles.tableHeader}>
            <h3 className={styles.tableTitle}>Execution History</h3>
            <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', color: 'var(--text3)' }}>
                <input 
                  type="checkbox" 
                  checked={liveMode} 
                  onChange={(e) => setLiveMode(e.target.checked)}
                  style={{ cursor: 'pointer' }}
                />
                {liveMode ? 'LIVE' : 'MANUAL SYNC'}
              </div>
              <div className={liveMode ? styles.liveIndicator : ''} style={{ background: liveMode ? '#10b981' : '#6b7280' }} />
              <button 
                onClick={() => fetchData()} 
                className="nexus-btn-text" 
                style={{ fontSize: '11px', display: 'flex', alignItems: 'center', gap: '4px' }}
                disabled={refreshing}
              >
                <span className={refreshing ? styles.spin : ''}>🔄</span>
                {refreshing ? 'REFRESHING...' : 'FORCE REFRESH'}
              </button>
            </div>
          </div>

          <div className={styles.filterBar}>
            <input 
              className={styles.searchInput}
              placeholder="Search by Task Name or ID..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
            <select 
              className={styles.selectInput}
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
            >
              <option value="">All Statuses</option>
              <option value="success">Success</option>
              <option value="failed">Failed</option>
              <option value="running">Running</option>
              <option value="queued">Queued</option>
            </select>
          </div>
          
          <table className={`${styles.jobTable} ${refreshing ? styles.refreshingTable : ''}`}>
            <thead>
              <tr>
                <th>Task</th>
                <th>Status</th>
                <th>Queued</th>
                <th>Latency</th>
                <th>ID</th>
              </tr>
            </thead>
            <tbody>
              {jobs.map((job) => (
                <tr 
                  key={job.id} 
                  className={`${styles.jobRow} ${selectedJob?.id === job.id ? styles.selected : ''}`}
                  onClick={() => setSelectedJob(job)}
                >
                  <td>
                    <span className={styles.taskName}>{job.task_name}</span>
                  </td>
                  <td>
                    <span className={`${styles.statusBadge} ${styles[`status_${job.status}`]}`}>
                      {job.status}
                    </span>
                  </td>
                  <td>{formatTime(job.queued_at)}</td>
                  <td>{job.duration_ms ? `${Math.round(job.duration_ms)}ms` : '-'}</td>
                  <td style={{ opacity: 0.5, fontSize: '10px' }}>{job.id.slice(0, 8)}</td>
                </tr>
              ))}
              {jobs.length === 0 && (
                <tr>
                  <td colSpan={5} className={styles.emptyState}>No job history matches your filters.</td>
                </tr>
              )}
            </tbody>
          </table>

          {/* Pagination Footer */}
          <div className={styles.pagination}>
            <div className={styles.pageInfo}>
              Showing {(page - 1) * 10 + 1} - {Math.min(page * 10, totalCount)} of {totalCount} jobs
            </div>
            <div className={styles.pageControls}>
              <button 
                className={styles.pageBtn} 
                onClick={() => handlePageChange(1)}
                disabled={page === 1}
              >«</button>
              <button 
                className={styles.pageBtn} 
                onClick={() => handlePageChange(page - 1)}
                disabled={page === 1}
              >PREV</button>
              <button className={`${styles.pageBtn} ${styles.pageBtnActive}`}>
                {page}
              </button>
              <button 
                className={styles.pageBtn} 
                onClick={() => handlePageChange(page + 1)}
                disabled={page === totalPages}
              >NEXT</button>
              <button 
                className={styles.pageBtn} 
                onClick={() => handlePageChange(totalPages)}
                disabled={page === totalPages}
              >»</button>
            </div>
          </div>
        </div>

        {/* Sidebar Diagnostics */}
        <div className={styles.sideDetail}>
          {selectedJob ? (
            <>
              <div className={styles.detailCard}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                  <h4 className={styles.detailTitle} style={{ margin: 0 }}>🆔 Identity</h4>
                  <button 
                    onClick={() => copyToClipboard(selectedJob.id)}
                    className="nexus-btn-text"
                    style={{ fontSize: '10px', color: 'var(--accent)' }}
                  >
                    COPY FULL ID
                  </button>
                </div>
                <div className={styles.idBox}>{selectedJob.id}</div>
              </div>

              <div className={styles.detailCard}>
                <h4 className={styles.detailTitle}>⏱️ Timeline</h4>
                <div className={styles.timeline}>
                  <div className={styles.timelineItem}>
                    <div className={styles.timelinePoint} />
                    <div className={styles.timelineLabel}>Queued</div>
                    <div className={styles.timelineTime}>{new Date(selectedJob.queued_at).toLocaleTimeString()}</div>
                  </div>
                  <div className={styles.timelineConnector}>
                    <span>Wait: {calculateWaitTime(selectedJob.queued_at, selectedJob.started_at)}ms</span>
                  </div>
                  <div className={styles.timelineItem}>
                    <div className={styles.timelinePoint} />
                    <div className={styles.timelineLabel}>Started</div>
                    <div className={styles.timelineTime}>{selectedJob.started_at ? formatTime(selectedJob.started_at) : 'Pending...'}</div>
                  </div>
                  <div className={styles.timelineConnector}>
                    <span>Exec: {selectedJob.duration_ms ? `${Math.round(selectedJob.duration_ms)}ms` : '...'}</span>
                  </div>
                  <div className={styles.timelineItem}>
                    <div className={styles.timelinePoint} />
                    <div className={styles.timelineLabel}>Finished</div>
                    <div className={styles.timelineTime}>{selectedJob.finished_at ? formatTime(selectedJob.finished_at) : '...'}</div>
                  </div>
                </div>
              </div>

              <div className={styles.detailCard}>
                <h4 className={styles.detailTitle}>📥 Payload</h4>
                <div className={styles.jsonBox}>
                  <pre>{JSON.stringify({ args: selectedJob.args, kwargs: selectedJob.kwargs }, null, 2)}</pre>
                </div>
              </div>

              {selectedJob.metadata && Object.keys(selectedJob.metadata).length > 0 && (
                <div className={styles.detailCard} style={{ borderLeft: '4px solid var(--accent)' }}>
                  <h4 className={styles.detailTitle}>🧩 Context Metadata</h4>
                  <div className={styles.metadataGrid}>
                    {Object.entries(selectedJob.metadata).map(([key, val]) => (
                      <div key={key} className={styles.metadataRow}>
                        <span className={styles.metadataLabel}>{key}</span>
                        <span className={styles.metadataValue}>{String(val)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div className={styles.detailCard}>
                <h4 className={styles.detailTitle}>📤 Result</h4>
                {selectedJob.status === 'failed' ? (
                  <div className={styles.errorBox}>
                    {selectedJob.error || 'Unknown execution error occurred.'}
                  </div>
                ) : (
                  <div className={styles.jsonBox}>
                    <pre>{JSON.stringify(selectedJob.result || { status: 'OK' }, null, 2)}</pre>
                  </div>
                )}
              </div>
            </>
          ) : (
            <div className={styles.emptyState}>Select a job to view diagnostics.</div>
          )}
        </div>
      </div>
    </div>
  );
};