File size: 27,313 Bytes
46d70d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import { useEffect, useMemo, useState } from "react";
import {
  AlertTriangle,
  ArrowRight,
  CheckCircle2,
  ChevronDown,
  ChevronRight,
  Download,
  Loader2,
  ShieldCheck,
  Sparkles,
  Wrench,
} from "lucide-react";
import type { FixStackCandidate, FixStackResponse, SearchRequest } from "../../types/ostra";
import { HelpInfo } from "../common/HelpInfo";

interface FixStackPanelProps {
  labeledCount: number;
  fixStack: FixStackResponse | null;
  compiling: boolean;
  strictZeroReg: boolean;
  onToggleStrictZeroReg: (v: boolean) => void;
  onBuildPlan: () => void;
  onApplyPlan: (patch: Partial<SearchRequest>, label: string) => void;
  onOpenExport: () => void;
  onOpenQuickLabeler: () => void;
}

const VERDICT_META: Record<
  FixStackResponse["verdict"],
  { tag: string; boxCls: string; tagCls: string }
> = {
  verified_ship: {
    tag: "Ready to Ship",
    boxCls: "bg-emerald-50 border-emerald-800 text-emerald-950",
    tagCls: "bg-emerald-700 text-white",
  },
  cautious_ship: {
    tag: "Promising — Verify on More Queries",
    boxCls: "bg-amber-50 border-amber-700 text-amber-950",
    tagCls: "bg-amber-700 text-white",
  },
  overfit_warning: {
    tag: "Likely Overfit on Small Suite",
    boxCls: "bg-red-50 border-red-700 text-red-950",
    tagCls: "bg-red-700 text-white",
  },
  already_optimal: {
    tag: "Already Strong",
    boxCls: "bg-sky-50 border-sky-700 text-sky-950",
    tagCls: "bg-sky-700 text-white",
  },
  needs_labels: {
    tag: "Needs Labels",
    boxCls: "bg-amber-50 border-amber-700 text-amber-950",
    tagCls: "bg-amber-700 text-white",
  },
};

