Catalyst / admin/Bid-Sentinel 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Bid-Sentinel

public

Bid Scrape and Tracking Application with AI Capability

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Bid-Sentinel / bid-sentinel-v2 / frontend / src / pages / Dashboard.jsx 36113 B · main
  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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
import { Fragment, useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  addTuneOut,
  bulkDeleteTenders,
  createTender,
  deleteTender,
  downloadManagementSummary,
  emailReport,
  fetchAiConfig,
  fetchEmailStatus,
  fetchManagementSummaryBlob,
  fetchPortals,
  fetchTenders,
  triggerScrape,
  undoDelete,
  updateTender,
} from "../api/client";
import { useAuth } from "../context/AuthContext.jsx";
import BidStatusSelect from "../components/BidStatusSelect.jsx";
import OutcomeSelect from "../components/OutcomeSelect.jsx";
import AnalyticsPanel from "../components/AnalyticsPanel.jsx";
import CommentsSection from "../components/CommentsSection.jsx";
import ThemeToggle from "../components/ThemeToggle.jsx";
import { buildCsvBlob, buildPdfBlob, exportCsv, exportPdf } from "../utils/export";
import { daysUntil, formatDate, formatValue } from "../utils/format";
import logo from "../assets/bid-sentinel-logo.png";

const STATUS_FILTERS = ["All", "Pending", "Bid", "No Bid"];
const SORT_OPTIONS = [
  { value: "published_date", label: "Published date" },
  { value: "closing_date", label: "Closing date" },
  { value: "value_amount", label: "Value" },
  { value: "fit_score", label: "Fit %" },
  { value: "title", label: "Title" },
];

