-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlearn-module.js
More file actions
4637 lines (4123 loc) · 311 KB
/
Copy pathlearn-module.js
File metadata and controls
4637 lines (4123 loc) · 311 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
/**
* Learn Module - Creative Asset Validator v3.0.7
* Knowledge Intelligence with URL Analyzer, Competitor Tracking,
* Best Practices Library, Benchmarks Database, and Swipe File System
*
* v3.0.7 FIXES:
* - Auto-save to swipe file after URL analysis
* - Extract benchmarks from URL analysis automatically
* - Detect and track competitors from URL analysis
* - Persist all analysis history to localStorage and CRM
* - Link URL analyses to CRM companies
* - Show sources for benchmarks
*/
(function() {
'use strict';
const LEARN_VERSION = '3.3.0';
// User-specific storage key prefix - ROBUST multi-source check
function getLearnStoragePrefix() {
try {
// Try multiple session sources
let email = null;
// 1. Check window.cavUserSession
if (window.cavUserSession?.email) {
email = window.cavUserSession.email;
}
// 2. Check CAVSecurity SecureSessionManager
if (!email) {
const secureSession = window.CAVSecurity?.SecureSessionManager?.getSession?.();
if (secureSession?.email) email = secureSession.email;
}
// 3. Check localStorage cav_user_session
if (!email) {
try {
const session = JSON.parse(localStorage.getItem('cav_user_session') || 'null');
if (session?.email) email = session.email;
} catch (e) {}
}
// 4. Check localStorage cav_secure_session_v3
if (!email) {
try {
const secureV3 = JSON.parse(localStorage.getItem('cav_secure_session_v3') || 'null');
if (secureV3?.email) email = secureV3.email;
} catch (e) {}
}
// 5. Check localStorage cav_last_user_email
if (!email) {
const lastEmail = localStorage.getItem('cav_last_user_email');
if (lastEmail && lastEmail !== 'anonymous') email = lastEmail;
}
if (email) {
const userKey = email.toLowerCase().replace(/[^a-z0-9]/g, '_');
return `cav_learn_${userKey}_`;
}
} catch (e) {
console.warn('[Learn] Error getting user prefix:', e);
}
return 'cav_learn_anonymous_';
}
// Dynamic storage keys - user-specific
const STORAGE_KEYS = {
get SWIPE_FILE() { return `${getLearnStoragePrefix()}swipe_file`; },
get BENCHMARKS() { return `${getLearnStoragePrefix()}benchmarks`; },
get BEST_PRACTICES() { return `${getLearnStoragePrefix()}best_practices`; },
get URL_HISTORY() { return `${getLearnStoragePrefix()}url_history`; },
get COMPETITORS() { return `${getLearnStoragePrefix()}competitors`; },
};
// ============================================
// STANDARDIZED ICONS (SVG - No Emojis)
// ============================================
const ICONS = {
link: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',
image: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',
video: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>',
folder: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>',
book: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>',
chart: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>',
eye: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
search: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>',
target: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>',
lightbulb: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18h6M10 22h4M12 2a7 7 0 0 1 4 12.9V17a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2.1A7 7 0 0 1 12 2z"/></svg>',
hook: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/><path d="M8 12l2 2 4-4"/></svg>',
megaphone: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v-2a4 4 0 0 0-4-4H9l4-7"/><path d="M8 9v10c0 .55.45 1 1 1h2"/><line x1="3" y1="9" x2="3" y2="14"/></svg>',
palette: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="8" r="1.5"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/><circle cx="12" cy="16" r="1.5"/></svg>',
smartphone: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg>',
check: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
x: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
plus: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>',
trash: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',
refresh: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>',
copy: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',
save: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>',
upload: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>',
download: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
externalLink: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',
file: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>',
star: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>',
sparkle: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l1.5 5.5L19 10l-5.5 1.5L12 17l-1.5-5.5L5 10l5.5-1.5L12 3z"/></svg>',
building: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21h18M3 10h18M5 6l7-3 7 3M4 10v11M20 10v11M8 14v3M12 14v3M16 14v3"/></svg>',
clock: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
play: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>',
auto: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="3"/></svg>',
competitor: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>',
globe: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>',
compare: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg>',
chat: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
send: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>',
};
// ============================================
// STANDARDIZED STYLES
// ============================================
const STYLES = {
// Section headers
sectionHeader: 'margin: 0 0 var(--cav-space-4, 16px); color: var(--cav-text-primary, #fff); font-size: 1.125rem; font-weight: 600; font-family: var(--cav-font-sans, Inter, sans-serif); display: flex; align-items: center; gap: 8px;',
// Card containers
card: 'background: var(--cav-bg-card, #1a1a1a); border-radius: var(--cav-radius, 12px); padding: var(--cav-space-5, 20px); border: 1px solid var(--cav-glass-border, rgba(255,255,255,0.08));',
cardElevated: 'background: var(--cav-bg-elevated, #252525); border-radius: var(--cav-radius-sm, 10px); padding: var(--cav-space-4, 16px); border: 1px solid var(--cav-glass-border, rgba(255,255,255,0.08));',
// Text styles
textPrimary: 'color: var(--cav-text-primary, #fff); font-family: var(--cav-font-sans, Inter, sans-serif);',
textSecondary: 'color: var(--cav-text-secondary, #a1a1aa); font-family: var(--cav-font-sans, Inter, sans-serif);',
textMuted: 'color: var(--cav-text-muted, #71717a); font-family: var(--cav-font-sans, Inter, sans-serif);',
textLabel: 'color: var(--cav-text-muted, #71717a); font-size: 0.6875rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; font-family: var(--cav-font-sans, Inter, sans-serif);',
// Button base
btnBase: 'display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 10px 18px; border-radius: var(--cav-radius-sm, 10px); font-size: 0.875rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease; border: none; font-family: var(--cav-font-sans, Inter, sans-serif);',
btnPrimary: 'background: var(--cav-primary, #ec4899); color: #fff;',
btnSecondary: 'background: var(--cav-bg-elevated, #252525); border: 1px solid var(--cav-glass-border, rgba(255,255,255,0.08)); color: var(--cav-text-secondary, #a1a1aa);',
btnGhost: 'background: transparent; color: var(--cav-text-muted, #71717a); padding: 8px 14px;',
btnDanger: 'background: transparent; border: 1px solid var(--cav-error, #ef4444); color: var(--cav-error, #ef4444);',
btnSmall: 'padding: 6px 12px; font-size: 0.8125rem;',
// Input styles
input: 'width: 100%; padding: 12px 16px; background: var(--cav-bg-elevated, #252525); border: 1px solid var(--cav-glass-border, rgba(255,255,255,0.08)); border-radius: var(--cav-radius-sm, 10px); color: var(--cav-text-primary, #fff); font-size: 0.9375rem; font-family: var(--cav-font-sans, Inter, sans-serif); outline: none; transition: border-color 0.2s ease;',
select: 'padding: 10px 14px; background: var(--cav-bg-elevated, #252525); border: 1px solid var(--cav-glass-border, rgba(255,255,255,0.08)); border-radius: var(--cav-radius-sm, 10px); color: var(--cav-text-primary, #fff); font-size: 0.875rem; font-family: var(--cav-font-sans, Inter, sans-serif); cursor: pointer;',
// Badge styles
badge: 'display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 9999px; font-size: 0.6875rem; font-weight: 600; font-family: var(--cav-font-sans, Inter, sans-serif);',
badgeSuccess: 'background: var(--cav-success-bg, rgba(16,185,129,0.12)); color: var(--cav-success, #10b981);',
badgeWarning: 'background: var(--cav-warning-bg, rgba(245,158,11,0.12)); color: var(--cav-warning, #f59e0b);',
badgeError: 'background: var(--cav-error-bg, rgba(239,68,68,0.12)); color: var(--cav-error, #ef4444);',
badgeInfo: 'background: var(--cav-info-bg, rgba(59,130,246,0.12)); color: var(--cav-info, #3b82f6);',
badgePrimary: 'background: var(--cav-primary-soft, rgba(236,72,153,0.12)); color: var(--cav-primary, #ec4899);',
// Grid
grid: 'display: grid; gap: var(--cav-space-4, 16px);',
gridAuto: 'grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));',
// Flexbox
flexRow: 'display: flex; align-items: center; gap: var(--cav-space-3, 12px);',
flexCol: 'display: flex; flex-direction: column; gap: var(--cav-space-3, 12px);',
flexBetween: 'display: flex; align-items: center; justify-content: space-between; gap: var(--cav-space-3, 12px);',
flexWrap: 'flex-wrap: wrap;',
// Score display
scoreLarge: 'font-size: 2rem; font-weight: 700; font-family: var(--cav-font-sans, Inter, sans-serif);',
scoreGood: 'color: var(--cav-success, #10b981);',
scoreMedium: 'color: var(--cav-warning, #f59e0b);',
scoreLow: 'color: var(--cav-error, #ef4444);',
};
// ============================================
// LEARN MODULE CLASS
// ============================================
class LearnModule {
constructor() {
this.currentView = 'url-analyzer';
this.swipeFile = this.loadSwipeFile();
this.benchmarks = this.loadBenchmarks();
this.bestPractices = this.loadBestPractices();
this.urlAnalysisHistory = this.loadURLHistory();
this.detectedCompetitors = this.loadDetectedCompetitors();
this.comparisonImage = null; // Selected image for creative comparison
this.icons = ICONS; // Reference to icons
this.styles = STYLES; // Reference to styles
console.log(`[Learn] Initialized v${LEARN_VERSION} - ${this.swipeFile.length} swipes, ${this.benchmarks.length} benchmarks, ${this.urlAnalysisHistory.length} URL analyses`);
}
// Load URL analysis history
loadURLHistory() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEYS.URL_HISTORY) || '[]');
} catch {
return [];
}
}
// Save URL analysis to history
saveURLHistory(result) {
this.urlAnalysisHistory.unshift(result);
// Keep last 100 analyses
if (this.urlAnalysisHistory.length > 100) {
this.urlAnalysisHistory = this.urlAnalysisHistory.slice(0, 100);
}
localStorage.setItem(STORAGE_KEYS.URL_HISTORY, JSON.stringify(this.urlAnalysisHistory));
}
// Load detected competitors
loadDetectedCompetitors() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEYS.COMPETITORS) || '[]');
} catch {
return [];
}
}
// Save detected competitor
saveDetectedCompetitor(competitor) {
if (!competitor) return null;
// Check if already exists - with null safety
const competitorName = competitor.name || '';
const competitorDomain = competitor.domain || '';
const existing = this.detectedCompetitors.find(c => {
const cName = c?.name || '';
const cDomain = c?.domain || '';
return (cDomain && competitorDomain && cDomain === competitorDomain) ||
(cName && competitorName && cName.toLowerCase() === competitorName.toLowerCase());
});
if (!existing && competitorName) {
this.detectedCompetitors.push({
...competitor,
id: `comp_${Date.now()}`,
detectedAt: new Date().toISOString()
});
localStorage.setItem(STORAGE_KEYS.COMPETITORS, JSON.stringify(this.detectedCompetitors));
// Also add to CRM as a company if available
this.addCompetitorToCRM(competitor);
}
return competitor;
}
// Add competitor to CRM
async addCompetitorToCRM(competitor) {
if (!window.cavCRM) return;
try {
// Check if company already exists
const existingCompanies = window.cavCRM.getAllCompanies({ search: competitor.name });
if (existingCompanies.length > 0) {
console.log(`[Learn] Company ${competitor.name} already exists in CRM`);
return existingCompanies[0];
}
// Create new company
const company = window.cavCRM.createCompany({
name: competitor.name,
domain: competitor.domain,
website: competitor.website || `https://${competitor.domain}`,
industry: competitor.industry || 'Unknown',
type: 'competitor',
description: `Auto-detected competitor from URL analysis`,
tags: ['competitor', 'auto-detected'],
source: 'url_analyzer'
});
console.log(`[Learn] Created CRM company for competitor: ${competitor.name}`);
return company;
} catch (e) {
console.warn('[Learn] Failed to add competitor to CRM:', e);
}
}
// ============================================
// URL ANALYZER
// ============================================
async analyzeURL(url, comparisonImage = null) {
const result = {
id: `url_${Date.now()}`,
url,
urlType: this.detectURLType(url),
analyzedAt: new Date().toISOString(),
creativeSummary: null,
hookAnalysis: null,
messageArchitecture: null,
visualStrategy: null,
ctaEvaluation: null,
platformOptimization: null,
performanceIndicators: null,
takeaways: [],
savedToSwipeFile: false,
comparisonResult: null,
// NEW: Additional extracted data
extractedBenchmarks: [],
detectedCompetitor: null,
linkedCompanyId: null,
sources: []
};
try {
const urlObj = new URL(url);
const domain = urlObj.hostname.replace('www.', '');
// Use SearchAPI to get page content and additional context
if (window.AIOrchestrator?.isProviderAvailable('searchapi')) {
// Get page info
const searchResult = await window.AIOrchestrator.callSearchAPI(`site:${domain}`, {
num: 3
});
result.pageSnippet = searchResult.results?.[0]?.snippet;
result.sources = searchResult.results?.map(r => ({
title: r.title,
url: r.link,
snippet: r.snippet
})) || [];
// Search for company/brand info
const brandSearch = await window.AIOrchestrator.callSearchAPI(`${domain} company about`, {
num: 3
});
result.brandSources = brandSearch.results?.map(r => ({
title: r.title,
url: r.link,
snippet: r.snippet
})) || [];
}
// Use Claude/Gemini for deep analysis
const analysis = await this.getEnhancedURLAnalysis(url, result.urlType, result.sources);
Object.assign(result, analysis);
// AUTO-DETECT BRAND (NOT competitor - this is the analyzed brand/client)
if (analysis.detectedBrand && analysis.detectedBrand !== 'unknown') {
// This is the BRAND being analyzed - add as CLIENT, not competitor
const brand = {
name: analysis.detectedBrand,
domain: domain,
website: `https://${domain}`,
industry: analysis.creativeSummary?.industry || analysis.detectedIndustry || 'Unknown',
advertisingChannels: analysis.platformOptimization?.detectedChannels || [],
messageThemes: analysis.messageArchitecture?.supporting || []
};
// Save brand as a company/client (NOT competitor)
result.detectedBrand = brand;
// Link to CRM as CLIENT
if (window.cavCRM) {
let companyId = null;
const companies = window.cavCRM.getAllCompanies({ search: brand.name });
if (companies.length > 0) {
companyId = companies[0].id;
} else {
// Create as CLIENT, not competitor
const newCompany = window.cavCRM.createCompany({
name: brand.name,
domain: brand.domain,
website: brand.website,
industry: brand.industry,
type: 'client', // IMPORTANT: Client, not competitor!
description: `Auto-detected from URL analysis: ${url}`,
tags: ['auto-detected', 'url-analysis']
});
companyId = newCompany.id;
console.log(`[Learn] Created company for brand: ${brand.name}`);
}
result.linkedCompanyId = companyId;
}
// NOW auto-fetch actual competitors for this brand
result.competitors = await this.autoFetchCompetitors(brand.name, brand.industry);
}
// AUTO-EXTRACT BENCHMARKS from the analysis
if (analysis.performanceIndicators) {
await this.extractAndSaveBenchmarks(analysis, domain);
result.extractedBenchmarks = analysis.extractedBenchmarks || [];
}
// If comparison image is provided, run comparison analysis
if (comparisonImage) {
result.comparisonResult = await this.compareCreatives(result, comparisonImage);
}
// AUTO-SAVE to URL history
this.saveURLHistory(result);
// AUTO-SAVE to swipe file with analysis data
this.autoSaveToSwipeFile(result);
} catch (error) {
console.error('[Learn] URL analysis error:', error);
result.error = error.message;
}
return result;
}
// AUTO-FETCH COMPETITORS for a brand using AI (3 competitors)
async autoFetchCompetitors(brandName, industry) {
if (!brandName || brandName === 'unknown') return [];
console.log(`[Learn] Auto-fetching competitors for ${brandName} in ${industry}`);
const competitors = [];
try {
// First, use SearchAPI to find competitors
if (window.AIOrchestrator?.callSearchAPI) {
const searchResults = await window.AIOrchestrator.callSearchAPI(
`${brandName} competitors ${industry} alternative companies`,
{ num: 10 }
);
// Use AI to extract competitors from search results
if (searchResults.results?.length > 0 && window.AIOrchestrator?.callAI) {
const prompt = `Based on these search results, identify the TOP 3 main competitors of ${brandName} in the ${industry || 'same'} industry.
Search Results:
${searchResults.results.map(r => `- ${r.title}: ${r.snippet}`).join('\n')}
Return ONLY a JSON array with exactly 3 competitors. Each competitor should have:
- name: Company name
- website: Website URL if found
- description: Brief 1-sentence description
- strengths: Array of 2-3 key strengths
- marketPosition: "leader", "challenger", "niche", or "emerging"
Example format:
[{"name":"CompanyA","website":"https://companya.com","description":"Leading provider...","strengths":["Innovation","Price"],"marketPosition":"leader"}]
JSON only, no markdown:`;
const aiResponse = await window.AIOrchestrator.callAI(prompt, {
model: 'claude',
format: 'json'
});
// Parse competitors from AI response
let parsedCompetitors = [];
try {
const jsonMatch = aiResponse.match(/\[[\s\S]*?\]/);
if (jsonMatch) {
parsedCompetitors = JSON.parse(jsonMatch[0]);
}
} catch (e) {
console.warn('[Learn] Failed to parse competitor JSON:', e);
}
// Save each competitor to CRM
for (const comp of parsedCompetitors.slice(0, 3)) {
const savedCompetitor = this.saveCompetitorToCRM(comp, brandName, industry);
if (savedCompetitor) {
competitors.push(savedCompetitor);
}
}
}
}
// Fallback: Use Gemini for competitor detection if SearchAPI unavailable
if (competitors.length === 0 && window.AIOrchestrator?.callAI) {
const fallbackPrompt = `Name the top 3 direct competitors of ${brandName} in the ${industry || 'technology'} industry.
Return ONLY a JSON array with 3 competitors:
[{"name":"Company Name","description":"Brief description","marketPosition":"leader/challenger/niche"}]
JSON only:`;
const fallbackResponse = await window.AIOrchestrator.callAI(fallbackPrompt, {
model: 'gemini',
format: 'json'
});
try {
const jsonMatch = fallbackResponse.match(/\[[\s\S]*?\]/);
if (jsonMatch) {
const fallbackCompetitors = JSON.parse(jsonMatch[0]);
for (const comp of fallbackCompetitors.slice(0, 3)) {
const savedCompetitor = this.saveCompetitorToCRM(comp, brandName, industry);
if (savedCompetitor) {
competitors.push(savedCompetitor);
}
}
}
} catch (e) {
console.warn('[Learn] Fallback competitor parsing failed:', e);
}
}
console.log(`[Learn] Found ${competitors.length} competitors for ${brandName}`);
} catch (error) {
console.error('[Learn] Error fetching competitors:', error);
}
return competitors;
}
// Save competitor to CRM (separate from companies!)
saveCompetitorToCRM(competitor, relatedBrandName, industry) {
if (!competitor?.name) return null;
try {
// Use the CRM's competitor management (separate from companies)
if (window.cavCRM?.createCompetitor) {
// Check if competitor already exists
const existing = window.cavCRM.getAllCompetitors({ search: competitor.name });
if (existing.length > 0) {
// Update existing
return window.cavCRM.updateCompetitor(existing[0].id, {
...competitor,
lastChecked: new Date().toISOString()
});
}
// Create new competitor
return window.cavCRM.createCompetitor({
name: competitor.name,
website: competitor.website || '',
industry: industry || competitor.industry || 'Unknown',
description: competitor.description || `Competitor of ${relatedBrandName}`,
strengths: competitor.strengths || [],
marketShare: competitor.marketPosition || '',
source: 'ai_detected',
notes: `Auto-detected as competitor of ${relatedBrandName}`
});
}
// Fallback: Save to detected competitors storage
const detected = {
id: `comp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
name: competitor.name,
website: competitor.website || '',
industry: industry,
description: competitor.description,
strengths: competitor.strengths || [],
marketPosition: competitor.marketPosition,
relatedTo: relatedBrandName,
detectedAt: new Date().toISOString(),
source: 'ai_detected'
};
this.saveDetectedCompetitor(detected);
return detected;
} catch (e) {
console.warn('[Learn] Failed to save competitor:', e);
return null;
}
}
// Enhanced URL analysis that extracts more data - with VISUAL analysis for images
async getEnhancedURLAnalysis(url, urlType, sources = []) {
const sourcesContext = sources.length > 0 ?
`\nRelated search results:\n${sources.map(s => `- ${s.title}: ${s.snippet}`).join('\n')}` : '';
const isImageUrl = urlType === 'image' || url.match(/\.(jpg|jpeg|png|gif|webp)$/i);
const prompt = isImageUrl ?
`You are an expert creative strategist and visual analyst. Analyze this image in comprehensive detail for advertising and marketing intelligence.
Provide a THOROUGH analysis covering:
1. **Visual Elements**: Describe everything you see - subjects, objects, colors, composition, typography, logos
2. **Brand Detection**: What company/brand is this from? Look for logos, watermarks, brand colors
3. **Creative Type**: Is this a product shot, lifestyle image, ad creative, social post, infographic?
4. **Message Analysis**: What is the primary message? What emotions does it evoke?
5. **Target Audience**: Who is this creative designed to appeal to?
6. **Visual Quality**: Professional quality assessment (lighting, composition, focus, color grading)
7. **Hook/Attention**: What grabs attention first? Rate the "thumb-stop" potential 0-100
8. **CTA Presence**: Any call-to-action visible? Text overlays?
9. **Platform Fit**: Which platforms would this work best on? (Instagram, Facebook, LinkedIn, etc.)
10. **Strengths**: What works well about this creative?
11. **Improvements**: What could be improved?
12. **Similar Examples**: What style/trend does this follow?
Return ONLY valid JSON with this structure:
{
"detectedBrand": "Brand Name or unknown",
"detectedIndustry": "Industry name",
"visualDescription": "Detailed description of what's in the image",
"creativeType": "product_shot/lifestyle/ad_creative/social_post/infographic/other",
"creativeSummary": {
"product": "Product/service shown",
"keyMessage": "Main value proposition or message",
"targetAudience": "Who this is designed for",
"industry": "Industry",
"emotionalTone": "Emotions evoked"
},
"hookAnalysis": {
"score": 75,
"element": "What grabs attention first",
"effectiveness": "Why it works or doesn't",
"thumbStopPotential": "high/medium/low"
},
"visualStrategy": {
"colors": ["#hex1", "#hex2", "#hex3"],
"colorMood": "Warm/Cool/Neutral/Vibrant",
"imageryApproach": "Lifestyle/Product/Abstract/UGC/Professional",
"composition": "Layout and composition analysis",
"typography": "Any text styles observed",
"qualityScore": 85
},
"ctaEvaluation": {
"present": true,
"text": "CTA text if visible",
"type": "hard/soft/engagement/none",
"clarity": 80,
"urgency": 60,
"visibility": "prominent/subtle/none"
},
"platformOptimization": {
"bestPlatforms": ["Instagram", "Facebook"],
"aspectRatio": "1:1/4:5/16:9/9:16/other",
"platformScores": {"instagram": 85, "facebook": 80, "linkedin": 70, "tiktok": 60},
"improvements": ["Suggestion 1", "Suggestion 2"]
},
"performanceIndicators": {
"qualitySignals": ["High production value", "Professional lighting"],
"weaknesses": ["Low contrast", "Busy composition"],
"predictedEngagement": "high/medium/low"
},
"benchmarkEstimates": {
"ctr": {"low": 0.5, "expected": 1.2, "high": 2.5},
"engagementRate": {"low": 1.5, "expected": 3.0, "high": 5.5}
},
"strengths": ["Strength 1", "Strength 2", "Strength 3"],
"improvements": ["Improvement 1", "Improvement 2", "Improvement 3"],
"takeaways": [
"Actionable insight 1",
"Actionable insight 2",
"Actionable insight 3",
"Actionable insight 4"
]
}`
: `Analyze this URL for creative intelligence. Extract as much information as possible.
URL: ${url}
URL Type: ${urlType}
${sourcesContext}
Provide comprehensive analysis including:
1. **Brand Detection**: What company/brand is this from? Identify the exact brand name.
2. **Industry**: What industry is this in?
3. **Creative Summary**: Product, key message, target audience
4. **Hook Analysis**: Attention-grabbing elements, score 0-100
5. **Message Architecture**: Primary message, supporting points, proof points
6. **Visual Strategy**: Colors, imagery approach, composition
7. **CTA Evaluation**: Call-to-action presence, clarity (0-100), urgency (0-100)
8. **Platform Optimization**: Detected channels, optimization score
9. **Performance Indicators**: Quality signals, estimated metrics
10. **Key Takeaways**: 3-5 actionable insights
11. **Benchmark Estimates**: CTR range, CPM range, engagement rate range (based on industry/platform)
Return ONLY valid JSON:
{
"detectedBrand": "Brand Name or unknown",
"detectedIndustry": "Industry name",
"creativeSummary": {
"product": "Product/service",
"keyMessage": "Main value proposition",
"targetAudience": "Who this is for",
"industry": "Industry"
},
"hookAnalysis": {
"score": 75,
"element": "What grabs attention",
"effectiveness": "Why it works"
},
"messageArchitecture": {
"primary": "Main message",
"supporting": ["Point 1", "Point 2"],
"proofPoints": ["Social proof", "Statistics"]
},
"visualStrategy": {
"colors": ["#hex1", "#hex2"],
"imageryApproach": "Lifestyle/Product/Abstract",
"composition": "Layout description"
},
"ctaEvaluation": {
"present": true,
"text": "CTA text",
"type": "hard/soft/engagement",
"clarity": 80,
"urgency": 60
},
"platformOptimization": {
"detectedChannels": ["Facebook", "Google"],
"platform": "Primary platform",
"optimizationScore": 70,
"improvements": ["Suggestion 1"]
},
"performanceIndicators": {
"qualitySignals": ["High production value"],
"engagementSignals": ["Active comments"]
},
"benchmarkEstimates": {
"ctr": {"low": 0.5, "expected": 1.2, "high": 2.5},
"cpm": {"low": 5, "expected": 12, "high": 25},
"engagementRate": {"low": 1.5, "expected": 3.0, "high": 5.5}
},
"takeaways": [
"Actionable insight 1",
"Actionable insight 2",
"Actionable insight 3"
]
}`;
try {
let result;
const apiKey = localStorage.getItem('cav_gemini_api_key');
if (apiKey) {
// Build request parts
const parts = [{ text: prompt }];
// For image URLs, fetch and include the actual image for visual analysis
if (isImageUrl) {
try {
console.log('[Learn] Fetching image for visual analysis:', url);
const imageResponse = await fetch(url);
const blob = await imageResponse.blob();
const base64 = await this.blobToBase64(blob);
const mimeType = blob.type || 'image/jpeg';
parts.push({
inline_data: {
mime_type: mimeType,
data: base64.split(',')[1] // Remove data URL prefix
}
});
console.log('[Learn] Image loaded for analysis, size:', blob.size);
} catch (imgError) {
console.warn('[Learn] Could not fetch image, using text-only analysis:', imgError);
}
}
// Use Gemini for analysis (vision model for images)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${apiKey}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts }],
generationConfig: { temperature: 0.3, maxOutputTokens: 4000 }
})
}
);
const data = await response.json();
const text = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
result = this.parseJSON(text);
// Store thumbnail for swipe file
if (isImageUrl) {
result.thumbnailData = url;
}
} else if (window.AIOrchestrator?.isProviderAvailable('claude')) {
const claudeResult = await window.AIOrchestrator.callClaude(prompt, { temperature: 0.3 });
result = this.parseJSON(claudeResult.content);
}
return result || {};
} catch (e) {
console.error('[Learn] Enhanced analysis error:', e);
return {};
}
}
// Helper to convert blob to base64
blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
// Extract benchmarks from analysis and save them
async extractAndSaveBenchmarks(analysis, sourceDomain) {
const benchmarks = [];
if (analysis.benchmarkEstimates) {
const be = analysis.benchmarkEstimates;
const platform = analysis.platformOptimization?.platform || 'all';
const industry = analysis.detectedIndustry || analysis.creativeSummary?.industry || null;
// Save CTR benchmark
if (be.ctr) {
const ctrBench = {
id: `bench_ctr_${Date.now()}`,
metric: 'ctr',
platform: platform,
industry: industry,
value: be.ctr,
source: `URL Analysis: ${sourceDomain}`,
sourceUrl: analysis.url,
lastUpdated: new Date().toISOString()
};
this.saveBenchmark(ctrBench);
benchmarks.push(ctrBench);
}
// Save CPM benchmark
if (be.cpm) {
const cpmBench = {
id: `bench_cpm_${Date.now()}`,
metric: 'cpm',
platform: platform,
industry: industry,
value: be.cpm,
source: `URL Analysis: ${sourceDomain}`,
sourceUrl: analysis.url,
lastUpdated: new Date().toISOString()
};
this.saveBenchmark(cpmBench);
benchmarks.push(cpmBench);
}
// Save engagement rate benchmark
if (be.engagementRate) {
const engBench = {
id: `bench_engagement_${Date.now()}`,
metric: 'engagement_rate',
platform: platform,
industry: industry,
value: be.engagementRate,
source: `URL Analysis: ${sourceDomain}`,
sourceUrl: analysis.url,
lastUpdated: new Date().toISOString()
};
this.saveBenchmark(engBench);
benchmarks.push(engBench);
}
}
analysis.extractedBenchmarks = benchmarks;
console.log(`[Learn] Extracted ${benchmarks.length} benchmarks from URL analysis`);
}
// Auto-save URL analysis to swipe file AND to CRM company
autoSaveToSwipeFile(result) {
if (result.error) return; // Don't save failed analyses
// Handle data URLs - they ARE the image/thumbnail
const isDataUrl = result.url?.startsWith('data:');
const thumbnailData = isDataUrl ? result.url : (result.thumbnailData || null);
// For display URL, truncate data URLs
let displayUrl = result.url;
let hostname = 'data-url';
if (!isDataUrl) {
try {
hostname = new URL(result.url).hostname;
} catch (e) {
hostname = 'unknown';
}
}
const swipeEntry = {
id: result.id,
source: 'url_analyzer',
sourceUrl: isDataUrl ? `Data URL (${result.urlType})` : result.url,
originalUrl: result.url, // Keep original for re-analysis
urlType: result.urlType,
title: result.creativeSummary?.keyMessage?.substring(0, 50) || `Analysis: ${hostname}`,
thumbnailData: thumbnailData,
analysis: {
creativeSummary: result.creativeSummary,
hookAnalysis: result.hookAnalysis,
ctaEvaluation: result.ctaEvaluation,
visualStrategy: result.visualStrategy,
platformOptimization: result.platformOptimization,
strengths: result.strengths,
improvements: result.improvements,
takeaways: result.takeaways,
visualDescription: result.visualDescription
},
tags: [
result.urlType,
result.detectedBrand?.name || result.detectedBrand,
result.detectedIndustry,
...(result.platformOptimization?.detectedChannels || result.platformOptimization?.bestPlatforms || [])
].filter(Boolean),
collections: ['Auto-Saved URL Analyses'],
notes: result.creativeSummary?.keyMessage || result.takeaways?.[0] || '',
savedAt: new Date().toISOString(),
savedBy: 'auto',
isCompetitor: !!result.detectedCompetitor,
competitorId: result.detectedCompetitor?.id,
linkedCompanyId: result.linkedCompanyId,
sources: result.sources
};
// Save to swipe file
this.swipeFile.unshift(swipeEntry);
localStorage.setItem(STORAGE_KEYS.SWIPE_FILE, JSON.stringify(this.swipeFile));
// Also save to unified storage for cross-device sync
if (window.UnifiedStorage) {
window.UnifiedStorage.saveSwipeFile(swipeEntry).catch(e => console.warn('[Learn] Unified storage save failed:', e));
window.UnifiedStorage.saveURLAnalysis(result).catch(e => console.warn('[Learn] URL analysis save failed:', e));
}
result.savedToSwipeFile = true;
console.log(`[Learn] Auto-saved URL analysis to swipe file: ${result.url}`);
// ALSO SAVE TO CRM COMPANY if linked
if (result.linkedCompanyId && window.cavCRM) {
try {
// Save swipe file entry to company
window.cavCRM.addSwipeFileToCompany(result.linkedCompanyId, swipeEntry);
// Save URL analysis to company
window.cavCRM.addURLAnalysisToCompany(result.linkedCompanyId, {
id: result.id,
url: result.url,
urlType: result.urlType,
analyzedAt: result.analyzedAt,
creativeSummary: result.creativeSummary,
hookAnalysis: result.hookAnalysis,
ctaEvaluation: result.ctaEvaluation,
performanceIndicators: result.performanceIndicators,
takeaways: result.takeaways
});
// Save benchmarks to company if any
if (result.extractedBenchmarks?.length > 0) {
for (const benchmark of result.extractedBenchmarks) {
window.cavCRM.addBenchmarkToCompany(result.linkedCompanyId, benchmark);
}
}
// Save best practices extracted from analysis
if (result.takeaways?.length > 0) {
for (const takeaway of result.takeaways.slice(0, 5)) {
window.cavCRM.addBestPracticeToCompany(result.linkedCompanyId, {
category: result.urlType || 'General',
practice: takeaway,
source: result.url,
extractedAt: new Date().toISOString()
});
}
}
// Save detected competitors to the company
if (result.competitors?.length > 0) {
for (const competitor of result.competitors) {
window.cavCRM.addCompetitorToCompany(result.linkedCompanyId, competitor);
}
}
console.log(`[Learn] Saved URL analysis data to CRM company: ${result.linkedCompanyId}`);
} catch (e) {
console.warn('[Learn] Failed to save to CRM company:', e);
}
}
}
// Compare user's creative against URL analysis
async compareCreatives(urlAnalysis, userImage) {
const comparison = {
overallScore: 0,
strengths: [],
improvements: [],
detailedComparison: {}
};
try {
const imageData = userImage.thumbnail_url || userImage.dataUrl || '';
if (!imageData) return comparison;
// Use Gemini or Claude for visual comparison
const apiKey = localStorage.getItem('cav_gemini_api_key');
if (apiKey && imageData.startsWith('data:')) {
const cleanBase64 = imageData.replace(/^data:image\/[a-z]+;base64,/, '');
const mimeType = imageData.match(/^data:(image\/[a-z]+);base64,/)?.[1] || 'image/jpeg';
const prompt = `You are a creative director comparing a user's creative asset against competitor insights.
URL Analysis Summary:
- Product/Service: ${urlAnalysis.creativeSummary?.product || 'Unknown'}
- Key Message: ${urlAnalysis.creativeSummary?.keyMessage || 'Unknown'}
- Target Audience: ${urlAnalysis.creativeSummary?.targetAudience || 'Unknown'}
- Hook Score: ${urlAnalysis.hookAnalysis?.score || 'N/A'}
- Visual Strategy: ${urlAnalysis.visualStrategy?.imageryApproach || 'Unknown'}
- CTA: ${urlAnalysis.ctaEvaluation?.type || 'Unknown'}
Analyze the uploaded image and compare it against the competitor creative insights:
1. **Overall Score (0-100)**: How well does this creative compete?
2. **Strengths**: What does this creative do well compared to competitor insights?
3. **Improvements**: What could be improved based on competitor best practices?
4. **Detailed Comparison**:
- Hook Comparison: How does the attention-grabbing element compare?
- Message Clarity: Is the value proposition clear?
- Visual Quality: Professional quality comparison