export function FixStackPanel({
  labeledCount,
  fixStack,
  compiling,
  strictZeroReg,
  onToggleStrictZeroReg,
  onBuildPlan,
  onApplyPlan,
  onOpenExport,
  onOpenQuickLabeler,
}: FixStackPanelProps) {
  const [selectedStackId, setSelectedStackId] = useState<string>("recommended");
  const [showQueryDeltas, setShowQueryDeltas] = useState(false);

  useEffect(() => {
    if (fixStack) {
      setSelectedStackId(fixStack.recommended_stack_id || "recommended");
      setShowQueryDeltas(false);
    }
  }, [fixStack]);

  const activeCandidate: FixStackCandidate | null = useMemo(() => {
    if (!fixStack || fixStack.pareto_stacks.length === 0) return null;
    return (
      fixStack.pareto_stacks.find((s) => s.id === selectedStackId) ??
      fixStack.pareto_stacks.find((s) => s.is_recommended) ??
      fixStack.pareto_stacks[0]
    );
  }, [fixStack, selectedStackId]);

  const changedDeltas = useMemo(
    () => (fixStack?.query_deltas ?? []).filter((d) => d.status !== "unchanged"),
    [fixStack]
  );

  // Needs-Labels Empty State
  if (labeledCount === 0) {
    return (
      <div className="paper-card p-5 space-y-3">
        <div className="flex items-start gap-3">
          <div className="w-8 h-8 border-[1.5px] border-[#0f172a] bg-amber-50 flex items-center justify-center shrink-0">
            <Wrench className="w-4 h-4 text-amber-800" />
          </div>
          <div className="space-y-1">
            <h4 className="font-mono font-bold text-sm text-[#0f172a]">
              Label at least 4 queries to build a cross-checked Fix Plan
            </h4>
            <p className="text-[11px] text-[#475569] leading-relaxed">
              Fix Plan tests synonyms, hub cleanup, hybrid routing, and phrase proximity together—and verifies them across held-out splits so you never ship a lucky overfit.
            </p>
          </div>
        </div>
        <div>
          <button
            type="button"
            onClick={onOpenQuickLabeler}
            className="paper-btn-ink inline-flex items-center gap-1.5 px-3 py-1.5 font-mono text-[11px] font-semibold cursor-pointer"
          >
            <span>Open Quick Labeler</span>
            <ArrowRight className="w-3.5 h-3.5 text-sky-400" />
          </button>
        </div>
      </div>
    );
  }

  const selectedLevers = (fixStack?.levers ?? []).filter((l) => l.selected);
  const droppedLevers = (fixStack?.levers ?? []).filter((l) => !l.selected);
  const maxContrib = Math.max(
    ...selectedLevers.map((l) => Math.abs(l.shapley_mrr)),
    0.01
  );

  const previewHit = activeCandidate ? activeCandidate.hit_at_k : fixStack?.recommended_hit_at_k ?? 0;
  const previewMrr = activeCandidate ? activeCandidate.mrr : fixStack?.recommended_mrr ?? 0;
  const previewFixed = activeCandidate ? activeCandidate.fixed_count : fixStack?.recommended_fixed_count ?? 0;
  const previewReg = activeCandidate ? activeCandidate.regressed_count : fixStack?.recommended_regressed_count ?? 0;
  const hitDeltaPp = fixStack ? (previewHit - fixStack.baseline_hit_at_k) * 100 : 0;
  const mrrDelta = fixStack ? previewMrr - fixStack.baseline_mrr : 0;

  return (
    <div className="space-y-3">
      {/* Action Header Strip */}
      <div className="paper-card p-3 flex flex-wrap items-center justify-between gap-2.5">
        <div className="space-y-0.5">
          <div className="font-mono font-bold text-xs text-[#0f172a] flex items-center gap-1.5">
            <Sparkles className="w-3.5 h-3.5 text-emerald-700" />
            <span>Guided Fix Plan</span>
            {fixStack && (
              <span className="text-[10px] font-normal text-[#64748b] tabular-nums">
                · {fixStack.labeled_count} labeled · {fixStack.elapsed_ms.toFixed(0)}ms
              </span>
            )}
          </div>
          <p className="text-[11px] text-[#475569]">
            Tests all retrieval fixes together, detects overlaps &amp; conflicts, and verifies gains on held-out splits.
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <label className="inline-flex items-center gap-1.5 font-mono text-[11px] text-[#0f172a] cursor-pointer select-none">
            <input
              type="checkbox"
              checked={strictZeroReg}
              onChange={(e) => onToggleStrictZeroReg(e.target.checked)}
              className="accent-emerald-700"
            />
            <span>Zero-Regression Guard</span>
            <HelpInfo topic="zeroRegressionGuard" />
          </label>

          <button
            type="button"
            disabled={compiling}
            onClick={onBuildPlan}
            className="paper-btn-ink inline-flex items-center gap-1.5 px-3 py-1.5 font-mono text-[11px] font-semibold cursor-pointer disabled:opacity-50"
          >
            {compiling ? (
              <Loader2 className="w-3.5 h-3.5 animate-spin text-sky-400" />
            ) : (
              <Wrench className="w-3.5 h-3.5 text-sky-400" />
            )}
            <span>{compiling ? "Building Plan…" : "Build Guided Fix Plan"}</span>
          </button>
        </div>
      </div>

      {/* Prompt state before first run */}
      {!fixStack && !compiling && (
        <div className="paper-box p-4 bg-white text-[11px] text-[#475569] flex items-center justify-between gap-3">
          <span>
            Ready to evaluate <strong className="text-[#0f172a] font-mono">{labeledCount}</strong> labeled{" "}
            {labeledCount === 1 ? "query" : "queries"} across vocabulary rules, hub &amp; cone geometry, corpus hygiene, hybrid routing, and phrase proximity.
          </span>
          {labeledCount < 4 && (
            <button
              type="button"
              onClick={onOpenQuickLabeler}
              className="paper-btn px-2.5 py-1 font-mono text-[10px] shrink-0 cursor-pointer"
            >
              Label {4 - labeledCount} more for Held-Out Check →
            </button>
          )}
        </div>
      )}

      {/* Results View */}
      {fixStack && (
        <div className="space-y-3">
          {/* 1-Line Verdict Banner */}
          <div
            className={`border-[1.5px] px-3 py-2 flex flex-wrap items-center justify-between gap-2 shadow-[2px_2px_0_rgba(15,23,42,0.12)] ${VERDICT_META[fixStack.verdict].boxCls}`}
          >
            <div className="flex flex-wrap items-center gap-2">
              <span
                className={`px-2 py-0.5 font-mono text-[10px] font-bold uppercase tracking-wide ${VERDICT_META[fixStack.verdict].tagCls}`}
              >
                {VERDICT_META[fixStack.verdict].tag}
              </span>
              <span className="text-xs font-medium">{fixStack.verdict_headline}</span>
            </div>
            {!fixStack.cv_evaluated && (
              <button
                type="button"
                onClick={onOpenQuickLabeler}
                className="font-mono text-[10px] underline font-semibold cursor-pointer"
              >
                Label more queries →
              </button>
            )}
          </div>

          {/* 4-Tile Metric Delta Row */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-2 font-mono">
            <div className="paper-box bg-white p-2.5">
              <div className="text-[9px] uppercase tracking-wider text-[#64748b]">
                HIT@{fixStack.top_k}
              </div>
              <div className="mt-0.5 text-sm font-bold text-[#0f172a] tabular-nums">
                {(fixStack.baseline_hit_at_k * 100).toFixed(0)}% → {(previewHit * 100).toFixed(0)}%
              </div>
              <div
                className={`text-[10px] font-semibold tabular-nums ${
                  hitDeltaPp > 0.05
                    ? "text-emerald-700"
                    : hitDeltaPp < -0.05
                    ? "text-red-700"
                    : "text-[#64748b]"
                }`}
              >
                {hitDeltaPp >= 0 ? "+" : ""}
                {hitDeltaPp.toFixed(1)}pp
              </div>
            </div>

            <div className="paper-box bg-white p-2.5">
              <div className="text-[9px] uppercase tracking-wider text-[#64748b]">MRR</div>
              <div className="mt-0.5 text-sm font-bold text-[#0f172a] tabular-nums">
                {fixStack.baseline_mrr.toFixed(3)} → {previewMrr.toFixed(3)}
              </div>
              <div
                className={`text-[10px] font-semibold tabular-nums ${
                  mrrDelta > 0.001
                    ? "text-emerald-700"
                    : mrrDelta < -0.001
                    ? "text-red-700"
                    : "text-[#64748b]"
                }`}
              >
                {mrrDelta >= 0 ? "+" : ""}
                {mrrDelta.toFixed(3)}
              </div>
            </div>

            <div className="paper-box bg-white p-2.5">
              <div className="text-[9px] uppercase tracking-wider text-[#64748b]">QUERIES</div>
              <div className="mt-0.5 text-sm font-bold tabular-nums flex items-center gap-2">
                <span className="text-emerald-700">+{previewFixed} fixed</span>
                <span className={previewReg > 0 ? "text-red-700" : "text-[#475569]"}>
                  −{previewReg} regressed
                </span>
              </div>
              <div className="text-[10px] text-[#64748b] tabular-nums">
                {fixStack.labeled_count} labeled evaluated
              </div>
            </div>

            <div className="paper-box bg-white p-2.5">
              <div className="text-[9px] uppercase tracking-wider text-[#64748b]">
                HELD-OUT CHECK
              </div>
              {fixStack.cv_evaluated &&
              fixStack.cv_mrr_before !== null &&
              fixStack.cv_mrr_after !== null ? (
                <>
                  <div className="mt-0.5 text-sm font-bold text-[#0f172a] tabular-nums">
                    {fixStack.cv_mrr_before.toFixed(2)} → {fixStack.cv_mrr_after.toFixed(2)}
                  </div>
                  <div className="text-[10px] text-[#475569] tabular-nums truncate">
                    {fixStack.cv_mode === "loocv"
                      ? `${fixStack.cv_folds}-split LOO`
                      : `${fixStack.cv_folds}-fold`}
                    {fixStack.cv_mrr_ci_low !== null && fixStack.cv_mrr_ci_high !== null
                      ? ` · 95% CI [${fixStack.cv_mrr_ci_low >= 0 ? "+" : ""}${fixStack.cv_mrr_ci_low.toFixed(2)}, ${fixStack.cv_mrr_ci_high >= 0 ? "+" : ""}${fixStack.cv_mrr_ci_high.toFixed(2)}]`
                      : ""}
                  </div>
                </>
              ) : (
                <>
                  <div className="mt-0.5 text-xs font-bold text-amber-800">
                    Skipped (&lt;4 labels)
                  </div>
                  <div className="text-[10px] text-[#64748b]">
                    Add 4+ labels to verify
                  </div>
                </>
              )}
            </div>
          </div>

          {/* Plan Selector (1–3 distinct radio cards) */}
          {fixStack.pareto_stacks.length > 0 && (
            <div className="space-y-1.5">
              <div className="font-mono text-[10px] uppercase tracking-wider font-bold text-[#475569]">
                Choose Plan Option
              </div>
              <div
                className={`grid gap-2 ${
                  fixStack.pareto_stacks.length === 1
                    ? "grid-cols-1"
                    : fixStack.pareto_stacks.length === 2
                    ? "grid-cols-1 sm:grid-cols-2"
                    : "grid-cols-1 sm:grid-cols-3"
                }`}
              >
                {fixStack.pareto_stacks.map((opt) => {
                  const isActive = activeCandidate?.id === opt.id;
                  return (
                    <button
                      key={opt.id}
                      type="button"
                      onClick={() => setSelectedStackId(opt.id)}
                      className={`text-left p-2.5 border-[1.5px] transition-colors cursor-pointer ${
                        isActive
                          ? "bg-white border-[#0f172a] shadow-[3px_3px_0_rgba(15,23,42,0.16)]"
                          : "bg-[#f8fafc] border-[#cbd5e1] hover:border-[#0f172a]"
                      }`}
                    >
                      <div className="flex items-center justify-between gap-1.5">
                        <span className="font-mono text-[11px] font-bold text-[#0f172a]">
                          {opt.label}
                        </span>
                        {opt.is_recommended && (
                          <span className="px-1.5 py-0.5 font-mono text-[9px] font-bold bg-[#0f172a] text-white uppercase">
                            Recommended
                          </span>
                        )}
                      </div>
                      <div className="mt-1 font-mono text-[11px] text-[#334155] tabular-nums flex items-center gap-2">
                        <span>MRR {opt.mrr.toFixed(3)}</span>
                        <span>·</span>
                        <span>Hit@{fixStack.top_k} {(opt.hit_at_k * 100).toFixed(0)}%</span>
                      </div>
                      <div className="mt-0.5 font-mono text-[10px] text-[#64748b] tabular-nums">
                        {opt.lever_ids.length} {opt.lever_ids.length === 1 ? "fix" : "fixes"} ·{" "}
                        <span className="text-emerald-700">+{opt.fixed_count}</span> /{" "}
                        <span className={opt.regressed_count > 0 ? "text-red-700" : ""}>
                          −{opt.regressed_count}
                        </span>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* What Each Fix Contributes */}
          {fixStack.levers.length > 0 && (
            <div className="paper-card p-3 space-y-2.5">
              <div className="flex items-center justify-between">
                <h4 className="font-mono text-[11px] font-bold uppercase tracking-wider text-[#0f172a]">
                  What Each Fix Contributes
                </h4>
                <span className="font-mono text-[10px] text-[#64748b]">
                  Exact share of total MRR gain
                </span>
              </div>

              {selectedLevers.length === 0 ? (
                <div className="text-[11px] text-[#475569] bg-[#f8fafc] border border-[#cbd5e1] px-2.5 py-2">
                  No retrieval changes were needed — your current configuration already scores best under the active guardrails.
                </div>
              ) : (
                <div className="space-y-2">
                  {selectedLevers.map((lv) => {
                    const widthPct = Math.min(
                      100,
                      Math.max(4, (Math.abs(lv.shapley_mrr) / maxContrib) * 100)
                    );
                    const splitTone =
                      lv.fold_total_count === 0
                        ? "bg-[#f1f4f8] border-[#cbd5e1] text-[#64748b]"
                        : lv.fold_selection_rate >= 0.75
                        ? "bg-emerald-50 border-emerald-700 text-emerald-900"
                        : "bg-amber-50 border-amber-700 text-amber-900";
                    return (
                      <div
                        key={lv.lever_id}
                        className="border border-[#cbd5e1] bg-[#f8fafc] px-2.5 py-2 space-y-1.5"
                      >
                        <div className="flex flex-wrap items-center justify-between gap-2">
                          <div className="flex items-center gap-1.5 min-w-0">
                            <CheckCircle2 className="w-3.5 h-3.5 text-emerald-700 shrink-0" />
                            <span className="font-mono text-[11px] font-bold text-[#0f172a]">
                              {lv.label}
                            </span>
                            <span className="text-[10px] text-[#475569] truncate">
                              · {lv.summary}
                            </span>
                          </div>
                          <div className="flex items-center gap-2 font-mono text-[10px] tabular-nums shrink-0">
                            <span
                              className={
                                lv.shapley_mrr >= 0
                                  ? "font-bold text-emerald-700"
                                  : "font-bold text-red-700"
                              }
                            >
                              {lv.shapley_mrr >= 0 ? "+" : ""}
                              {lv.shapley_mrr.toFixed(3)} MRR
                            </span>
                            <span className="text-[#475569]">
                              ({lv.shapley_hit >= 0 ? "+" : ""}
                              {(lv.shapley_hit * 100).toFixed(0)}pp)
                            </span>
                            {lv.fold_total_count > 0 && (
                              <span className={`px-1.5 py-0.5 border text-[9px] font-semibold ${splitTone}`}>
                                {lv.fold_selected_count}/{lv.fold_total_count} splits
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="h-1.5 bg-white border border-[#cbd5e1] overflow-hidden">
                          <div
                            className={lv.shapley_mrr >= 0 ? "h-full bg-emerald-600" : "h-full bg-red-600"}
                            style={{ width: `${widthPct}%` }}
                          />
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Dropped levers muted below */}
              {droppedLevers.length > 0 && (
                <div className="pt-1.5 border-t border-[#e2e8f0] space-y-1">
                  <div className="font-mono text-[9px] uppercase tracking-wider text-[#64748b]">
                    Tested &amp; Skipped
                  </div>
                  {droppedLevers.map((lv) => (
                    <div
                      key={lv.lever_id}
                      className="flex flex-wrap items-center justify-between gap-2 px-2 py-1 bg-white border border-[#e2e8f0] text-[10px] text-[#64748b]"
                    >
                      <span className="font-mono">
                        <strong className="text-[#475569]">{lv.label}</strong> ({lv.summary})
                      </span>
                      <span className="italic">
                        Skipped: {lv.prune_reason ?? "Gain too small for added complexity"}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Conditional Overlap / Combo Callouts (only rendered if interactions exist) */}
          {fixStack.interactions.length > 0 && (
            <div className="paper-card p-3 space-y-2">
              <div className="font-mono text-[11px] font-bold uppercase tracking-wider text-[#0f172a]">
                Fix Interactions Detected
              </div>
              <div className="space-y-1.5">
                {fixStack.interactions.map((inter) => {
                  const isCombo = inter.kind === "synergy";
                  return (
                    <div
                      key={`${inter.lever_a}_${inter.lever_b}`}
                      className={`border px-2.5 py-1.5 flex flex-wrap items-start gap-2 text-[11px] ${
                        isCombo
                          ? "bg-emerald-50/70 border-emerald-700 text-emerald-950"
                          : "bg-amber-50/70 border-amber-700 text-amber-950"
                      }`}
                    >
                      <span
                        className={`px-1.5 py-0.5 font-mono text-[9px] font-bold uppercase shrink-0 ${
                          isCombo
                            ? "bg-emerald-700 text-white"
                            : "bg-amber-700 text-white"
                        }`}
                      >
                        {isCombo ? "Strong Combo" : "Overlap / Conflict"}
                      </span>
                      <span className="leading-snug flex-1">{inter.plain_explanation}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Optional Calibration Note */}
          {fixStack.calibration_note?.applied && (
            <div className="border-[1.5px] border-sky-800 bg-sky-50 px-3 py-2 flex items-center gap-2 text-[11px] text-sky-950">
              <ShieldCheck className="w-4 h-4 text-sky-700 shrink-0" />
              <span>{fixStack.calibration_note.note}</span>
            </div>
          )}

          {/* Collapsed-by-Default Per-Query Impact Accordion */}
          {fixStack.query_deltas.length > 0 && (
            <div className="border-[1.5px] border-[#0f172a] bg-white">
              <button
                type="button"
                onClick={() => setShowQueryDeltas((v) => !v)}
                className="w-full px-3 py-2 flex items-center justify-between font-mono text-[11px] font-semibold text-[#0f172a] hover:bg-[#f8fafc] cursor-pointer"
              >
                <span className="inline-flex items-center gap-1.5">
                  {showQueryDeltas ? (
                    <ChevronDown className="w-3.5 h-3.5" />
                  ) : (
                    <ChevronRight className="w-3.5 h-3.5" />
                  )}
                  <span>
                    Per-Query Impact ({changedDeltas.length} changed of {fixStack.query_deltas.length})
                  </span>
                </span>
                <span className="text-[10px] text-[#64748b]">
                  {showQueryDeltas ? "Hide" : "Show"}
                </span>
              </button>

              {showQueryDeltas && (
                <div className="border-t border-[#cbd5e1] divide-y divide-[#e2e8f0] max-h-60 overflow-y-auto">
                  {fixStack.query_deltas.map((qd) => (
                    <div
                      key={qd.question_id}
                      className="px-3 py-1.5 flex items-center justify-between gap-2 text-[11px]"
                    >
                      <span className="truncate text-[#0f172a] flex-1">{qd.query}</span>
                      <div className="flex items-center gap-2 font-mono text-[10px] tabular-nums shrink-0">
                        <span className="text-[#475569]">
                          {qd.before_rank ? `#${qd.before_rank}` : "miss"} →{" "}
                          {qd.after_rank ? `#${qd.after_rank}` : "miss"}
                        </span>
                        <span
                          className={`px-1.5 py-0.5 text-[9px] font-bold uppercase ${
                            qd.status === "fixed"
                              ? "bg-emerald-100 text-emerald-900"
                              : qd.status === "improved"
                              ? "bg-sky-100 text-sky-900"
                              : qd.status === "regressed"
                              ? "bg-red-100 text-red-900"
                              : "bg-[#f1f4f8] text-[#64748b]"
                          }`}
                        >
                          {qd.status}
                        </span>
                        {qd.decisive_lever && (
                          <span className="text-[#64748b] hidden md:inline">
                            via {qd.decisive_lever}
                          </span>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Primary Bottom Actions */}
          <div className="flex flex-wrap items-center justify-between gap-2 pt-1">
            <div className="flex items-center gap-2">
              <button
                type="button"
                disabled={!activeCandidate || activeCandidate.lever_ids.length === 0}
                onClick={() => {
                  if (!activeCandidate) return;
                  onApplyPlan(activeCandidate.patch, activeCandidate.label);
                }}
                className="paper-btn-ink inline-flex items-center gap-1.5 px-3.5 py-1.5 font-mono text-[11px] font-semibold cursor-pointer disabled:opacity-45"
              >
                <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400" />
                <span>
                  Apply {activeCandidate ? activeCandidate.label : "Selected Plan"}
                </span>
              </button>

              <button
                type="button"
                onClick={onOpenExport}
                className="paper-btn inline-flex items-center gap-1.5 px-3 py-1.5 font-mono text-[11px] font-semibold cursor-pointer"
              >
                <Download className="w-3.5 h-3.5 text-[#0f172a]" />
                <span>Export Unified Pipeline</span>
              </button>
            </div>

            {fixStack.verdict === "overfit_warning" && (
              <div className="inline-flex items-center gap-1 text-[10px] font-mono text-red-700">
                <AlertTriangle className="w-3.5 h-3.5" />
                <span>Single-step Undo available after apply</span>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}