export default function Dashboard() {
  const { user, logout } = useAuth();
  const isAdmin = user?.role === "admin";
  const canManagementReport = isAdmin || user?.role === "analyst";

  const [tenders, setTenders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("All");
  const [sourceFilter, setSourceFilter] = useState("All");
  const [sortBy, setSortBy] = useState("published_date");
  const [order, setOrder] = useState("desc");
  const [sources, setSources] = useState([]);
  const [scraping, setScraping] = useState(false);
  const [notice, setNotice] = useState("");
  const [hideDisregarded, setHideDisregarded] = useState(true);
  const [expanded, setExpanded] = useState(() => new Set());
  const [showAdd, setShowAdd] = useState(false);
  const [editTarget, setEditTarget] = useState(null);
  const [selected, setSelected] = useState(() => new Set());
  const [undoBatch, setUndoBatch] = useState(null);
  const [aiActive, setAiActive] = useState(false);
  const [emailAvailable, setEmailAvailable] = useState(false);

  // AI Assistant is "active" only when enabled AND an API key is configured.
  useEffect(() => {
    fetchAiConfig()
      .then((cfg) => setAiActive(Boolean(cfg.enabled && cfg.available)))
      .catch(() => setAiActive(false));
    fetchEmailStatus()
      .then((s) => setEmailAvailable(Boolean(s.available)))
      .catch(() => setEmailAvailable(false));
  }, []);

  async function emailFile(blob, filename, subject) {
    setNotice("");
    try {
      const r = await emailReport(blob, filename, subject);
      setNotice(`Emailed to ${r.to}.`);
    } catch (err) {
      setNotice(err.response?.data?.detail || "Could not send email.");
    }
  }

  function toggleExpand(id) {
    setExpanded((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }

  // Portal names populate the Source filter dropdown.
  useEffect(() => {
    fetchPortals()
      .then((ps) => setSources(ps.map((p) => p.name)))
      .catch(() => {});
  }, []);

  const load = useCallback(async () => {
    setLoading(true);
    setError("");
    setSelected(new Set()); // reset selection when the filtered list changes
    try {
      const params = { sort_by: sortBy, order };
      if (statusFilter !== "All") params.bid_status = statusFilter;
      if (sourceFilter !== "All") params.source = sourceFilter;
      if (search.trim()) params.search = search.trim();
      setTenders(await fetchTenders(params));
    } catch {
      setError("Failed to load tenders. Please try again.");
    } finally {
      setLoading(false);
    }
  }, [statusFilter, sourceFilter, sortBy, order, search]);

  useEffect(() => {
    const t = setTimeout(load, 300); // debounce search/filter changes
    return () => clearTimeout(t);
  }, [load]);

  async function handleScrape() {
    setScraping(true);
    setNotice("");
    try {
      const res = await triggerScrape();
      setNotice(res.message);
      await load();
    } catch {
      setNotice("Scrape failed. Are you signed in as an admin?");
    } finally {
      setScraping(false);
    }
  }

  function handleRowUpdate(updated) {
    setTenders((prev) => prev.map((t) => (t.id === updated.id ? updated : t)));
  }

  async function handleDelete(tender) {
    if (!window.confirm(`Delete "${tender.title}"? You can undo this straight after.`)) return;
    try {
      const res = await deleteTender(tender.id);
      setTenders((prev) => prev.filter((t) => t.id !== tender.id));
      setUndoBatch(res?.batch_id || null);
      setNotice("Opportunity deleted.");
    } catch (err) {
      setNotice(err.response?.data?.detail || "Could not delete the opportunity.");
    }
  }

  async function handleUndo() {
    if (!undoBatch) return;
    const batch = undoBatch;
    setUndoBatch(null);
    try {
      const res = await undoDelete(batch);
      setNotice(
        `Restored ${res.restored} opportunit${res.restored === 1 ? "y" : "ies"}.`
      );
      await load();
    } catch (err) {
      setNotice(err.response?.data?.detail || "Could not undo — it may have expired.");
    }
  }

  // Tune out an irrelevant TYPE of opportunity. Adds a term to the tune-out list
  // so matching non-cyber opportunities are removed now and suppressed on future
  // scrapes. Cyber-security-related opportunities are never removed (server-side
  // guardrail), so we warn if the user tries to tune out a cyber match.
  async function handleTuneOut(tender) {
    const suggestion = (tender.matched_keyword || tender.title || "")
      .split(/\s+/)
      .slice(0, 4)
      .join(" ")
      .trim();
    const term = window.prompt(
      "Tune out this TYPE of opportunity so it stops appearing.\n\n" +
        "Enter a word or phrase found in opportunities you want to hide (e.g. a " +
        "non-cyber service like \"catering\" or \"grounds maintenance\").\n\n" +
        "Anything Cyber Security related is always kept, whatever you enter.",
      suggestion
    );
    if (term == null) return; // cancelled
    const clean = term.trim();
    if (!clean) return;
    try {
      const res = await addTuneOut(clean);
      // Drop the removed opportunities from the current view.
      await load();
      setNotice(
        `Tuned out “${clean}”. Removed ${res.removed} matching non-cyber ` +
          `opportunit${res.removed === 1 ? "y" : "ies"}; these types won't return. ` +
          `Manage the tune-out list under Settings.`
      );
    } catch (err) {
      const status = err.response?.status;
      if (status === 409) {
        setNotice(`“${clean}” is already on the tune-out list.`);
      } else if (status === 403) {
        setNotice("Only an administrator can tune out opportunity types.");
      } else {
        setNotice(err.response?.data?.detail || "Could not tune out that type.");
      }
    }
  }

  async function handleManagementPdf() {
    setNotice("");
    try {
      await downloadManagementSummary();
    } catch (err) {
      setNotice(err.response?.data?.detail || "Could not generate the management summary.");
    }
  }

  async function emailManagementPdf() {
    try {
      const blob = await fetchManagementSummaryBlob();
      await emailFile(
        blob,
        "bid-sentinel-management-summary.pdf",
        "Bid Sentinel — Management Summary"
      );
    } catch (err) {
      setNotice(err.response?.data?.detail || "Could not email the management summary.");
    }
  }

  function toggleSelect(id) {
    setSelected((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }

  // Bulk-delete the selected opportunities and block them from future scrapes.
  async function handleBulkDelete(ids) {
    if (ids.length === 0) return;
    if (
      !window.confirm(
        `Delete ${ids.length} selected opportunit${ids.length === 1 ? "y" : "ies"} ` +
          `and stop them being scraped back in? This cannot be undone.`
      )
    )
      return;
    try {
      const res = await bulkDeleteTenders(ids);
      setTenders((prev) => prev.filter((t) => !ids.includes(t.id)));
      setSelected(new Set());
      setUndoBatch(res?.batch_id || null);
      setNotice(
        `Deleted ${res.deleted} opportunit${res.deleted === 1 ? "y" : "ies"}; ` +
          `${res.suppressed} blocked from future scrapes.`
      );
    } catch (err) {
      setNotice(err.response?.data?.detail || "Could not delete the selected opportunities.");
    }
  }

  const visibleTenders = hideDisregarded
    ? tenders.filter((t) => t.outcome !== "Disregarded")
    : tenders;
  const disregardedCount = tenders.length - visibleTenders.length;

  const colCount = isAdmin ? 10 : 9; // extra column for the select checkbox
  const selectedVisibleIds = visibleTenders.filter((t) => selected.has(t.id)).map((t) => t.id);
  const allVisibleSelected =
    visibleTenders.length > 0 && selectedVisibleIds.length === visibleTenders.length;

  function toggleSelectAll() {
    setSelected((prev) => {
      if (allVisibleSelected) return new Set(); // clear
      const next = new Set(prev);
      visibleTenders.forEach((t) => next.add(t.id));
      return next;
    });
  }

  return (
    <div className="min-h-full">
      {/* Header */}
      <header className="bg-brand text-white shadow">
        <div className="mx-auto flex max-w-7xl items-center justify-between px-6 py-3">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-white px-2 py-1 shadow-sm">
              <img src={logo} alt="Bid Sentinel" className="h-10 w-auto object-contain" />
            </div>
            <div>
              <h1 className="text-lg font-bold tracking-wide">BID SENTINEL</h1>
              <p className="text-xs text-white/70">
                UK Cyber Security Tender Platform
              </p>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <ThemeToggle />
            <AiIndicator active={aiActive} />
            <span className="hidden text-sm text-white/80 sm:inline">
              {user?.email} {isAdmin && <span className="ml-1 rounded bg-white/20 px-1.5 py-0.5 text-xs">admin</span>}
            </span>
            {(isAdmin || user?.role === "analyst") && (
              <Link to="/intelligence" className="rounded-md bg-white/10 px-3 py-1.5 text-sm hover:bg-white/20">
                Intelligence
              </Link>
            )}
            <Link to="/settings" className="rounded-md bg-white/10 px-3 py-1.5 text-sm hover:bg-white/20">
              Settings
            </Link>
            <button
              onClick={logout}
              className="rounded-md bg-white/10 px-3 py-1.5 text-sm hover:bg-white/20"
            >
              Sign out
            </button>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-7xl px-6 py-6">
        {/* Customizable analytics / KPI dashboard */}
        <AnalyticsPanel tenders={visibleTenders} />

        {/* Toolbar */}
        <div className="mb-4 flex flex-wrap items-center gap-3">
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search title or buyer…"
            className="flex-1 min-w-[220px] rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20"
          />
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
          >
            {STATUS_FILTERS.map((s) => (
              <option key={s} value={s}>
                {s === "All" ? "All statuses" : s}
              </option>
            ))}
          </select>

          <select
            value={sourceFilter}
            onChange={(e) => setSourceFilter(e.target.value)}
            className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
          >
            <option value="All">All portals</option>
            {sources.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
            <option value="Manual entry">Manual entry</option>
          </select>

          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value)}
            className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
            title="Sort by"
          >
            {SORT_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                Sort: {o.label}
              </option>
            ))}
          </select>

          <button
            onClick={() => setOrder((o) => (o === "asc" ? "desc" : "asc"))}
            className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50"
            title={order === "asc" ? "Ascending" : "Descending"}
          >
            {order === "asc" ? "↑ Asc" : "↓ Desc"}
          </button>

          <label className="flex items-center gap-1.5 text-sm text-slate-600">
            <input
              type="checkbox"
              checked={hideDisregarded}
              onChange={(e) => setHideDisregarded(e.target.checked)}
            />
            Hide disregarded{disregardedCount > 0 ? ` (${disregardedCount})` : ""}
          </label>

          <button
            onClick={() => setShowAdd(true)}
            className="rounded-lg border border-brand bg-white px-3 py-2 text-sm font-semibold text-brand hover:bg-brand/5"
          >
            + Add opportunity
          </button>

          {isAdmin && selectedVisibleIds.length > 0 && (
            <button
              onClick={() => handleBulkDelete(selectedVisibleIds)}
              className="rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm font-semibold text-red-600 hover:bg-red-100"
              title="Delete the selected opportunities and block them from future scrapes"
            >
              🗑 Delete selected ({selectedVisibleIds.length})
            </button>
          )}

          <button
            onClick={() => exportCsv(visibleTenders)}
            className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50"
          >
            Export CSV
          </button>
          <button
            onClick={() => exportPdf(visibleTenders)}
            className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50"
          >
            Export PDF
          </button>

          {canManagementReport && (
            <button
              onClick={handleManagementPdf}
              className="rounded-lg border border-brand bg-white px-3 py-2 text-sm font-semibold text-brand hover:bg-brand/5"
              title="Download the management summary (pipeline + capability/cert gaps)"
            >
              📊 Management PDF
            </button>
          )}
          {canManagementReport && emailAvailable && (
            <button
              onClick={emailManagementPdf}
              className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50"
              title="Email the management summary to your account address"
            >
               Email summary
            </button>
          )}

          {emailAvailable && (
            <>
              <button
                onClick={() =>
                  emailFile(buildCsvBlob(visibleTenders), "bid-sentinel-tenders.csv", "Bid Sentinel — opportunities (CSV)")
                }
                className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50"
                title="Email the CSV to your account address"
              >
                 Email CSV
              </button>
              <button
                onClick={() =>
                  emailFile(buildPdfBlob(visibleTenders), "bid-sentinel-tenders.pdf", "Bid Sentinel — opportunities (PDF)")
                }
                className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50"
                title="Email the PDF to your account address"
              >
                 Email PDF
              </button>
            </>
          )}

          {isAdmin && (
            <button
              onClick={handleScrape}
              disabled={scraping}
              className="rounded-lg bg-brand px-3 py-2 text-sm font-semibold text-white hover:bg-brand-dark disabled:opacity-60"
            >
              {scraping ? "Scraping…" : "Run Scraper"}
            </button>
          )}
        </div>

        {notice && (
          <div className="mb-4 flex items-center justify-between gap-3 rounded-lg bg-blue-50 px-4 py-2 text-sm text-blue-700">
            <span>{notice}</span>
            {undoBatch && (
              <button
                onClick={handleUndo}
                className="shrink-0 rounded-md border border-blue-300 bg-white px-3 py-1 text-xs font-semibold text-blue-700 hover:bg-blue-100"
              >
                 Undo
              </button>
            )}
          </div>
        )}
        {error && (
          <div className="mb-4 rounded-lg bg-red-50 px-4 py-2 text-sm text-red-700">{error}</div>
        )}

        {/* Table */}
        <div className="overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
          <table className="min-w-full divide-y divide-slate-200 text-sm">
            <thead className="bg-slate-50">
              <tr>
                {isAdmin && (
                  <th className="px-3 py-3">
                    <input
                      type="checkbox"
                      checked={allVisibleSelected}
                      onChange={toggleSelectAll}
                      title="Select all"
                      aria-label="Select all opportunities"
                    />
                  </th>
                )}
                <Th>Opportunity Name</Th>
                <Th>Fit</Th>
                <Th>Published</Th>
                <Th>Closing</Th>
                <Th>Value (£)</Th>
                <Th>Duration</Th>
                <Th>Bid Status</Th>
                <Th>Outcome</Th>
                <Th>Link</Th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {loading ? (
                <tr>
                  <td colSpan={colCount} className="px-4 py-10 text-center text-slate-400">
                    Loading opportunities
                  </td>
                </tr>
              ) : visibleTenders.length === 0 ? (
                <tr>
                  <td colSpan={colCount} className="px-4 py-10 text-center text-slate-400">
                    No opportunities found.
                  </td>
                </tr>
              ) : (
                visibleTenders.map((t) => {
                  const days = daysUntil(t.closing_date);
                  const isOpen = expanded.has(t.id);
                  return (
                    <Fragment key={t.id}>
                    <tr className={`hover:bg-slate-50/60 ${selected.has(t.id) ? "bg-red-50/40" : ""}`}>
                      {isAdmin && (
                        <td className="px-3 py-3 align-top">
                          <input
                            type="checkbox"
                            checked={selected.has(t.id)}
                            onChange={() => toggleSelect(t.id)}
                            className="mt-1"
                            aria-label={`Select ${t.title}`}
                          />
                        </td>
                      )}
                      <td className="px-4 py-3">
                        <div className="flex items-start gap-2">
                          <button
                            onClick={() => toggleExpand(t.id)}
                            className="mt-0.5 text-slate-400 hover:text-brand"
                            title={isOpen ? "Collapse" : "Expand details"}
                            aria-label={isOpen ? "Collapse" : "Expand"}
                          >
                            {isOpen ? "▾" : "▸"}
                          </button>
                          <div className="font-medium text-slate-800">{t.title}</div>
                          {isAdmin && (
                            <button
                              onClick={() => handleTuneOut(t)}
                              className="ml-auto shrink-0 whitespace-nowrap rounded border border-slate-200 px-1.5 py-0.5 text-xs text-slate-400 hover:border-amber-300 hover:bg-amber-50 hover:text-amber-600"
                              title="Tune out this type of opportunity (never hides Cyber Security related)"
                            >
                              🔕 Tune out
                            </button>
                          )}
                        </div>
                        <div className="mt-0.5 text-xs text-slate-500">
                          {t.buyer || "Unknown buyer"}
                          {t.matched_keyword && (
                            <span className="ml-2 rounded bg-brand/10 px-1.5 py-0.5 text-brand">
                              {t.matched_keyword}
                            </span>
                          )}
                        </div>
                        {t.required_certs && (
                          <div className="mt-1 flex flex-wrap gap-1">
                            {t.required_certs.split(", ").map((c) => (
                              <span
                                key={c}
                                className="rounded bg-amber-50 px-1.5 py-0.5 text-xs text-amber-700"
                                title="Certification / accreditation mentioned"
                              >
                                {c}
                              </span>
                            ))}
                          </div>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <FitCell tender={t} />
                      </td>
                      <td className="whitespace-nowrap px-4 py-3 text-slate-600">
                        {formatDate(t.published_date)}
                      </td>
                      <td className="whitespace-nowrap px-4 py-3">
                        <div className="text-slate-600">{formatDate(t.closing_date)}</div>
                        {days != null && (
                          <div className={`text-xs ${days < 7 ? "text-red-500" : "text-slate-400"}`}>
                            {days >= 0 ? `${days} days left` : "closed"}
                          </div>
                        )}
                      </td>
                      <td className="whitespace-nowrap px-4 py-3 text-slate-700">
                        {formatValue(t)}
                      </td>
                      <td className="px-4 py-3 text-slate-600">{t.duration || "—"}</td>
                      <td className="px-4 py-3">
                        <BidStatusSelect tender={t} onChange={handleRowUpdate} />
                      </td>
                      <td className="px-4 py-3">
                        <OutcomeSelect tender={t} onChange={handleRowUpdate} />
                      </td>
                      <td className="whitespace-nowrap px-4 py-3">
                        {t.url && /^https?:\/\//i.test(t.url) ? (
                          <a
                            href={t.url}
                            target="_blank"
                            rel="noreferrer"
                            className="font-medium text-brand-light hover:underline"
                          >
                            View 
                          </a>
                        ) : (
                          <span className="text-xs text-slate-400">Manual</span>
                        )}
                      </td>
                    </tr>
                    {isOpen && (
                      <tr className="bg-slate-50/40">
                        <td colSpan={colCount} className="px-8 py-4">
                          <DetailPanel
                            tender={t}
                            onEdit={() => setEditTarget(t)}
                            onDelete={() => handleDelete(t)}
                          />
                        </td>
                      </tr>
                    )}
                    </Fragment>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </main>

      {showAdd && (
        <OpportunityModal
          onClose={() => setShowAdd(false)}
          onSaved={() => {
            setShowAdd(false);
            setNotice("Opportunity added.");
            load();
          }}
        />
      )}

      {editTarget && (
        <OpportunityModal
          tender={editTarget}
          onClose={() => setEditTarget(null)}
          onSaved={(updated) => {
            setEditTarget(null);
            setNotice("Opportunity updated.");
            if (updated) handleRowUpdate(updated);
          }}
        />
      )}
    </div>
  );
}

function OpportunityModal({ tender, onClose, onSaved }) {
  const editing = Boolean(tender);
  const [form, setForm] = useState(() => ({
    title: tender?.title || "",
    buyer: tender?.buyer || "",
    url: tender && /^https?:\/\//i.test(tender.url || "") ? tender.url : "",
    value: tender?.value_text || (tender?.value_amount != null ? String(tender.value_amount) : ""),
    closing_date: tender?.closing_date ? tender.closing_date.slice(0, 10) : "",
    published_date: tender?.published_date ? tender.published_date.slice(0, 10) : "",
    duration: tender?.duration || "",
    description: tender?.description || "",
  }));
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  function set(field, v) {
    setForm((prev) => ({ ...prev, [field]: v }));
  }

  async function submit(e) {
    e.preventDefault();
    setError("");
    if (!form.title.trim()) {
      setError("Title is required.");
      return;
    }
    setSaving(true);
    try {
      // Send all fields (so text can be cleared on edit); skip empty dates.
      const payload = {};
      for (const [k, v] of Object.entries(form)) {
        if ((k === "closing_date" || k === "published_date") && !v) continue;
        payload[k] = v;
      }
      if (editing) {
        const updated = await updateTender(tender.id, payload);
        onSaved(updated);
      } else {
        await createTender(payload);
        onSaved();
      }
    } catch (err) {
      setError(err.response?.data?.detail || `Could not ${editing ? "save" : "add"} the opportunity.`);
    } finally {
      setSaving(false);
    }
  }

  const input =
    "w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20";

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/40 p-4"
      onClick={onClose}
    >
      <div
        className="mt-12 w-full max-w-lg rounded-2xl bg-white p-6 shadow-xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-bold text-brand">{editing ? "Edit opportunity" : "Add opportunity"}</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600" aria-label="Close">
            
          </button>
        </div>

        {error && <div className="mb-3 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{error}</div>}

        <form onSubmit={submit} className="space-y-3">
          <Field label="Title *">
            <input value={form.title} onChange={(e) => set("title", e.target.value)} required className={input} />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Buyer">
              <input value={form.buyer} onChange={(e) => set("buyer", e.target.value)} className={input} />
            </Field>
            <Field label="Value (£)">
              <input
                value={form.value}
                onChange={(e) => set("value", e.target.value)}
                placeholder="e.g. 250000 or POA"
                className={input}
              />
            </Field>
          </div>
          <Field label="URL (optional)">
            <input
              type="url"
              value={form.url}
              onChange={(e) => set("url", e.target.value)}
              placeholder="https://…"
              className={input}
            />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Published date">
              <input type="date" value={form.published_date} onChange={(e) => set("published_date", e.target.value)} className={input} />
            </Field>
            <Field label="Closing date">
              <input type="date" value={form.closing_date} onChange={(e) => set("closing_date", e.target.value)} className={input} />
            </Field>
          </div>
          <Field label="Duration">
            <input value={form.duration} onChange={(e) => set("duration", e.target.value)} placeholder="e.g. 24 months" className={input} />
          </Field>
          <Field label="Description">
            <textarea
              value={form.description}
              onChange={(e) => set("description", e.target.value)}
              rows={4}
              placeholder="Paste the opportunity details — certs, fit and technical requirements are analysed from this."
              className={input}
            />
          </Field>

          <div className="flex justify-end gap-2 pt-1">
            <button type="button" onClick={onClose} className="rounded-lg border border-slate-300 px-4 py-2 text-sm font-medium hover:bg-slate-50">
              Cancel
            </button>
            <button
              type="submit"
              disabled={saving}
              className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark disabled:opacity-60"
            >
              {saving ? "Saving…" : editing ? "Save changes" : "Add opportunity"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div>
      <label className="mb-1 block text-sm font-medium text-slate-700">{label}</label>
      {children}
    </div>
  );
}

function AiIndicator({ active }) {
  return (
    <span
      className="flex items-center gap-1.5 text-xs text-white/80"
      title={active ? "AI Assistant active" : "AI Assistant inactive"}
    >
      <span
        className={`h-2.5 w-2.5 rounded-full animate-blink-slow ${
          active ? "bg-green-400" : "bg-red-400"
        }`}
        aria-hidden="true"
      />
      AI {active ? "active" : "off"}
    </span>
  );
}

function Th({ children }) {
  return (
    <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
      {children}
    </th>
  );
}

const CLEARANCE_NAMES = ["SC Clearance", "DV Clearance", "BPSS", "NPPV", "List X"];

function DetailPanel({ tender, onEdit, onDelete }) {
  const allCerts = (tender.required_certs || "").split(", ").filter(Boolean);
  const clearances = allCerts.filter((c) => CLEARANCE_NAMES.includes(c));
  const certs = allCerts.filter((c) => !CLEARANCE_NAMES.includes(c));
  const techReqs = (tender.tech_requirements || "").split("\n").filter(Boolean);

  return (
    <div>
    <div className="mb-3 flex justify-end gap-2">
      <button
        onClick={onEdit}
        className="rounded-md border border-slate-300 bg-white px-3 py-1 text-xs font-medium text-slate-700 hover:bg-slate-50"
      >
         Edit
      </button>
      <button
        onClick={onDelete}
        className="rounded-md border border-red-300 bg-white px-3 py-1 text-xs font-medium text-red-600 hover:bg-red-50"
        title="Delete this opportunity entirely (e.g. scraped in error)"
      >
        🗑 Delete
      </button>
    </div>
    {tender.ai_summary && (
      <div className="mb-4 rounded-lg border border-brand/20 bg-brand/5 px-3 py-2">
        <p className="mb-0.5 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-brand">
          <span className="rounded bg-brand px-1 py-0.5 text-[10px] text-white">AI</span>
          Summary
        </p>
        <p className="text-sm text-slate-700">{tender.ai_summary}</p>
      </div>
    )}
    <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
      {/* 1. Certs / accreditations / clearances */}
      <div>
        <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-400">
          Certifications, accreditations &amp; security clearances
        </p>
        {allCerts.length === 0 && <p className="text-sm text-slate-400">None detected.</p>}
        {certs.length > 0 && (
          <div className="mb-2">
            <p className="text-xs text-slate-500">Certifications / accreditations</p>
            <div className="mt-1 flex flex-wrap gap-1">
              {certs.map((c) => (
                <span key={c} className="rounded bg-amber-50 px-1.5 py-0.5 text-xs text-amber-700">
                  {c}
                </span>
              ))}
            </div>
          </div>
        )}
        {clearances.length > 0 && (
          <div>
            <p className="text-xs text-slate-500">Security clearances</p>
            <div className="mt-1 flex flex-wrap gap-1">
              {clearances.map((c) => (
                <span key={c} className="rounded bg-red-50 px-1.5 py-0.5 text-xs text-red-700">
                  {c}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* 2. Top 5 technical requirements */}
      <div>
        <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-400">
          Top technical requirements
        </p>
        {techReqs.length === 0 ? (
          <p className="text-sm text-slate-400">None extracted from the description.</p>
        ) : (
          <ol className="list-decimal space-y-1 pl-4 text-sm text-slate-700">
            {techReqs.map((r, i) => (
              <li key={i}>{r}</li>
            ))}
          </ol>
        )}
      </div>

      {/* 3. Comments */}
      <div>
        <CommentsSection tenderId={tender.id} />
      </div>
    </div>
    </div>
  );
}

function FitCell({ tender }) {
  if (tender.fit_score == null) {
    return <span className="text-xs text-slate-300" title="No capability profile set"></span>;
  }
  const score = tender.fit_score;
  const color =
    score >= 60 ? "text-green-600" : score >= 30 ? "text-amber-600" : "text-slate-400";
  const bar = score >= 60 ? "bg-green-500" : score >= 30 ? "bg-amber-500" : "bg-slate-300";
  return (
    <div className="min-w-[64px]" title={tender.fit_matched ? `Matched: ${tender.fit_matched}` : "No capability terms matched"}>
      <div className={`text-sm font-semibold ${color}`}>{score}%</div>
      <div className="mt-1 h-1.5 w-14 overflow-hidden rounded-full bg-slate-100">
        <div className={`h-full ${bar}`} style={{ width: `${score}%` }} />
      </div>
    </div>
  );
}