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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import { useEffect, useState, useMemo } from "react";
import { useAppState } from "./store";
import type { IterationSummary } from "./types";

const ADAPTATION_COLORS: Record<string, { bg: string; text: string; bar: string }> = {
  L1_explore: { bg: "bg-blue-900/40", text: "text-blue-400", bar: "bg-blue-500" },
  L1_exploit: { bg: "bg-green-900/40", text: "text-green-400", bar: "bg-green-500" },
  L2_migrate: { bg: "bg-amber-900/40", text: "text-amber-400", bar: "bg-amber-500" },
  L3_meta: { bg: "bg-red-900/40", text: "text-red-400", bar: "bg-red-500" },
};

const DEFAULT_COLOR = { bg: "bg-gray-900/40", text: "text-gray-400", bar: "bg-gray-500" };

function getAdaptationColor(type: string) {
  return ADAPTATION_COLORS[type] || DEFAULT_COLOR;
}

type SortKey = "iteration" | "score" | "best_score" | "delta" | "island_id" | "adaptation_type";
type SortDir = "asc" | "desc";

export default function AdaevolveApp() {
  const store = useAppState();
  const { state } = store;
  const [repoInput, setRepoInput] = useState("");
  const [sortKey, setSortKey] = useState<SortKey>("iteration");
  const [sortDir, setSortDir] = useState<SortDir>("asc");

  useEffect(() => {
    store.loadPresets();
  }, []);

  // Get the currently selected dataset
  const selectedDataset = useMemo(
    () => state.datasets.find((d) => d.id === state.selectedDatasetId) ?? null,
    [state.datasets, state.selectedDatasetId]
  );

  // Filter iterations by adaptation type
  const filteredIterations = useMemo(() => {
    if (!selectedDataset) return [];
    let iters = selectedDataset.iterations;
    if (state.filterAdaptation) {
      iters = iters.filter((it) => it.adaptation_type === state.filterAdaptation);
    }
    return iters;
  }, [selectedDataset, state.filterAdaptation]);

  // Sort iterations
  const sortedIterations = useMemo(() => {
    const sorted = [...filteredIterations];
    sorted.sort((a, b) => {
      const av = a[sortKey];
      const bv = b[sortKey];
      if (typeof av === "number" && typeof bv === "number") {
        return sortDir === "asc" ? av - bv : bv - av;
      }
      const sa = String(av);
      const sb = String(bv);
      return sortDir === "asc" ? sa.localeCompare(sb) : sb.localeCompare(sa);
    });
    return sorted;
  }, [filteredIterations, sortKey, sortDir]);

  // Get all unique adaptation types across selected dataset
  const adaptationTypes = useMemo(() => {
    if (!selectedDataset) return [];
    const types = new Set(selectedDataset.iterations.map((it) => it.adaptation_type));
    return Array.from(types).sort();
  }, [selectedDataset]);

  function handleSort(key: SortKey) {
    if (sortKey === key) {
      setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    } else {
      setSortKey(key);
      setSortDir("asc");
    }
  }

  function handleLoad() {
    if (repoInput.trim()) {
      store.loadDataset(repoInput.trim());
      setRepoInput("");
    }
  }

  // Compute max score for bar chart scaling
  const maxScore = useMemo(() => {
    if (!filteredIterations.length) return 1;
    return Math.max(...filteredIterations.map((it) => Math.abs(it.score)), 0.001);
  }, [filteredIterations]);

  const sortIndicator = (key: SortKey) => {
    if (sortKey !== key) return "";
    return sortDir === "asc" ? " ^" : " v";
  };

  return (
    <div className="flex h-full overflow-hidden">
      {/* Sidebar */}
      <div className="w-72 border-r border-gray-800 bg-gray-900 flex flex-col overflow-hidden shrink-0">
        {/* Repo input */}
        <div className="p-3 border-b border-gray-800">
          <label className="text-xs text-gray-500 mb-1 block">HuggingFace Repo</label>
          <div className="flex gap-1">
            <input
              type="text"
              value={repoInput}
              onChange={(e) => setRepoInput(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && handleLoad()}
              placeholder="org/dataset-name"
              className="flex-1 bg-gray-800 text-sm px-2 py-1.5 rounded border border-gray-700 focus:border-rose-500 focus:outline-none text-gray-200"
            />
            <button
              onClick={handleLoad}
              disabled={state.loading || !repoInput.trim()}
              className="bg-rose-600 hover:bg-rose-500 disabled:opacity-50 text-white text-sm px-3 py-1.5 rounded"
            >
              Load
            </button>
          </div>
        </div>

        {/* Presets */}
        <div className="p-3 border-b border-gray-800">
          <div className="text-xs text-gray-500 mb-2">Presets</div>
          {state.presets.length === 0 && (
            <div className="text-xs text-gray-600">No presets available</div>
          )}
          <div className="space-y-1 max-h-32 overflow-y-auto">
            {state.presets.map((p) => (
              <div
                key={p.id}
                className="flex items-center justify-between group"
              >
                <button
                  onClick={() => store.loadPreset(p)}
                  className="text-xs text-rose-400 hover:text-rose-300 truncate flex-1 text-left"
                  title={p.repo}
                >
                  {p.name}
                </button>
                <button
                  onClick={() => store.deletePreset(p.id)}
                  className="text-gray-600 hover:text-red-400 text-xs opacity-0 group-hover:opacity-100 ml-1"
                >
                  x
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Loaded datasets */}
        <div className="flex-1 overflow-y-auto p-3">
          <div className="text-xs text-gray-500 mb-2">
            Loaded Datasets ({state.datasets.length})
          </div>
          {state.datasets.map((ds) => (
            <div
              key={ds.id}
              className={`mb-3 p-2 rounded border cursor-pointer ${
                state.selectedDatasetId === ds.id
                  ? "border-rose-500 bg-rose-900/20"
                  : "border-gray-700 hover:border-gray-600"
              }`}
              onClick={() => store.selectDataset(ds.id)}
            >
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-200 truncate" title={ds.repo}>
                  {ds.name}
                </span>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    store.unloadDataset(ds.id);
                  }}
                  className="text-gray-600 hover:text-red-400 text-xs ml-1"
                >
                  x
                </button>
              </div>
              <div className="text-xs text-gray-500 mt-1">
                {ds.n_iterations} iterations | {ds.summary_stats.n_islands} islands
              </div>
              <div className="text-xs text-gray-500">
                Best: {ds.summary_stats.global_best.toFixed(4)}
              </div>
              {/* Adaptation breakdown */}
              <div className="mt-1 space-y-0.5">
                {Object.entries(ds.summary_stats.adaptation_counts).map(([type, count]) => {
                  const color = getAdaptationColor(type);
                  return (
                    <div key={type} className="flex items-center text-xs gap-1">
                      <span className={`w-2 h-2 rounded-full ${color.bar}`} />
                      <span className={color.text}>{type}</span>
                      <span className="text-gray-600 ml-auto">{count}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        {/* Filter by adaptation type */}
        {selectedDataset && (
          <div className="p-3 border-t border-gray-800">
            <div className="text-xs text-gray-500 mb-1">Filter by Adaptation</div>
            <select
              value={state.filterAdaptation}
              onChange={(e) => store.setFilterAdaptation(e.target.value)}
              className="w-full bg-gray-800 text-sm px-2 py-1 rounded border border-gray-700 text-gray-200"
            >
              <option value="">All</option>
              {adaptationTypes.map((t) => (
                <option key={t} value={t}>
                  {t}
                </option>
              ))}
            </select>
          </div>
        )}
      </div>

      {/* Main content */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {state.error && (
          <div className="bg-red-900/50 border-b border-red-700 px-4 py-2 text-sm text-red-200 flex justify-between items-center">
            <span>{state.error}</span>
            <button
              onClick={() => store.setError(null)}
              className="text-red-400 hover:text-red-200 ml-4"
            >
              dismiss
            </button>
          </div>
        )}

        {state.loading && (
          <div className="bg-rose-900/30 border-b border-rose-800 px-4 py-1.5 text-xs text-rose-300">
            Loading...
          </div>
        )}

        {/* Timeline view */}
        {state.viewMode === "timeline" && selectedDataset && (
          <div className="flex-1 flex flex-col overflow-hidden">
            {/* Bar chart */}
            <div className="border-b border-gray-800 p-4 shrink-0">
              <div className="text-sm text-gray-400 mb-2">
                Score Timeline ({filteredIterations.length} iterations)
              </div>
              <div className="flex items-end gap-px h-32 overflow-x-auto">
                {filteredIterations.map((it) => {
                  const height = Math.max((Math.abs(it.score) / maxScore) * 100, 2);
                  const color = getAdaptationColor(it.adaptation_type);
                  return (
                    <div
                      key={it.index}
                      className="flex flex-col items-center justify-end flex-shrink-0 cursor-pointer group"
                      style={{ minWidth: Math.max(4, Math.min(20, 800 / filteredIterations.length)) }}
                      onClick={() => store.selectIteration(selectedDataset.id, it.index)}
                      title={`iter ${it.iteration} | score ${it.score.toFixed(4)} | ${it.adaptation_type}`}
                    >
                      <div
                        className={`w-full rounded-t ${color.bar} group-hover:opacity-80 transition-opacity`}
                        style={{ height: `${height}%` }}
                      />
                    </div>
                  );
                })}
              </div>
              {/* Legend */}
              <div className="flex gap-4 mt-2">
                {Object.entries(ADAPTATION_COLORS).map(([type, color]) => (
                  <div key={type} className="flex items-center gap-1 text-xs">
                    <span className={`w-2 h-2 rounded-full ${color.bar}`} />
                    <span className={color.text}>{type}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Iteration table */}
            <div className="flex-1 overflow-auto">
              <table className="w-full text-sm">
                <thead className="sticky top-0 bg-gray-900 border-b border-gray-800">
                  <tr>
                    {(
                      [
                        ["iteration", "Iter"],
                        ["island_id", "Island"],
                        ["score", "Score"],
                        ["best_score", "Best"],
                        ["delta", "Delta"],
                        ["adaptation_type", "Adaptation"],
                      ] as [SortKey, string][]
                    ).map(([key, label]) => (
                      <th
                        key={key}
                        onClick={() => handleSort(key)}
                        className="px-3 py-2 text-left text-gray-400 font-medium cursor-pointer hover:text-gray-200 select-none"
                      >
                        {label}
                        {sortIndicator(key)}
                      </th>
                    ))}
                    <th className="px-3 py-2 text-left text-gray-400 font-medium">Valid</th>
                    <th className="px-3 py-2 text-left text-gray-400 font-medium">Task</th>
                  </tr>
                </thead>
                <tbody>
                  {sortedIterations.map((it) => {
                    const color = getAdaptationColor(it.adaptation_type);
                    return (
                      <tr
                        key={it.index}
                        onClick={() => store.selectIteration(selectedDataset.id, it.index)}
                        className="border-b border-gray-800/50 hover:bg-gray-800/50 cursor-pointer"
                      >
                        <td className="px-3 py-1.5 text-gray-300">{it.iteration}</td>
                        <td className="px-3 py-1.5 text-gray-300">{it.island_id}</td>
                        <td className="px-3 py-1.5 text-gray-200 font-mono">
                          {it.score.toFixed(4)}
                        </td>
                        <td className="px-3 py-1.5 text-gray-200 font-mono">
                          {it.best_score.toFixed(4)}
                        </td>
                        <td
                          className={`px-3 py-1.5 font-mono ${
                            it.delta > 0
                              ? "text-green-400"
                              : it.delta < 0
                              ? "text-red-400"
                              : "text-gray-500"
                          }`}
                        >
                          {it.delta > 0 ? "+" : ""}
                          {it.delta.toFixed(4)}
                        </td>
                        <td className="px-3 py-1.5">
                          <span
                            className={`px-1.5 py-0.5 rounded text-xs ${color.bg} ${color.text}`}
                          >
                            {it.adaptation_type}
                          </span>
                        </td>
                        <td className="px-3 py-1.5">
                          {it.is_valid ? (
                            <span className="text-green-400 text-xs">yes</span>
                          ) : (
                            <span className="text-red-400 text-xs">no</span>
                          )}
                        </td>
                        <td className="px-3 py-1.5 text-gray-500 text-xs truncate max-w-[150px]">
                          {it.task_id}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Detail view */}
        {state.viewMode === "detail" && state.iterationDetail && (
          <div className="flex-1 flex flex-col overflow-hidden">
            {/* Detail header */}
            <div className="border-b border-gray-800 px-4 py-2 flex items-center gap-4 shrink-0">
              <button
                onClick={() => store.backToTimeline()}
                className="text-rose-400 hover:text-rose-300 text-sm"
              >
                &larr; Back to timeline
              </button>
              <div className="text-sm text-gray-300">
                Iteration {state.iterationDetail.iteration} | Island{" "}
                {state.iterationDetail.island_id}
              </div>
              <div className="flex items-center gap-2 ml-auto">
                <span
                  className={`px-2 py-0.5 rounded text-xs ${
                    getAdaptationColor(state.iterationDetail.adaptation_type).bg
                  } ${getAdaptationColor(state.iterationDetail.adaptation_type).text}`}
                >
                  {state.iterationDetail.adaptation_type}
                </span>
                <span className="text-gray-400 text-sm font-mono">
                  score: {state.iterationDetail.score.toFixed(4)}
                </span>
                <span
                  className={`text-sm font-mono ${
                    state.iterationDetail.delta > 0
                      ? "text-green-400"
                      : state.iterationDetail.delta < 0
                      ? "text-red-400"
                      : "text-gray-500"
                  }`}
                >
                  ({state.iterationDetail.delta > 0 ? "+" : ""}
                  {state.iterationDetail.delta.toFixed(4)})
                </span>
                {state.iterationDetail.is_valid ? (
                  <span className="text-green-400 text-xs border border-green-800 rounded px-1">
                    valid
                  </span>
                ) : (
                  <span className="text-red-400 text-xs border border-red-800 rounded px-1">
                    invalid
                  </span>
                )}
              </div>
            </div>

            {/* Detail grid */}
            <div className="flex-1 overflow-auto p-4">
              <div className="grid grid-cols-2 gap-4 h-full">
                {/* Meta info */}
                <div className="col-span-2 grid grid-cols-4 gap-3">
                  <div className="bg-gray-900 rounded border border-gray-800 p-3">
                    <div className="text-xs text-gray-500 mb-1">Task ID</div>
                    <div className="text-sm text-gray-200 break-all">
                      {state.iterationDetail.task_id || "-"}
                    </div>
                  </div>
                  <div className="bg-gray-900 rounded border border-gray-800 p-3">
                    <div className="text-xs text-gray-500 mb-1">Exploration Intensity</div>
                    <div className="text-sm text-gray-200 font-mono">
                      {state.iterationDetail.exploration_intensity.toFixed(4)}
                    </div>
                  </div>
                  <div className="bg-gray-900 rounded border border-gray-800 p-3">
                    <div className="text-xs text-gray-500 mb-1">Meta-Guidance Tactic</div>
                    <div className="text-sm text-gray-200">
                      {state.iterationDetail.meta_guidance_tactic || "-"}
                    </div>
                  </div>
                  <div className="bg-gray-900 rounded border border-gray-800 p-3">
                    <div className="text-xs text-gray-500 mb-1">Tactic Approach</div>
                    <div className="text-sm text-gray-200">
                      {state.iterationDetail.tactic_approach_type || "-"}
                    </div>
                  </div>
                </div>

                {/* Prompt */}
                <div className="bg-gray-900 rounded border border-gray-800 flex flex-col overflow-hidden">
                  <div className="px-3 py-2 border-b border-gray-800 text-xs text-rose-400 font-medium shrink-0">
                    Prompt
                  </div>
                  <pre className="flex-1 overflow-auto p-3 text-xs text-gray-300 whitespace-pre-wrap font-mono">
                    {state.iterationDetail.prompt_text || "(empty)"}
                  </pre>
                </div>

                {/* Reasoning trace */}
                <div className="bg-gray-900 rounded border border-gray-800 flex flex-col overflow-hidden">
                  <div className="px-3 py-2 border-b border-gray-800 text-xs text-rose-400 font-medium shrink-0">
                    Reasoning Trace
                  </div>
                  <pre className="flex-1 overflow-auto p-3 text-xs text-gray-300 whitespace-pre-wrap font-mono">
                    {state.iterationDetail.reasoning_trace || "(empty)"}
                  </pre>
                </div>

                {/* Generated code */}
                <div className="col-span-2 bg-gray-900 rounded border border-gray-800 flex flex-col overflow-hidden max-h-96">
                  <div className="px-3 py-2 border-b border-gray-800 text-xs text-rose-400 font-medium shrink-0">
                    Generated Code
                  </div>
                  <pre className="flex-1 overflow-auto p-3 text-xs text-gray-300 whitespace-pre-wrap font-mono">
                    {state.iterationDetail.program_code || "(empty)"}
                  </pre>
                </div>
              </div>
            </div>

            {/* Navigation */}
            {selectedDataset && (
              <div className="border-t border-gray-800 px-4 py-2 flex items-center justify-between shrink-0">
                <button
                  onClick={() => {
                    const idx = state.iterationDetail!.index;
                    if (idx > 0) store.selectIteration(selectedDataset.id, idx - 1);
                  }}
                  disabled={state.iterationDetail.index <= 0}
                  className="text-sm text-rose-400 hover:text-rose-300 disabled:opacity-30 disabled:cursor-default"
                >
                  &larr; Previous
                </button>
                <span className="text-xs text-gray-500">
                  {state.iterationDetail.index + 1} / {selectedDataset.n_iterations}
                </span>
                <button
                  onClick={() => {
                    const idx = state.iterationDetail!.index;
                    if (idx < selectedDataset.n_iterations - 1)
                      store.selectIteration(selectedDataset.id, idx + 1);
                  }}
                  disabled={
                    state.iterationDetail.index >= selectedDataset.n_iterations - 1
                  }
                  className="text-sm text-rose-400 hover:text-rose-300 disabled:opacity-30 disabled:cursor-default"
                >
                  Next &rarr;
                </button>
              </div>
            )}
          </div>
        )}

        {/* Empty state */}
        {state.datasets.length === 0 && state.viewMode === "timeline" && (
          <div className="flex-1 flex items-center justify-center text-gray-500">
            <div className="text-center">
              <div className="text-lg mb-2">No datasets loaded</div>
              <div className="text-sm">
                Load a HuggingFace repo from the sidebar or select a preset
              </div>
            </div>
          </div>
        )}

        {state.datasets.length > 0 && !selectedDataset && state.viewMode === "timeline" && (
          <div className="flex-1 flex items-center justify-center text-gray-500">
            <div className="text-center">
              <div className="text-lg mb-2">Select a dataset</div>
              <div className="text-sm">Click a dataset in the sidebar to view its iterations</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}