-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
1225 lines (1141 loc) · 58.6 KB
/
Copy pathindex.html
File metadata and controls
1225 lines (1141 loc) · 58.6 KB
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VC Conference Scout</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
.pill { display:inline-block; padding:4px 12px; border-radius:9999px; font-size:.875rem; cursor:pointer; border:1px solid; transition:all .15s; line-height:1.5; }
.pill-active { background:#7c3aed; color:white; border-color:#7c3aed; }
.pill-inactive { background:white; color:#4b5563; border-color:#d1d5db; }
.pill-inactive:hover { border-color:#a78bfa; }
.range-wrap { position:relative; width:10rem; height:1.5rem; }
.range-wrap input[type=range] { position:absolute; width:100%; top:0; pointer-events:none; -webkit-appearance:none; appearance:none; background:transparent; height:1.5rem; }
.range-wrap input[type=range]::-webkit-slider-thumb { -webkit-appearance:none; pointer-events:all; width:16px; height:16px; border-radius:50%; background:#7c3aed; cursor:pointer; border:2px solid white; box-shadow:0 1px 3px rgba(0,0,0,.2); }
.range-track { position:absolute; top:50%; transform:translateY(-50%); height:4px; width:100%; background:#e5e7eb; border-radius:4px; pointer-events:none; }
.range-track-active { position:absolute; top:50%; transform:translateY(-50%); height:4px; background:#7c3aed; border-radius:4px; pointer-events:none; }
.btn { display:inline-flex; align-items:center; gap:.5rem; padding:.5rem 1rem; border-radius:.5rem; font-weight:500; transition:all .15s; cursor:pointer; }
.btn-primary { background:#7c3aed; color:white; border:1px solid #7c3aed; }
.btn-primary:hover { background:#6d28d9; }
.btn-secondary { background:white; color:#4b5563; border:1px solid #d1d5db; }
.btn-secondary:hover { border-color:#a78bfa; }
.input { width:100%; border:1px solid #d1d5db; border-radius:.5rem; padding:.5rem .75rem; font-size:.875rem; }
.input:focus { outline:none; border-color:#7c3aed; box-shadow:0 0 0 3px rgba(124,58,237,.1); }
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- Top nav -->
<nav class="bg-white border-b">
<div class="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<a href="#/" class="flex items-center gap-2 text-xl font-bold text-gray-900">
<span class="text-violet-600">◆</span> VC Conference Scout
</a>
<div class="flex items-center gap-2">
<button class="btn btn-secondary" onclick="openSettings()">⚙ Settings</button>
<button class="btn btn-primary" onclick="openNewScan()">+ New Scan</button>
</div>
</div>
</nav>
<!-- Views -->
<div id="view-home" class="hidden"></div>
<div id="view-scan" class="hidden"></div>
<!-- Modals -->
<div id="modal-settings" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeSettings()">
<div class="absolute inset-0 bg-black/40"></div>
<div class="relative bg-white rounded-2xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-6">
<h2 class="text-2xl font-bold text-gray-900 mb-1">Settings</h2>
<p class="text-sm text-gray-500 mb-6">Stored locally in your browser. Never sent to our server.</p>
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-700 mb-1">Anthropic API Key</label>
<div class="flex items-center gap-2">
<input id="setting-api-key" type="password" class="input flex-1" placeholder="sk-ant-..."/>
<button type="button" onclick="saveApiKey()" class="btn btn-secondary whitespace-nowrap" id="setting-key-btn">Save Key</button>
</div>
<p class="text-xs text-gray-500 mt-1">Get one at console.anthropic.com. Stored in browser localStorage.</p>
</div>
<div>
<label class="block text-sm font-semibold text-gray-700 mb-1">Your VC Profile / Thesis</label>
<textarea id="setting-profile" class="input" rows="6" placeholder="e.g. Acme Ventures, early-stage VC investing in vertical AI for healthcare..."></textarea>
<div class="flex items-center gap-2 mt-2">
<input id="setting-firm-url" type="url" class="input flex-1" placeholder="https://yourvcfirm.com"/>
<button onclick="extractProfile('setting')" class="btn btn-secondary whitespace-nowrap" id="setting-extract-btn">Extract from URL</button>
</div>
<p class="text-xs text-gray-500 mt-1">Describe what you invest in, or paste your firm's website URL and click Extract.</p>
</div>
</div>
<div class="flex gap-2 mt-6 pt-4 border-t">
<button onclick="saveSettings()" class="btn btn-primary">Save</button>
<button onclick="closeSettings()" class="btn btn-secondary">Cancel</button>
</div>
</div>
</div>
<div id="modal-new-scan" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeNewScan()">
<div class="absolute inset-0 bg-black/40"></div>
<div class="relative bg-white rounded-2xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-6">
<h2 class="text-2xl font-bold text-gray-900 mb-6">New Scan</h2>
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-700 mb-1">Scan Name</label>
<input id="ns-name" type="text" class="input" placeholder="e.g. HumanX 2026"/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-700 mb-2">Source</label>
<div class="flex gap-2 mb-2">
<button type="button" id="ns-src-url-btn" onclick="setSourceMode('url')" class="pill pill-active">From URL</button>
<button type="button" id="ns-src-csv-btn" onclick="setSourceMode('csv')" class="pill pill-inactive">CSV upload</button>
</div>
<div id="ns-src-url">
<input id="ns-url" type="url" class="input" placeholder="https://example.com/attendees"/>
<p class="text-xs text-gray-500 mt-1">Note: many conference sites load their attendee list with JavaScript (Map-Your-Show, 6Connex, etc.) — those won't work with URL scraping. If the scan fails, copy the company list into a CSV and use the CSV upload tab instead.</p>
<button type="button" onclick="document.getElementById('ns-advanced').classList.toggle('hidden')" class="text-xs text-violet-600 hover:underline mt-2">▸ Advanced (CSS selector)</button>
<div id="ns-advanced" class="hidden mt-2">
<input id="ns-selector" type="text" class="input" placeholder="e.g. .company-name (leave blank for auto-detect)"/>
<p class="text-xs text-gray-500 mt-1">Optional. If auto-detect fails, inspect the page in your browser and provide a CSS selector pointing at company names.</p>
</div>
</div>
<div id="ns-src-csv" class="hidden">
<div class="bg-amber-50 border border-amber-200 rounded p-3 text-xs text-amber-900 mb-2">
<strong>CSV format requirements:</strong>
<ul class="list-disc ml-4 mt-1 space-y-0.5">
<li>Comma-separated, with a header row in the very first line.</li>
<li>One column should contain the company names — name it <code>name</code>, <code>company</code>, <code>exhibitor</code>, <code>organization</code>, or <code>attendee</code>. The parser auto-detects which column to read.</li>
<li><strong>No leading empty columns or sheet-title rows.</strong> If you exported from Numbers/Excel, delete the auto-prepended title row first.</li>
<li>Other columns (descriptions, booth numbers, etc.) are ignored.</li>
</ul>
</div>
<input id="ns-csv-file" type="file" accept=".csv,.txt" class="input" onchange="onCsvSelected()"/>
<p id="ns-csv-status" class="text-xs text-gray-500 mt-1">Upload a CSV or TXT file. The parser will tell you how many companies it found before you start the scan.</p>
</div>
</div>
<div id="ns-profile-warn" class="hidden bg-yellow-50 border border-yellow-200 rounded p-3 text-sm text-yellow-800">
Set your VC Profile in <button class="underline" onclick="closeNewScan();openSettings()">Settings</button> first.
</div>
<div>
<label class="block text-sm font-semibold text-gray-700 mb-2">Categories</label>
<div class="flex gap-2 mb-2">
<button type="button" id="ns-cat-auto-btn" onclick="setCatMode('auto')" class="pill pill-active">Auto-generate</button>
<button type="button" id="ns-cat-manual-btn" onclick="setCatMode('manual')" class="pill pill-inactive">Manual</button>
</div>
<p id="ns-cat-auto-help" class="text-xs text-gray-500">Categories will be generated from the actual results after enrichment, tailored to this conference.</p>
<textarea id="ns-categories" class="input hidden mt-1" rows="6" placeholder="One category per line"></textarea>
</div>
<div id="ns-key-warn" class="hidden bg-yellow-50 border border-yellow-200 rounded p-3 text-sm text-yellow-800">
Set your Anthropic API key in <button class="underline" onclick="closeNewScan();openSettings()">Settings</button> first.
</div>
<div class="bg-violet-50 border border-violet-200 rounded p-3 text-xs text-violet-900">
<strong>Typical cost:</strong> $30–60 per conference, ~15–25 minutes. The pipeline coarse-triages all attendees, then enriches every high-confidence match (relevance ≥ 5) with a web search before scoring with full context. Low-confidence candidates stay as name-only — deepen them later with the <em>Enrich uncertain</em> button on the scan page.
</div>
</div>
<div class="flex gap-2 mt-6 pt-4 border-t">
<button onclick="submitNewScan()" class="btn btn-primary">Start Scan</button>
<button onclick="closeNewScan()" class="btn btn-secondary">Cancel</button>
</div>
</div>
</div>
<!-- Detail Modal (company card detail) -->
<div id="modal-company" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeCompanyModal()">
<div class="absolute inset-0 bg-black/40"></div>
<div class="relative bg-white rounded-2xl shadow-xl max-w-2xl w-full max-h-[85vh] overflow-y-auto p-6">
<button onclick="closeCompanyModal()" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none">×</button>
<div id="company-modal-body"></div>
</div>
</div>
<script>
// ===== Settings (localStorage) =====
function getSettings() {
return {
apiKey: localStorage.getItem('vcs_api_key') || '',
profile: localStorage.getItem('vcs_profile') || '',
};
}
function openSettings() {
const s = getSettings();
document.getElementById('setting-api-key').value = s.apiKey;
document.getElementById('setting-profile').value = s.profile;
document.getElementById('modal-settings').classList.remove('hidden');
}
function closeSettings() { document.getElementById('modal-settings').classList.add('hidden'); }
function saveApiKey() {
const key = document.getElementById('setting-api-key').value.trim();
if (!key) { alert('Enter an API key first.'); return; }
localStorage.setItem('vcs_api_key', key);
const btn = document.getElementById('setting-key-btn');
const orig = btn.textContent;
btn.textContent = '✓ Saved';
setTimeout(() => { btn.textContent = orig; }, 1500);
}
function saveSettings() {
localStorage.setItem('vcs_api_key', document.getElementById('setting-api-key').value.trim());
localStorage.setItem('vcs_profile', document.getElementById('setting-profile').value.trim());
closeSettings();
}
// ===== Profile extraction =====
async function extractProfile(prefix) {
// Read key from the live Settings input if it's open, otherwise localStorage
const liveKey = document.getElementById('setting-api-key').value.trim();
const apiKey = liveKey || localStorage.getItem('vcs_api_key') || '';
if (!apiKey) { alert('Enter your Anthropic API key first.'); return; }
const url = document.getElementById(prefix + '-firm-url').value.trim();
if (!url) { alert('Enter your VC firm website URL first.'); return; }
const btn = document.getElementById(prefix + '-extract-btn');
const orig = btn.textContent;
btn.textContent = 'Extracting...';
btn.disabled = true;
try {
const res = await fetch('/api/extract-profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url, api_key: apiKey }),
});
if (!res.ok) throw new Error((await res.json()).error || 'Failed');
const { profile } = await res.json();
document.getElementById(prefix + '-profile').value = profile;
} catch (e) {
alert('Error: ' + e.message);
} finally {
btn.textContent = orig;
btn.disabled = false;
}
}
// ===== New Scan =====
let nsSourceMode = 'url';
let nsCsvCompanies = [];
function setSourceMode(mode) {
nsSourceMode = mode;
document.getElementById('ns-src-url-btn').className = mode==='url' ? 'pill pill-active' : 'pill pill-inactive';
document.getElementById('ns-src-csv-btn').className = mode==='csv' ? 'pill pill-active' : 'pill pill-inactive';
document.getElementById('ns-src-url').classList.toggle('hidden', mode!=='url');
document.getElementById('ns-src-csv').classList.toggle('hidden', mode!=='csv');
}
// Parse CSV into rows of cells (handles quoted fields with commas/quotes/newlines)
function parseCsvRows(text) {
const rows = [];
let row = [];
let cell = '';
let inQuotes = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (inQuotes) {
if (ch === '"' && text[i+1] === '"') { cell += '"'; i++; }
else if (ch === '"') { inQuotes = false; }
else { cell += ch; }
} else {
if (ch === '"') { inQuotes = true; }
else if (ch === ',') { row.push(cell); cell = ''; }
else if (ch === '\n' || ch === '\r') {
if (cell !== '' || row.length) { row.push(cell); rows.push(row); row = []; cell = ''; }
if (ch === '\r' && text[i+1] === '\n') i++;
} else { cell += ch; }
}
}
if (cell !== '' || row.length) { row.push(cell); rows.push(row); }
return rows.map(r => r.map(c => c.trim()));
}
const HEADER_RE = /^(name|company|company\s*name|organization|exhibitor|exhibitors|attendee|attendees|startup|startup\s*name|account|account\s*name|brand)$/i;
function looksLikeName(v) {
if (!v) return false;
if (v.length < 2 || v.length > 120) return false;
if (/^https?:\/\//i.test(v)) return false; // URL
if (/^[\d.,$%+\-/\s]+$/.test(v)) return false; // pure number/currency
if (!/[A-Za-z]/.test(v)) return false; // no letters
return true;
}
// Score how "name-like" a column is
function scoreColumn(rows, colIdx) {
let nameish = 0, total = 0, totalLen = 0;
const distinct = new Set();
for (const r of rows) {
const v = r[colIdx];
if (v === undefined || v === '') continue;
total++;
if (looksLikeName(v)) {
nameish++;
totalLen += v.length;
distinct.add(v.toLowerCase());
}
}
if (total === 0) return -Infinity;
const avgLen = nameish ? totalLen / nameish : 0;
// Sweet spot for company names is 5-50 chars
let lenBonus = 0;
if (avgLen >= 5 && avgLen <= 50) lenBonus = 20;
else if (avgLen > 50 && avgLen <= 80) lenBonus = 5;
return nameish * 2 + distinct.size + lenBonus - (total - nameish);
}
function parseCsv(text) {
const rows = parseCsvRows(text).filter(r => r.some(c => c !== ''));
if (!rows.length) return [];
const maxCols = Math.max(...rows.map(r => r.length));
// 1) Find a header row in the first ~5 rows that matches HEADER_RE
let headerRowIdx = -1;
let nameColIdx = -1;
for (let i = 0; i < Math.min(5, rows.length); i++) {
for (let c = 0; c < rows[i].length; c++) {
if (HEADER_RE.test(rows[i][c])) {
headerRowIdx = i;
nameColIdx = c;
break;
}
}
if (nameColIdx !== -1) break;
}
// 2) If no header found, score every column and pick the best
if (nameColIdx === -1) {
let bestScore = -Infinity;
for (let c = 0; c < maxCols; c++) {
const s = scoreColumn(rows, c);
if (s > bestScore) { bestScore = s; nameColIdx = c; }
}
}
if (nameColIdx === -1) return [];
// 3) Extract that column, skipping header row and noise
const NOISE = /^(all\s+exhibitors|attendees|companies|sponsors|exhibitors|sheet\s*\d*|page\s*\d*)/i;
const out = [];
for (let i = 0; i < rows.length; i++) {
if (i === headerRowIdx) continue;
const v = rows[i][nameColIdx];
if (!v) continue;
if (HEADER_RE.test(v)) continue;
if (NOISE.test(v)) continue;
if (/\(\s*\d+\s*\)/.test(v) && v.length < 40) continue; // "All Exhibitors ( 378 )"
if (!looksLikeName(v)) continue;
out.push(v);
}
// Dedupe (case-insensitive, preserve order)
const seen = new Set();
return out.filter(n => {
const k = n.toLowerCase();
if (seen.has(k)) return false;
seen.add(k);
return true;
});
}
function onCsvSelected() {
const file = document.getElementById('ns-csv-file').files[0];
if (!file) { nsCsvCompanies = []; return; }
const reader = new FileReader();
reader.onload = e => {
nsCsvCompanies = parseCsv(e.target.result);
document.getElementById('ns-csv-status').textContent = `Parsed ${nsCsvCompanies.length} companies from ${file.name}`;
};
reader.readAsText(file);
}
let nsCatMode = 'auto';
function setCatMode(mode) {
nsCatMode = mode;
document.getElementById('ns-cat-auto-btn').className = mode==='auto' ? 'pill pill-active' : 'pill pill-inactive';
document.getElementById('ns-cat-manual-btn').className = mode==='manual' ? 'pill pill-active' : 'pill pill-inactive';
document.getElementById('ns-cat-auto-help').classList.toggle('hidden', mode!=='auto');
document.getElementById('ns-categories').classList.toggle('hidden', mode!=='manual');
}
function openNewScan() {
const s = getSettings();
document.getElementById('ns-name').value = '';
document.getElementById('ns-url').value = '';
document.getElementById('ns-selector').value = '';
document.getElementById('ns-categories').value = '';
document.getElementById('ns-advanced').classList.add('hidden');
document.getElementById('ns-csv-file').value = '';
document.getElementById('ns-csv-status').textContent = 'Upload a CSV or TXT file. The first column (or each line) is treated as a company name.';
nsCsvCompanies = [];
setSourceMode('url');
setCatMode('auto');
document.getElementById('ns-key-warn').classList.toggle('hidden', !!s.apiKey);
document.getElementById('ns-profile-warn').classList.toggle('hidden', !!s.profile);
document.getElementById('modal-new-scan').classList.remove('hidden');
}
function closeNewScan() { document.getElementById('modal-new-scan').classList.add('hidden'); }
async function submitNewScan() {
const s = getSettings();
if (!s.apiKey) { alert('Set your Anthropic API key in Settings first.'); return; }
if (!s.profile) { alert('Set your VC Profile in Settings first.'); return; }
const name = document.getElementById('ns-name').value.trim();
const profile = s.profile;
if (!name) { alert('Please fill in a scan name.'); return; }
let url = '', selector = '', companies = null;
if (nsSourceMode === 'url') {
url = document.getElementById('ns-url').value.trim();
selector = document.getElementById('ns-selector').value.trim();
if (!url) { alert('Please provide a conference URL.'); return; }
} else {
if (!nsCsvCompanies.length) { alert('Upload a CSV file with company names first.'); return; }
companies = nsCsvCompanies;
}
let categories = [];
let auto_categorize = false;
if (nsCatMode === 'auto') {
auto_categorize = true;
// Provide a temporary placeholder so classify step has something to bucket into;
// these will be replaced after enrichment.
categories = ['Pending'];
} else {
categories = document.getElementById('ns-categories').value.split('\n').map(x=>x.trim()).filter(Boolean);
if (!categories.length) { alert('Add at least one category, or switch to Auto-generate.'); return; }
}
try {
const res = await fetch('/api/scans', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, url, selector, companies, profile, categories, auto_categorize, api_key: s.apiKey }),
});
if (!res.ok) throw new Error((await res.json()).error || 'Failed');
const { id } = await res.json();
closeNewScan();
location.hash = '#/scan/' + id;
} catch (e) {
alert('Error: ' + e.message);
}
}
// ===== Routing =====
function route() {
const hash = location.hash || '#/';
document.getElementById('view-home').classList.add('hidden');
document.getElementById('view-scan').classList.add('hidden');
if (hash === '#/' || hash === '') {
renderHome();
} else if (hash.startsWith('#/scan/')) {
const id = hash.slice('#/scan/'.length);
renderScan(id);
}
}
window.addEventListener('hashchange', route);
// ===== Home view =====
async function renderHome() {
const view = document.getElementById('view-home');
view.classList.remove('hidden');
view.innerHTML = '<div class="max-w-7xl mx-auto px-6 py-8"><p class="text-gray-500">Loading scans...</p></div>';
try {
const res = await fetch('/api/scans');
const scans = await res.json();
view.innerHTML = `
<div class="max-w-7xl mx-auto px-6 py-8">
<div class="mb-6">
<h1 class="text-3xl font-bold text-gray-900">Your Scans</h1>
<p class="text-gray-500 mt-1">${scans.length} scan${scans.length===1?'':'s'}</p>
</div>
${scans.length === 0 ? `
<div class="bg-white rounded-xl border p-12 text-center">
<p class="text-gray-500 mb-4">No scans yet.</p>
<button class="btn btn-primary" onclick="openNewScan()">+ Create your first scan</button>
</div>
` : `
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
${scans.map(s => renderScanCard(s)).join('')}
</div>
`}
</div>
`;
} catch (e) {
view.innerHTML = '<div class="max-w-7xl mx-auto px-6 py-8"><p class="text-red-500">Error loading scans: ' + e.message + '</p></div>';
}
}
function renderScanCard(s) {
const isError = s.stage === 'error';
const isDone = !isError && (s.stage === 'done' || s.completed_at);
const statusBg = isError ? 'bg-red-100 text-red-800' : (isDone ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800');
const statusLabel = isError ? 'Failed' : (isDone ? 'Complete' : (s.stage_label || s.stage || 'Running'));
return `
<a href="#/scan/${s.id}" class="block bg-white rounded-xl border p-5 hover:shadow-md transition-shadow relative">
<button onclick="event.preventDefault();event.stopPropagation();deleteScan('${s.id}', '${(s.name||'').replace(/'/g,"\\'")}')" class="absolute top-3 right-3 text-gray-300 hover:text-red-500" title="Delete">×</button>
<h3 class="font-semibold text-gray-900 text-lg pr-6">${s.name}</h3>
${s.url ? `<p class="text-xs text-gray-500 truncate mt-1">${s.url}</p>` : ''}
${s.synopsis ? `<p class="text-xs text-gray-400 mt-2 line-clamp-3">${s.synopsis}</p>` : ''}
<div class="flex flex-wrap gap-1.5 mt-3">
<span class="text-xs px-2 py-0.5 rounded-full ${statusBg}">${statusLabel}${!isDone && s.percent ? ' '+s.percent+'%' : ''}</span>
${s.relevant_matches ? `<span class="text-xs px-2 py-0.5 rounded-full bg-violet-100 text-violet-700">${s.relevant_matches} matches</span>` : ''}
${s.total_scraped ? `<span class="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600">${s.total_scraped} scraped</span>` : ''}
</div>
</a>
`;
}
async function deleteScan(id, name) {
if (!confirm(`Delete scan "${name}"? This cannot be undone.`)) return;
await fetch('/api/scans/' + id, { method: 'DELETE' });
renderHome();
}
// ===== Scan Detail view =====
let currentScanId = null;
let allData = [];
let starred = {};
let activeCategories = new Set();
let activeStages = new Set();
let starredOnly = false;
let sortAsc = false;
let progressInterval = null;
async function renderScan(id) {
currentScanId = id;
const view = document.getElementById('view-scan');
view.classList.remove('hidden');
// Render scan detail shell (the existing UI)
view.innerHTML = `
<div id="progress-banner" class="hidden bg-violet-600 text-white px-6 py-4">
<div class="max-w-7xl mx-auto">
<div class="flex items-center gap-3 mb-3">
<svg id="progress-spinner" class="animate-spin h-5 w-5" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/></svg>
<span id="progress-label">Starting...</span>
<div class="flex-1 bg-violet-400 rounded-full h-2 mx-4"><div id="progress-bar" class="bg-white rounded-full h-2 transition-all" style="width:0%"></div></div>
<span id="progress-pct" class="text-sm font-mono mr-2">0%</span>
<button id="btn-pause" onclick="controlScan('pause')" class="text-xs px-3 py-1 rounded border border-white/40 hover:bg-white/10">⏸ Pause</button>
<button id="btn-resume" onclick="controlScan('resume')" class="hidden text-xs px-3 py-1 rounded border border-white/40 hover:bg-white/10">▶ Resume</button>
<button id="btn-cancel" onclick="controlScan('cancel')" class="text-xs px-3 py-1 rounded border border-white/40 hover:bg-white/10">✕ Cancel</button>
</div>
<div id="progress-steps" class="flex items-center gap-2 text-xs flex-wrap"></div>
</div>
</div>
<div class="max-w-7xl mx-auto px-6 py-8">
<div class="mb-4"><a href="#/" class="text-sm text-violet-600 hover:underline">← Back to scans</a></div>
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
<div class="flex-1 min-w-0">
<h1 id="scan-title" class="text-3xl font-bold text-gray-900">Loading...</h1>
<div class="flex items-center gap-3 mt-1">
<p id="stats" class="text-gray-500 text-sm"></p>
<button id="synopsis-toggle" class="hidden text-xs text-violet-600 hover:underline" onclick="toggleSynopsis()">ⓘ About this conference</button>
</div>
<p id="scan-synopsis" class="hidden text-xs text-gray-500 mt-2 max-w-3xl bg-gray-50 border border-gray-200 rounded p-3"></p>
</div>
<div class="flex items-center gap-2">
<button id="enrich-uncertain-btn" onclick="enrichUncertain()" class="hidden btn btn-secondary whitespace-nowrap" title="Enrich the candidates that are still name-only"></button>
<input id="search" type="text" placeholder="Search companies..." class="input sm:w-72"/>
</div>
</div>
<div class="bg-white rounded-xl shadow-sm border p-5 mb-6 space-y-4">
<div class="flex items-center gap-2 flex-wrap">
<button id="starred-filter" class="pill pill-inactive inline-flex items-center gap-1" onclick="toggleStarredFilter()">
<span style="color:#eab308">★</span> Starred (<span id="starred-count">0</span>)
</button>
<button class="pill pill-inactive" onclick="clearAllFilters()">Show All</button>
<div class="flex-1"></div>
<button onclick="exportStarred()" class="pill pill-inactive">↓ Export Starred</button>
</div>
<div><label class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Categories</label><div id="category-pills" class="flex flex-wrap gap-2 mt-1"></div></div>
<div><label class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Stage</label><div id="stage-pills" class="flex flex-wrap gap-2 mt-1"></div></div>
<div class="flex flex-col sm:flex-row gap-4 items-start sm:items-center flex-wrap">
<div class="flex items-center gap-2">
<label class="text-sm text-gray-600">Score:</label>
<div class="range-wrap"><div class="range-track"></div><div id="score-track-active" class="range-track-active" style="left:0%;right:0%"></div>
<input id="score-lo" type="range" min="5" max="10" value="5" oninput="onScoreRange()"/>
<input id="score-hi" type="range" min="5" max="10" value="10" oninput="onScoreRange()"/>
</div>
<span id="score-val" class="text-sm font-mono text-gray-700">5 – 10</span>
</div>
<div class="flex items-center gap-2">
<label class="text-sm text-gray-600">Funding:</label>
<div class="range-wrap"><div class="range-track"></div><div id="funding-track-active" class="range-track-active" style="left:0%;right:0%"></div>
<input id="funding-lo" type="range" min="0" max="9" value="0" oninput="onFundingRange()"/>
<input id="funding-hi" type="range" min="0" max="9" value="9" oninput="onFundingRange()"/>
</div>
<span id="funding-val" class="text-sm font-mono text-gray-700">Any</span>
</div>
</div>
<div class="flex items-center gap-2">
<label class="text-sm text-gray-600">Sort by:</label>
<select id="sort-by" class="border rounded px-2 py-1 text-sm" onchange="render()">
<option value="relevance">Score</option><option value="name">Name</option>
<option value="funding">Funding</option><option value="stage">Stage</option><option value="founded">Founded</option>
</select>
<button id="sort-dir-btn" class="border rounded px-2 py-1 text-sm cursor-pointer hover:bg-gray-100" onclick="toggleSortDir()">▼</button>
</div>
</div>
<div id="cards" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"></div>
<p id="no-results" class="hidden text-center text-gray-400 py-12 text-lg">No companies match your filters.</p>
</div>
`;
// Wire search/sort change handlers
document.getElementById('search').addEventListener('input', render);
document.getElementById('sort-by').addEventListener('change', () => {
const v = document.getElementById('sort-by').value;
sortAsc = (v === 'name' || v === 'stage' || v === 'founded');
document.getElementById('sort-dir-btn').textContent = sortAsc ? '\u25B2' : '\u25BC';
});
await loadScanData(id);
if (progressInterval) clearInterval(progressInterval);
progressInterval = setInterval(() => pollProgress(id), 2000);
pollProgress(id);
}
function toggleSynopsis() {
const el = document.getElementById('scan-synopsis');
const btn = document.getElementById('synopsis-toggle');
const isHidden = el.classList.contains('hidden');
el.classList.toggle('hidden');
btn.textContent = isHidden ? '✕ Hide' : 'ⓘ About this conference';
}
async function loadScanData(id) {
try {
const res = await fetch('/api/scans/' + id);
if (!res.ok) throw new Error('Scan not found');
const data = await res.json();
currentScanConfig = data.config || {};
document.getElementById('scan-title').textContent = data.config.name || id;
const synopsisEl = document.getElementById('scan-synopsis');
const synopsisToggle = document.getElementById('synopsis-toggle');
if (data.config.synopsis) {
synopsisEl.textContent = data.config.synopsis;
synopsisEl.classList.add('hidden'); // collapsed by default
synopsisToggle.classList.remove('hidden');
synopsisToggle.textContent = 'ⓘ About this conference';
} else {
synopsisEl.classList.add('hidden');
synopsisToggle.classList.add('hidden');
}
starred = data.starred || {};
allData = (data.results.results || []).map(d => ({
...d,
_fundingNum: parseFunding(d.funding),
_stage: normalizeStage(d.stage || d.type),
}));
updateStarredCount();
buildFilters();
render();
updateEnrichUncertainBtn(data);
} catch (e) {
document.getElementById('stats').textContent = 'Error: ' + e.message;
}
}
function updateEnrichUncertainBtn(data) {
const btn = document.getElementById('enrich-uncertain-btn');
if (!btn) return;
// Only show on completed scans with unenriched companies
const isDone = (data.progress && data.progress.stage === 'done') || (data.config && data.config.completed_at);
if (!isDone) { btn.classList.add('hidden'); return; }
const unenriched = allData.filter(c => !c.description).length;
if (unenriched === 0) { btn.classList.add('hidden'); return; }
// Cost estimate: ~$0.10 per enrichment + scoring overhead
const estCost = (unenriched * 0.10).toFixed(0);
btn.textContent = `↑ Enrich ${unenriched} uncertain (~$${estCost})`;
btn.classList.remove('hidden');
}
async function enrichUncertain() {
const s = getSettings();
if (!s.apiKey) { alert('Set your Anthropic API key in Settings first.'); return; }
const unenriched = allData.filter(c => !c.description).length;
if (!confirm(`Enrich ${unenriched} uncertain companies via web search? Estimated cost: ~$${(unenriched * 0.10).toFixed(0)}, ~${Math.ceil(unenriched * 3 / 60)} minutes.`)) return;
try {
const res = await fetch('/api/scans/' + currentScanId + '/enrich-uncertain', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ api_key: s.apiKey }),
});
if (!res.ok) throw new Error((await res.json()).error || 'Failed');
document.getElementById('enrich-uncertain-btn').classList.add('hidden');
if (progressInterval) clearInterval(progressInterval);
progressInterval = setInterval(() => pollProgress(currentScanId), 2000);
pollProgress(currentScanId);
} catch (e) {
alert('Error: ' + e.message);
}
}
// Pipeline step definitions
const PIPELINE_STEPS = [
{ key: 'load', label: 'Load companies', stages: ['starting','scraping','loading'] },
{ key: 'filter', label: 'Pre-filter', stages: ['filtering'] },
{ key: 'synopsis', label: 'Conference synopsis', stages: ['synopsis'] },
{ key: 'triage', label: 'Coarse triage', stages: ['triaging','classifying'] },
{ key: 'enrich', label: 'Enrich (web search)', stages: ['enriching'] },
{ key: 'score', label: 'Score with full context', stages: ['scoring'] },
{ key: 'categorize', label: 'Auto-categorize', stages: ['categorizing'], optional: true },
];
let currentScanConfig = null;
function renderProgressSteps(currentStage) {
const container = document.getElementById('progress-steps');
if (!container) return;
const autoCategorize = currentScanConfig && currentScanConfig.auto_categorize;
const steps = PIPELINE_STEPS.filter(s => !s.optional || autoCategorize);
// Determine which step is active and which are done
let activeIdx = -1;
for (let i = 0; i < steps.length; i++) {
if (steps[i].stages.includes(currentStage)) { activeIdx = i; break; }
}
// If currentStage isn't recognized but is "done", mark all done
if (currentStage === 'done') activeIdx = steps.length;
container.innerHTML = steps.map((s, i) => {
let icon, opacity;
if (i < activeIdx) { icon = '✓'; opacity = '1'; }
else if (i === activeIdx) { icon = '●'; opacity = '1'; }
else { icon = '○'; opacity = '0.5'; }
const sep = i < steps.length - 1 ? '<span class="text-violet-300 mx-1">→</span>' : '';
const weight = i === activeIdx ? 'font-semibold' : '';
return `<span style="opacity:${opacity}" class="${weight}">${icon} ${s.label}</span>${sep}`;
}).join('');
}
async function controlScan(action) {
if (!currentScanId) return;
if (action === 'cancel' && !confirm('Cancel this scan? Partial results will be kept.')) return;
try {
const res = await fetch('/api/scans/' + currentScanId + '/' + action, { method: 'POST' });
if (!res.ok) throw new Error((await res.json()).error || 'Failed');
pollProgress(currentScanId);
} catch (e) {
alert('Error: ' + e.message);
}
}
async function pollProgress(id) {
try {
const res = await fetch('/api/scans/' + id + '/progress');
const p = await res.json();
const banner = document.getElementById('progress-banner');
if (!banner) return;
if (!p.stage) {
banner.classList.add('hidden');
return;
}
if (p.stage === 'cancelled') {
banner.classList.remove('hidden');
banner.classList.remove('bg-violet-600');
banner.classList.add('bg-gray-600');
document.getElementById('progress-spinner').classList.add('hidden');
document.getElementById('progress-label').textContent = 'Cancelled';
document.getElementById('btn-pause').classList.add('hidden');
document.getElementById('btn-resume').classList.add('hidden');
document.getElementById('btn-cancel').classList.add('hidden');
if (progressInterval) { clearInterval(progressInterval); progressInterval = null; }
loadScanData(id);
return;
}
if (p.stage === 'error') {
banner.classList.remove('hidden');
banner.classList.remove('bg-violet-600','bg-gray-600');
banner.classList.add('bg-red-600');
document.getElementById('progress-spinner').classList.add('hidden');
const detail = p.error_detail || p.stage_label || 'Scan failed';
document.getElementById('progress-label').innerHTML = '<strong>Scan failed:</strong> ' + detail;
document.getElementById('progress-bar').style.width = '0%';
document.getElementById('progress-pct').textContent = '';
document.getElementById('btn-pause').classList.add('hidden');
document.getElementById('btn-resume').classList.add('hidden');
document.getElementById('btn-cancel').classList.add('hidden');
if (progressInterval) { clearInterval(progressInterval); progressInterval = null; }
return;
}
if (p.stage === 'done') {
// Show steps as all done briefly, then hide
renderProgressSteps('done');
document.getElementById('progress-bar').style.width = '100%';
document.getElementById('progress-pct').textContent = '100%';
document.getElementById('progress-label').textContent = 'Complete';
if (progressInterval) {
clearInterval(progressInterval);
progressInterval = null;
loadScanData(id);
setTimeout(() => banner.classList.add('hidden'), 1500);
}
return;
}
banner.classList.remove('hidden');
banner.classList.remove('bg-gray-600');
banner.classList.add('bg-violet-600');
const spinner = document.getElementById('progress-spinner');
if (p.paused) {
spinner.classList.add('hidden');
document.getElementById('btn-pause').classList.add('hidden');
document.getElementById('btn-resume').classList.remove('hidden');
document.getElementById('progress-label').textContent = '⏸ Paused — ' + (p.stage_label || p.stage);
} else {
spinner.classList.remove('hidden');
document.getElementById('btn-pause').classList.remove('hidden');
document.getElementById('btn-resume').classList.add('hidden');
document.getElementById('progress-label').textContent = p.stage_label || p.stage;
}
document.getElementById('btn-cancel').classList.remove('hidden');
document.getElementById('progress-bar').style.width = (p.percent || 0) + '%';
document.getElementById('progress-pct').textContent = (p.percent || 0) + '%';
renderProgressSteps(p.stage);
// Reload data periodically as new matches stream in
if (p.stage === 'classifying' || p.stage === 'enriching' || p.stage === 'categorizing') {
loadScanData(id);
}
} catch {}
}
// ===== Stage / funding helpers =====
function normalizeStage(raw) {
if (!raw) return 'Unknown';
const s = raw.toLowerCase().replace(/[()]/g, '');
if (/acquired|acquisition/i.test(s)) return 'Acquired';
if (/public|ipo|nyse|nasdaq|spac/i.test(s)) return 'Public';
if (/series\s*f/i.test(s)) return 'Series F';
if (/series\s*e/i.test(s)) return 'Series E';
if (/series\s*d/i.test(s)) return 'Series D';
if (/series\s*c/i.test(s)) return 'Series C';
if (/series\s*b/i.test(s)) return 'Series B';
if (/series\s*a/i.test(s)) return 'Series A';
if (/pre.?a/i.test(s)) return 'Pre-A';
if (/pre.?seed/i.test(s)) return 'Pre-seed';
if (/angel/i.test(s)) return 'Pre-seed';
if (/seed/i.test(s)) return 'Seed';
if (/bootstrap|self.?fund|unfund|stealth/i.test(s)) return 'Bootstrapped';
if (/growth|unicorn|late.?stage|private equity|pe.?back/i.test(s)) return 'Growth';
if (/early|launch|grant|incubat|accelerat/i.test(s)) return 'Early Stage';
if (/private|not\s|n\/a|unknown|information|not specified/i.test(s)) return 'Unknown';
if (/startup/i.test(s)) return 'Early Stage';
if (/mature/i.test(s)) return 'Growth';
return 'Unknown';
}
const FUNDING_STEPS = [0, 0.1, 0.5, 1, 5, 10, 25, 50, 100, 250, Infinity];
const FUNDING_LABELS = ['Any','$100K','$500K','$1M','$5M','$10M','$25M','$50M','$100M','$250M+'];
function parseFunding(s) {
if (!s) return null;
s = s.replace(/,/g, '');
// Allow optional "+" and whitespace between the number and the unit, e.g. "$10+ billion"
const m = s.match(/\$([\d.]+)\s*\+?\s*(billion|bn|B|million|mm|M|K|thousand)?/i);
if (!m) return null;
let val = parseFloat(m[1]);
let unit = (m[2] || '').toUpperCase();
if (!unit) {
// Range like "$2.5 - $2.79B"
const range = s.match(/\$([\d.]+)\s*[-–]\s*\$?([\d.]+)\s*(billion|bn|B|million|mm|M|K|thousand)/i);
if (range) unit = range[3].toUpperCase();
}
if (unit === 'BILLION' || unit === 'BN' || unit === 'B') return val * 1000;
if (unit === 'MILLION' || unit === 'MM' || unit === 'M') return val;
if (unit === 'K' || unit === 'THOUSAND') return val / 1000;
// No unit — assume raw dollars
if (val >= 1000000) return val / 1000000;
if (val >= 1000) return val / 1000000;
return val;
}
function formatFunding(numM) {
if (numM == null) return '';
if (numM >= 1000) return '$' + (numM / 1000).toFixed(1).replace(/\.0$/, '') + 'B';
if (numM >= 1) return '$' + numM.toFixed(1).replace(/\.0$/, '') + 'M';
return '$' + Math.round(numM * 1000) + 'K';
}
function relativeTime(iso) {
if (!iso) return '';
const then = new Date(iso).getTime();
if (isNaN(then)) return '';
const diff = (Date.now() - then) / 1000;
if (diff < 60) return 'just now';
if (diff < 3600) return Math.floor(diff/60) + 'm ago';
if (diff < 86400) return Math.floor(diff/3600) + 'h ago';
if (diff < 2592000) return Math.floor(diff/86400) + 'd ago';
return new Date(iso).toLocaleDateString();
}
// ===== Filters =====
function buildFilters() {
const categories = [...new Set(allData.map(d => d.category).filter(Boolean))].sort();
const stageOrder = ['Pre-seed','Seed','Early Stage','Pre-A','Series A','Series B','Series C','Series D','Series E','Series F','Growth','Public','Acquired','Bootstrapped','Unknown'];
const stages = stageOrder.filter(s => allData.some(d => d._stage === s));
const catContainer = document.getElementById('category-pills');
catContainer.innerHTML = '';
categories.forEach(cat => {
const btn = document.createElement('button');
btn.className = 'pill pill-inactive';
btn.dataset.filter = cat;
btn.onclick = () => toggleFilter('category', cat);
catContainer.appendChild(btn);
});
const stageContainer = document.getElementById('stage-pills');
stageContainer.innerHTML = '';
stages.forEach(s => {
const btn = document.createElement('button');
btn.className = 'pill pill-inactive';
btn.dataset.filter = s;
btn.onclick = () => toggleFilter('stage', s);
stageContainer.appendChild(btn);
});
}
function updatePillCounts() {
document.querySelectorAll('#category-pills .pill').forEach(btn => {
const cat = btn.dataset.filter;
const count = allData.filter(d => d.category === cat).length;
btn.textContent = cat + ' (' + count + ')';
btn.className = activeCategories.has(cat) ? 'pill pill-active' : 'pill pill-inactive';
});
document.querySelectorAll('#stage-pills .pill').forEach(btn => {
const s = btn.dataset.filter;
const count = allData.filter(d => d._stage === s).length;
btn.textContent = s + ' (' + count + ')';
btn.className = activeStages.has(s) ? 'pill pill-active' : 'pill pill-inactive';
});
}
function toggleFilter(type, value) {
const set = type === 'category' ? activeCategories : activeStages;
if (set.has(value)) set.delete(value); else set.add(value);
render();
}
function toggleStarredFilter() {
starredOnly = !starredOnly;
const btn = document.getElementById('starred-filter');
btn.className = starredOnly ? 'pill pill-active inline-flex items-center gap-1' : 'pill pill-inactive inline-flex items-center gap-1';
render();
}
function clearAllFilters() {
activeCategories.clear();
activeStages.clear();
starredOnly = false;
document.getElementById('search').value = '';
document.getElementById('score-lo').value = 5;
document.getElementById('score-hi').value = 10;
document.getElementById('score-val').textContent = '5 – 10';
document.getElementById('score-track-active').style.left = '0%';
document.getElementById('score-track-active').style.right = '0%';
document.getElementById('funding-lo').value = 0;
document.getElementById('funding-hi').value = 9;
document.getElementById('funding-val').textContent = 'Any';
document.getElementById('funding-track-active').style.left = '0%';
document.getElementById('funding-track-active').style.right = '0%';
document.getElementById('starred-filter').className = 'pill pill-inactive inline-flex items-center gap-1';
render();
}
// ===== Star / save =====
function toggleStar(name) {
if (starred[name]) delete starred[name]; else starred[name] = true;
fetch('/api/scans/' + currentScanId + '/star', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(starred),
}).catch(()=>{});
updateStarredCount();
render();
}
function updateStarredCount() {
const el = document.getElementById('starred-count');
if (el) el.textContent = Object.keys(starred).length;
}
function exportStarred() {
const items = allData.filter(d => starred[d.name]);
if (!items.length) { alert('No starred companies to export.'); return; }
const headers = ['name','category','stage','funding','relevance','url','reason'];
const csv = [headers.join(',')];
items.forEach(d => {
csv.push(headers.map(h => '"' + String(d[h]||'').replace(/"/g,'""') + '"').join(','));
});
const blob = new Blob([csv.join('\n')], { type: 'text/csv' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = (currentScanId || 'scout') + '_starred.csv';
a.click();
}
// ===== Render =====
function render() {
const query = (document.getElementById('search')?.value || '').toLowerCase();
const scoreLo = parseInt(document.getElementById('score-lo').value);
const scoreHi = parseInt(document.getElementById('score-hi').value);
const fundingLo = parseInt(document.getElementById('funding-lo').value);
const fundingHi = parseInt(document.getElementById('funding-hi').value);
let filtered = allData.filter(d => {
if (d.relevance < scoreLo || d.relevance > scoreHi) return false;
if (starredOnly && !starred[d.name]) return false;
if (activeCategories.size && !activeCategories.has(d.category)) return false;
if (activeStages.size && !activeStages.has(d._stage)) return false;
if (fundingLo > 0 || fundingHi < 9) {
if (d._fundingNum == null) return false;
if (fundingLo > 0 && d._fundingNum < FUNDING_STEPS[fundingLo]) return false;
if (fundingHi < 9 && d._fundingNum > FUNDING_STEPS[fundingHi + 1]) return false;
}
if (query) {
const text = [d.name, d.description, d.reason, d.category, d.stage, d.type].join(' ').toLowerCase();
if (!text.includes(query)) return false;
}
return true;
});