-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
679 lines (624 loc) · 34.8 KB
/
Copy pathcontent.js
File metadata and controls
679 lines (624 loc) · 34.8 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
/* Lens v4 — content.js — clean rebuild */
/* ── Provider utilities in global scope ─────────────────────────────── */
window.LensProviders = {
groq: { name:'Groq', format:'openai', model:'llama-3.3-70b-versatile', endpoint:'https://api.groq.com/openai/v1/chat/completions', headers: k=>({'Content-Type':'application/json','Authorization':'Bearer '+k}) },
openai: { name:'OpenAI', format:'openai', model:'gpt-4o-mini', endpoint:'https://api.openai.com/v1/chat/completions', headers: k=>({'Content-Type':'application/json','Authorization':'Bearer '+k}) },
anthropic: { name:'Anthropic', format:'anthropic', model:'claude-haiku-4-5-20251001', endpoint:'https://api.anthropic.com/v1/messages', headers: k=>({'Content-Type':'application/json','x-api-key':k,'anthropic-version':'2023-06-01','anthropic-dangerous-direct-browser-access':'true'}) },
gemini: { name:'Gemini', format:'gemini', model:'gemini-1.5-flash', endpoint: k=>'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key='+k, headers:()=>({'Content-Type':'application/json'}) },
mistral: { name:'Mistral', format:'openai', model:'mistral-small-latest', endpoint:'https://api.mistral.ai/v1/chat/completions', headers: k=>({'Content-Type':'application/json','Authorization':'Bearer '+k}) },
together: { name:'Together AI', format:'openai', model:'meta-llama/Llama-3-70b-chat-hf', endpoint:'https://api.together.xyz/v1/chat/completions', headers: k=>({'Content-Type':'application/json','Authorization':'Bearer '+k}) },
};
window.lensDetect = function(key) {
if (!key) return null;
const k = key.trim();
if (k.startsWith('gsk_')) return 'groq';
if (k.startsWith('sk-ant-')) return 'anthropic';
if (k.startsWith('AIza')) return 'gemini';
if (k.startsWith('sk-')) return 'openai';
if (/^[a-f0-9]{64}$/i.test(k)) return 'together';
if (/^[A-Za-z0-9]{32}$/.test(k)) return 'mistral';
return null;
};
window.lensCall = async function(key, messages, jsonMode) {
const pk = window.lensDetect(key);
if (!pk) throw new Error('UNKNOWN_PROVIDER');
const p = window.LensProviders[pk];
if (p.format === 'openai') {
const body = { model:p.model, temperature:0.1, max_tokens:1400, messages };
if (jsonMode && pk !== 'together') body.response_format = { type:'json_object' };
const res = await fetch(p.endpoint, { method:'POST', headers:p.headers(key), body:JSON.stringify(body) });
if (res.status === 401) throw new Error('INVALID_KEY');
if (res.status === 429) throw new Error('RATE_LIMIT');
if (!res.ok) throw new Error('API_'+res.status);
const d = await res.json();
return d.choices?.[0]?.message?.content || '';
}
if (p.format === 'anthropic') {
const system = messages.find(m=>m.role==='system')?.content || 'Return only valid JSON.';
const userMsgs = messages.filter(m=>m.role!=='system');
const res = await fetch(p.endpoint, { method:'POST', headers:p.headers(key), body:JSON.stringify({ model:p.model, max_tokens:1400, system, messages:userMsgs }) });
if (res.status === 401) throw new Error('INVALID_KEY');
if (res.status === 429) throw new Error('RATE_LIMIT');
if (!res.ok) throw new Error('API_'+res.status);
const d = await res.json();
return d.content?.[0]?.text || '';
}
if (p.format === 'gemini') {
const ep = typeof p.endpoint === 'function' ? p.endpoint(key) : p.endpoint;
const combined = messages.map(m=>m.content).join('\n\n');
const res = await fetch(ep, { method:'POST', headers:p.headers(key), body:JSON.stringify({ contents:[{ parts:[{ text:combined }] }], generationConfig:{ temperature:0.1, maxOutputTokens:1400 } }) });
if (res.status === 400) throw new Error('INVALID_KEY');
if (res.status === 429) throw new Error('RATE_LIMIT');
if (!res.ok) throw new Error('API_'+res.status);
const d = await res.json();
return d.candidates?.[0]?.content?.parts?.[0]?.text || '';
}
throw new Error('UNSUPPORTED_FORMAT');
};
window.lensParseJSON = function(text) {
return JSON.parse(text.replace(/```json|```/g,'').trim());
};
window.lensGetKey = async function() {
return new Promise(resolve => {
chrome.storage.local.get(['pn_api_key','pn_api_valid','pn_ai_enabled'], d => {
const key = d.pn_api_key || '';
const valid = !!d.pn_api_valid;
const enabled = d.pn_ai_enabled !== false && valid;
window.__pn_api_key = key;
window.__pn_api_valid = valid;
window.__pn_ai_enabled = enabled;
resolve(enabled ? key : ''); // return empty if disabled
});
});
};
/* ── Main extension IIFE ─────────────────────────────────────────────── */
(function () {
'use strict';
if (document.getElementById('pagenav-fab')) return;
/* ── Site groups ── */
const SITE_GROUPS = {
amazon: [
{ label:'Product images', icon:'🖼️', q:['#imgTagWrapperId','#imageBlock','#imageBlock_feature_div'] },
{ label:'Price & offers', icon:'💰', q:['#corePrice_feature_div','#corePriceDisplay_desktop_feature_div','#apex_desktop'] },
{ label:'Add to cart', icon:'🛒', q:['#desktop_buybox_feature_div','#buybox','#addToCart'] },
{ label:'Product description', icon:'📝', q:['#feature-bullets','#featurebullets_feature_div'] },
{ label:'Product overview', icon:'📋', q:['#productOverview_feature_div','#productDescription_feature_div'] },
{ label:'Specifications', icon:'⚙️', q:['#productDetails_techSpec_section_1','#productDetails_feature_div','#tech-specs-section'] },
{ label:'A+ brand content', icon:'🏷️', q:['#aplus','#aplus3p_feature_div'] },
{ label:'Customer Q&A', icon:'❓', q:['#askATF','#ask-feature-div'] },
{ label:'Customer reviews', icon:'⭐', q:['#customerReviews','#reviewsMedley','#cm_cr_dp_d_rating_histogram'] },
{ label:'Related products', icon:'🔗', q:['#desktop-sims-feature-div','#sp-detail-atf'] },
{ label:'Delivery & returns', icon:'🚚', q:['#mir-layout-DELIVERY_BLOCK','#deliveryBlockMessage'] },
{ label:'Seller information', icon:'🏪', q:['#merchant-info','#tabular-buybox'] },
],
flipkart: [
{ label:'Product images', icon:'🖼️', q:['._3kidJX','._2r_T1I','[class*="image-block"]'] },
{ label:'Price & offers', icon:'💰', q:['._30jeq3','._16Jk6d','._1vC4OE'] },
{ label:'Bank offers & EMI', icon:'💳', q:['._3xFRSH','[class*="offer"]'] },
{ label:'Delivery details', icon:'🚚', q:['._2Tpdn3','[class*="delivery"]'] },
{ label:'Product highlights', icon:'✨', q:['._2418kt','[class*="Highlights"]'] },
{ label:'All details', icon:'📝', q:['._1AN87F','[class*="AllDetails"]'] },
{ label:'Ratings & reviews', icon:'⭐', q:['._3LWZlK','._1YokD2','._3HqJxg'] },
{ label:'Questions & answers', icon:'❓', q:['[class*="QnA"]','._3yFrcC'] },
{ label:'Similar products', icon:'🔗', q:['[class*="Similar"]','._2-y4Fk'] },
],
myntra: [
{ label:'Product images', icon:'🖼️', q:['.image-grid-container','[class*="image-grid"]'] },
{ label:'Price & buy', icon:'💰', q:['.pdp-price','[class*="pdp-price"]'] },
{ label:'Delivery & returns', icon:'🚚', q:['.delivery-section','[class*="delivery"]'] },
{ label:'Product summary', icon:'📝', q:['.pdp-product-description-content','[class*="product-description"]'] },
{ label:'Size & fit', icon:'📐', q:['.size-buttons-container','[class*="size-fit"]'] },
{ label:'Ratings & reviews', icon:'⭐', q:['.detailed-reviews','[class*="ratingSection"]'] },
{ label:'Similar products', icon:'🔗', q:['[class*="similar-products"]','[class*="recommendation"]'] },
],
meesho: [
{ label:'Product images', icon:'🖼️', q:['[class*="ProductImage"]','[class*="CarouselImage"]'] },
{ label:'Price & buy', icon:'💰', q:['[class*="PriceContainer"]','[class*="BuyNow"]'] },
{ label:'Product highlights', icon:'✨', q:['[class*="Highlights"]','[class*="ProductHighlight"]'] },
{ label:'Additional details', icon:'📋', q:['[class*="AdditionalDetail"]'] },
{ label:'Sold by', icon:'🏪', q:['[class*="SellerInfo"]','[class*="SoldBy"]'] },
{ label:'Ratings & reviews', icon:'⭐', q:['[class*="RatingReview"]','[class*="ReviewContainer"]'] },
{ label:'People also viewed', icon:'🔗', q:['[class*="SimilarProduct"]','[class*="Recommendation"]'] },
],
ajio: [
{ label:'Product images', icon:'🖼️', q:['.prod-img','.rilrtl-img-container'] },
{ label:'Price & offers', icon:'💰', q:['.prod-sp','[class*="prod-sp"]'] },
{ label:'Size selector', icon:'📐', q:['.size-container','[class*="size-container"]'] },
{ label:'Add to bag', icon:'🛒', q:['.add-to-bag','[class*="add-to-bag"]'] },
{ label:'Product details', icon:'📋', q:['.prod-detail-info','[class*="prod-detail-info"]'] },
{ label:'Returns & promise', icon:'🚚', q:['.prod-offers','[class*="returns"]'] },
{ label:'Ratings', icon:'⭐', q:['.ratings-container','[class*="ratings-container"]'] },
{ label:'Similar styles', icon:'🔗', q:['[class*="similar"]','.recommendations'] },
],
};
/* ── Helpers ── */
function getSiteKey() {
const h = location.hostname;
if (h.includes('amazon')) return 'amazon';
if (h.includes('flipkart')) return 'flipkart';
if (h.includes('myntra')) return 'myntra';
if (h.includes('meesho')) return 'meesho';
if (h.includes('ajio')) return 'ajio';
return null;
}
function isProductPage() {
const h = location.hostname, p = location.pathname;
if (h.includes('amazon')) return /\/dp\//i.test(p);
if (h.includes('flipkart')) return /\/p\//i.test(p);
if (h.includes('myntra')) return /\/buy$/i.test(p);
if (h.includes('meesho')) return /\/p\/[a-z0-9]+$/i.test(p);
if (h.includes('ajio')) return /\/p\//i.test(p);
return !!(document.querySelector('#buybox,#addToCart,[class*="add-to-cart"],[class*="buyNow"]'));
}
function scrollY() { return window.scrollY || document.documentElement.scrollTop || 0; }
function absTop(el) { return el.getBoundingClientRect().top + scrollY(); }
function isUsable(el) {
if (!el) return false;
if (el.closest('#pagenav-panel') || el.closest('#pagenav-fab') || el.closest('#pn-ai-popup')) return false;
const r = el.getBoundingClientRect();
return r.height > 30 && r.width > 60;
}
function eid(id) { return document.getElementById(id); }
function esc(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
let idCtr = 0;
function ensureId(el) { if (!el.id) el.id = '__pnv4_'+(idCtr++); return el.id; }
/* ── Section scanner ── */
function scan() {
const groups = SITE_GROUPS[getSiteKey()];
if (!groups) return [];
const results = [], usedEls = new WeakSet();
groups.forEach((g, gi) => {
let found = null;
for (const sel of g.q) {
try {
for (const el of document.querySelectorAll(sel)) {
if (!isUsable(el) || usedEls.has(el)) continue;
found = el; break;
}
} catch(_) {}
if (found) break;
}
if (!found) return;
usedEls.add(found);
const top = Math.round(absTop(found));
if (top < 0) return;
results.push({ id:ensureId(found), label:g.label, icon:g.icon, top });
});
results.sort((a,b) => a.top - b.top);
const out = []; let lastTop = -200;
for (const r of results) { if (r.top - lastTop > 80) { out.push(r); lastTop = r.top; } }
return out;
}
/* ── Page data scraper ── */
function scrapePageData() {
const q = sel => document.querySelector(sel);
const titleEl = q('#productTitle,h1.pdp-name,[class*="pdp-title"],[class*="product-title"],h1');
const priceEl = q('.a-price .a-offscreen,#priceblock_ourprice,._30jeq3,[class*="selling-price"],[class*="pdp-price"]');
const ratingEl = q('#acrPopover,[data-hook="average-star-rating"],._3LWZlK,[class*="averageRating"]');
const countEl = q('#acrCustomerReviewText,[data-hook="total-review-count"],[class*="reviewCount"]');
const specEl = q('#productDetails_feature_div,#tech-specs-section,._2418kt,[class*="specification"]');
const descEl = q('#feature-bullets,#productDescription,[class*="product-description"]');
const sellerEl = q('#sellerProfileTriggerId,#merchant-info,[class*="sellerName"]');
const retEl = q('#returns_policy_feature_div,[class*="returnPolicy"]');
const fulfilEl = q('#tabular-buybox,[class*="fulfillment"]');
const RSELS = ['[data-hook="review"]','._27M-vq','[class*="ReviewCard"]','[class*="review-card"]'];
const reviews = []; const seen = new WeakSet();
for (const sel of RSELS) {
try { document.querySelectorAll(sel).forEach(el => {
if (seen.has(el) || reviews.length >= 30 || el.closest('#pn-ai-popup')) return;
seen.add(el);
const b = el.querySelector('[data-hook="review-body"],[class*="reviewBody"],p');
const s = el.querySelector('[data-hook="review-star-rating"],[class*="starRating"]');
const v = el.querySelector('[data-hook="avp-badge"],[class*="verified"]');
const text = b ? b.textContent.trim().slice(0,400) : el.textContent.trim().slice(0,200);
if (text.length > 15) reviews.push({ title:'', body:text, stars:s?s.textContent.trim().slice(0,5):'', verified:!!v });
}); } catch(_) {}
}
return {
productName: titleEl ? titleEl.textContent.trim().replace(/\s+/g,' ').slice(0,150) : document.title.slice(0,100),
price: priceEl ? priceEl.textContent.trim().slice(0,30) : '',
rating: ratingEl ? ratingEl.textContent.trim().slice(0,20) : '',
reviewCount: countEl ? countEl.textContent.trim().slice(0,30) : '',
finePrint: {
seller: sellerEl ? sellerEl.textContent.trim().slice(0,200) : '',
returns: retEl ? retEl.textContent.trim().slice(0,300) : '',
fulfilment:fulfilEl ? fulfilEl.textContent.trim().slice(0,300) : '',
},
reviews,
};
}
/* ── AI call helpers ── */
async function getKey() {
return new Promise(resolve => {
try {
chrome.storage.local.get(['pn_api_key','pn_api_valid','pn_ai_enabled'], d => {
const key = (d && d.pn_api_key) || '';
const valid = !!(d && d.pn_api_valid);
const enabled = d && d.pn_ai_enabled !== false && valid;
window.__pn_api_key = key;
window.__pn_api_valid = valid;
window.__pn_ai_enabled = enabled;
resolve(enabled ? key : ''); // empty string if AI disabled
});
} catch(_) { resolve(window.__pn_ai_enabled ? (window.__pn_api_key || '') : ''); }
});
}
async function callReviewAI(pageData) {
const key = await getKey();
if (!key) throw new Error('NO_KEY');
const reviewsText = pageData.reviews.map((r,i) =>
'['+(i+1)+'] '+(r.stars?r.stars+' stars':'?')+' | '+(r.verified?'Verified':'Unverified')+'\n'+r.body
).join('\n\n');
const messages = [
{ role:'system', content:'You are a helpful product review analyst. Return ONLY valid JSON, no markdown.' },
{ role:'user', content:'Analyze reviews for "'+pageData.productName+'" ('+pageData.rating+', '+pageData.reviewCount+').\n\nREVIEWS:\n'+(reviewsText||'No reviews found.')+'\n\nReturn JSON:\n{"verdict":"RECOMMENDED","verdictReason":"one sentence","overallSentiment":75,"pros":["specific pro"],"cons":["specific con"],"buyAdvice":"2 sentence advice","reviewsAnalyzed":10}\n\nverdict must be RECOMMENDED, MIXED, or AVOID.' }
];
const text = await window.lensCall(key, messages, true);
return window.lensParseJSON(text);
}
async function callFinePrintAI(pageData) {
const key = await getKey();
if (!key) throw new Error('NO_KEY');
const messages = [
{ role:'system', content:'You are a consumer protection assistant. Return only valid JSON.' },
{ role:'user', content:'Analyze this listing for hidden fine print.\n\nProduct: '+pageData.productName+'\nPrice: '+pageData.price+'\nSeller: '+(pageData.finePrint.seller||'not found')+'\nReturns: '+(pageData.finePrint.returns||'not found')+'\nFulfilment: '+(pageData.finePrint.fulfilment||'not found')+'\n\nReturn JSON:\n{"alerts":[{"severity":"high","icon":"🚩","title":"short title","detail":"one sentence"}],"safe":["good signal"],"summary":"one sentence overall"}' }
];
const text = await window.lensCall(key, messages, true);
return window.lensParseJSON(text);
}
/* ── UI state ── */
let sections = [], currentId = null, panelOpen = false;
/* ── Build FAB ── */
const fab = document.createElement('button');
fab.id = 'pagenav-fab';
fab.title = 'Lens';
fab.innerHTML = '🔍';
const badge = document.createElement('span');
badge.className = 'pn-badge';
badge.textContent = '…';
fab.appendChild(badge);
document.body.appendChild(fab);
/* ── Build panel ── */
const panel = document.createElement('div');
panel.id = 'pagenav-panel';
panel.innerHTML = `
<div class="pn-hd">
<div class="pn-hd-logo">🔍</div>
<div class="pn-hd-text">
<div class="pn-hd-title">Lens</div>
<div class="pn-hd-host">${location.hostname.replace('www.','')}</div>
</div>
<div class="pn-hd-right">
<div class="pn-hd-pill pn-ai-off" id="pn-ai-status">
<span class="pn-hd-pill-dot pn-dot-grey" id="pn-ai-dot"></span>
<span id="pn-ai-txt">AI off</span>
</div>
<button class="pn-hd-close" id="pn-close">✕</button>
</div>
</div>
<div class="pn-body">
<div class="pn-card-label">AI tools</div>
<div class="pn-ai-card">
<button class="pn-ai-btn" id="pn-ai-btn">
<div class="pn-ai-btn-icon" style="background:#fef3c7;">⭐</div>
<div class="pn-ai-btn-text"><span class="pn-ai-btn-label">Analyze reviews</span><span class="pn-ai-btn-sub">Pros, cons & verdict</span></div>
<span class="pn-ai-btn-arr">›</span>
</button>
<button class="pn-ai-btn" id="pn-compare-btn">
<div class="pn-ai-btn-icon" style="background:#eef2ff;">⚖️</div>
<div class="pn-ai-btn-text"><span class="pn-ai-btn-label">Compare tabs</span><span class="pn-ai-btn-sub" id="pn-compare-sub">Side-by-side AI pick</span></div>
<span class="pn-ai-btn-arr">›</span>
</button>
<button class="pn-ai-btn" id="pn-fineprint-btn">
<div class="pn-ai-btn-icon" style="background:#fff1f2;">🚩</div>
<div class="pn-ai-btn-text"><span class="pn-ai-btn-label">Fine print scan</span><span class="pn-ai-btn-sub">Hidden flags & alerts</span></div>
<span class="pn-ai-btn-arr">›</span>
</button>
</div>
<div class="pn-card-label" style="margin-top:8px;">Page sections</div>
<div class="pn-nav-card">
<div class="pn-search">
<span class="pn-search-icon">⌕</span>
<input id="pn-input" type="text" placeholder="Jump to section…" autocomplete="off"/>
</div>
<div class="pn-list" id="pn-list"></div>
</div>
</div>
<div class="pn-ft">
<span id="pn-ft-left">Scanning…</span>
<span>Lens v4</span>
</div>
`;
document.body.appendChild(panel);
/* ── Build AI popup ── */
const overlay = document.createElement('div');
overlay.id = 'pn-ai-overlay';
document.body.appendChild(overlay);
const popup = document.createElement('div');
popup.id = 'pn-ai-popup';
popup.innerHTML = `
<div class="ai-hd">
<div class="ai-hd-icon" id="ai-hd-icon">⭐</div>
<div class="ai-hd-text">
<div class="ai-hd-title" id="ai-hd-title">Lens AI</div>
<div class="ai-hd-sub" id="ai-hd-sub">Analyzing…</div>
</div>
<button class="ai-hd-close" id="ai-popup-close">✕</button>
</div>
<div class="ai-body" id="ai-body"></div>
<div class="ai-ft">Lens AI · Results are AI-generated estimates</div>
`;
document.body.appendChild(popup);
/* ── Render helpers ── */
function showLoading(msg) {
eid('ai-body').innerHTML = '<div class="ai-loading"><div class="ai-spinner"></div><div>'+msg+'</div></div>';
}
function showError(msg) {
eid('ai-body').innerHTML = '<div class="ai-error"><div class="ai-error-icon">⚠️</div><div class="ai-error-title">Something went wrong</div><div class="ai-error-sub">'+msg+'</div><button class="ai-retry-btn" id="ai-retry">Try again</button></div>';
}
function errMsg(err) {
if (err.message === 'NO_KEY') return 'No API key saved. Click the 🔍 toolbar icon and add your key first.';
if (err.message === 'INVALID_KEY') return 'Invalid API key. Check the extension popup.';
if (err.message === 'RATE_LIMIT') return 'Rate limit hit. Wait a moment and try again.';
if (err.message === 'UNKNOWN_PROVIDER') return 'Unrecognised API key format. Supported: Groq, OpenAI, Anthropic, Gemini, Mistral.';
return err.message || 'Unknown error';
}
function renderResult(result) {
const vcls = result.verdict==='RECOMMENDED' ? 'v-safe' : result.verdict==='AVOID' ? 'v-warning' : 'v-caution';
const vicon = result.verdict==='RECOMMENDED' ? '👍' : result.verdict==='AVOID' ? '👎' : '🤔';
const vlabel = result.verdict==='RECOMMENDED' ? 'Worth buying' : result.verdict==='AVOID' ? 'Think twice' : 'Depends on needs';
const sent = result.overallSentiment || 50;
const bclr = sent>=65 ? '#22c55e' : sent>=40 ? '#f59e0b' : '#ef4444';
const prosH = (result.pros||[]).map(p=>'<div class="ai-point ai-pro"><span>✓</span><span>'+esc(p)+'</span></div>').join('') || '<div class="ai-point-empty">None found</div>';
const consH = (result.cons||[]).map(c=>'<div class="ai-point ai-con"><span>✗</span><span>'+esc(c)+'</span></div>').join('') || '<div class="ai-point-empty">None found</div>';
eid('ai-hd-sub').textContent = (result.reviewsAnalyzed||'?')+' reviews analyzed';
eid('ai-body').innerHTML =
'<div class="ai-verdict '+vcls+'"><div class="ai-verdict-icon">'+vicon+'</div><div class="ai-verdict-text"><div class="ai-verdict-label">'+vlabel+'</div><div class="ai-verdict-sub">'+esc(result.verdictReason||'')+'</div></div></div>'+
'<div class="ai-sentiment-row"><span class="ai-sentiment-label">User satisfaction</span><div class="ai-sentiment-track"><div class="ai-sentiment-fill" style="width:'+sent+'%;background:'+bclr+'"></div></div><span class="ai-sentiment-val">'+sent+'</span></div>'+
'<div class="ai-cols"><div><div class="ai-col-title">👍 Liked</div>'+prosH+'</div><div><div class="ai-col-title">👎 Issues</div>'+consH+'</div></div>'+
(result.buyAdvice?'<div class="ai-advice"><div class="ai-advice-label">Should you buy?</div><div class="ai-advice-text">'+esc(result.buyAdvice)+'</div></div>':'');
}
function renderFinePrint(result) {
const alerts = result.alerts || [];
const safe = result.safe || [];
const hasHigh = alerts.some(a=>a.severity==='high');
const vcls = hasHigh ? 'v-warning' : alerts.length ? 'v-caution' : 'v-safe';
const vicon = hasHigh ? '🚩' : alerts.length ? '⚠️' : '✅';
const vlabel = hasHigh ? 'Red flags found' : alerts.length ? 'Minor concerns' : 'Looks clean';
const alertsH = alerts.length ? alerts.map(a=>'<div class="ai-flag"><div class="ai-flag-icon">'+(a.icon||'⚠️')+'</div><div class="ai-flag-text"><strong>'+esc(a.title)+'</strong><br>'+esc(a.detail)+'</div></div>').join('') : '<div class="ai-pos"><span>✓</span> No hidden issues found.</div>';
const safeH = safe.map(s=>'<div class="ai-pos"><span class="ai-pos-icon">✓</span> '+esc(s)+'</div>').join('');
eid('ai-hd-sub').textContent = 'Fine print analysis';
eid('ai-body').innerHTML =
'<div class="ai-verdict '+vcls+'"><div class="ai-verdict-icon">'+vicon+'</div><div class="ai-verdict-text"><div class="ai-verdict-label">'+vlabel+'</div><div class="ai-verdict-sub">'+esc(result.summary||'')+'</div></div></div>'+
'<div class="ai-section"><div class="ai-section-title">Alerts</div>'+alertsH+'</div>'+
(safeH?'<div class="ai-section"><div class="ai-section-title">What looks good</div>'+safeH+'</div>':'');
}
function renderCompare(result, products) {
const medals = ['🥇','🥈','🥉'];
const vcls = result.verdict==='CLEAR_WINNER' ? 'v-safe' : 'v-caution';
const vlabel = result.verdict==='CLEAR_WINNER' ? 'Clear winner' : result.verdict==='CLOSE_CALL' ? 'Very close' : 'Depends on needs';
const ranked = [...(result.products||[])].sort((a,b)=>(a.rank||99)-(b.rank||99));
const wname = result.winnerName || (ranked[0]&&ranked[0].name) || '';
const cardsH = ranked.map(p=>{
const isW = p.rank===1;
const pros = (p.pros||[]).map(x=>'<div class="cmp-point cmp-pro"><span>✓</span><span>'+esc(x)+'</span></div>').join('');
const cons = (p.cons||[]).map(x=>'<div class="cmp-point cmp-con"><span>✗</span><span>'+esc(x)+'</span></div>').join('');
return '<div class="cmp-card'+(isW?' cmp-winner':'')+'">'+
'<div class="cmp-card-hd"><span class="cmp-medal">'+(medals[(p.rank||1)-1]||p.rank)+'</span><div class="cmp-card-title">'+esc(p.name||'')+'</div></div>'+
'<div class="cmp-meta">'+
(p.price ?'<span class="cmp-price">'+esc(p.price)+'</span>':'')+
(p.rating ?'<span class="cmp-rating">'+esc(p.rating)+' ★</span>':'')+
(p.site ?'<span class="cmp-site">'+esc(p.site)+'</span>':'')+
'</div>'+
(p.bestFor?'<div class="cmp-bestfor">Best for: '+esc(p.bestFor)+'</div>':'')+
pros+cons+'</div>';
}).join('');
eid('ai-hd-sub').textContent = products.length+' products compared';
eid('ai-body').innerHTML =
'<div class="ai-verdict '+vcls+'"><div class="ai-verdict-icon">'+medals[0]+'</div><div class="ai-verdict-text"><div class="ai-verdict-label">'+vlabel+(wname?': '+esc(wname.split(/[,|(]/)[0].trim().slice(0,50)):'')+'</div><div class="ai-verdict-sub">'+esc(result.winnerReason||'')+'</div></div></div>'+
'<div class="cmp-cards">'+cardsH+'</div>'+
(result.buyAdvice?'<div class="ai-advice"><div class="ai-advice-label">Should you buy?</div><div class="ai-advice-text">'+esc(result.buyAdvice)+'</div></div>':'');
}
/* ── Open / close popup ── */
function openPopup(icon, title) {
eid('ai-hd-icon').textContent = icon;
eid('ai-hd-title').textContent = title;
overlay.classList.add('pn-ai-open');
popup.classList.add('pn-ai-open');
}
function closePopup() {
overlay.classList.remove('pn-ai-open');
popup.classList.remove('pn-ai-open');
}
/* ── AI runners ── */
async function runReviews() {
openPopup('⭐','Review analysis');
showLoading('Reading reviews…');
try {
const data = scrapePageData();
eid('ai-hd-sub').textContent = 'Found '+data.reviews.length+' reviews';
showLoading('Analyzing with AI…');
const result = await callReviewAI(data);
renderResult(result);
} catch(e) { showError(errMsg(e)); }
}
async function runFinePrint() {
openPopup('🚩','Fine print scan');
showLoading('Scanning listing…');
try {
const data = scrapePageData();
const result = await callFinePrintAI(data);
renderFinePrint(result);
} catch(e) { showError(errMsg(e)); }
}
async function runCompare() {
openPopup('⚖️','Compare products');
showLoading('Looking for open product tabs…');
const key = await getKey();
if (!key) { showError(errMsg({message:'NO_KEY'})); return; }
chrome.runtime.sendMessage({ type:'COMPARE_TABS', groqKey:key });
}
/* ── Render sections list ── */
function renderList(filter) {
const list = eid('pn-list');
if (!list) return;
const q = (filter||'').trim().toLowerCase();
const rows = q ? sections.filter(s=>s.label.toLowerCase().includes(q)) : sections;
if (!rows.length) {
list.innerHTML = '<div class="pn-msg"><div class="pn-msg-icon">'+(sections.length?'🔎':'📭')+'</div>'+(sections.length?'No matching sections.':'Sections not detected yet.')+'</div>';
return;
}
list.innerHTML = rows.map(s=>`
<div class="pn-row ${s.id===currentId?'pn-here':''}" data-id="${s.id}">
<div class="pn-row-icon">${s.icon}</div>
<span class="pn-row-label">${esc(s.label)}</span>
<span class="pn-row-chip">${s.id===currentId?'here':'↓'}</span>
</div>`).join('');
list.querySelectorAll('.pn-row').forEach(el=>el.addEventListener('click',()=>jumpTo(el.dataset.id)));
}
function jumpTo(id) {
const el = document.getElementById(id);
if (!el) return;
window.scrollTo({ top:Math.max(0,absTop(el)-72), behavior:'smooth' });
el.classList.add('pn-flash-highlight');
setTimeout(()=>el.classList.remove('pn-flash-highlight'),2000);
currentId = id;
renderList(eid('pn-input')?.value||'');
}
/* ── Status pill ── */
function updateStatus() {
const bar = eid('pn-ai-status');
const dot = eid('pn-ai-dot');
const txt = eid('pn-ai-txt');
if (!bar) return;
const key = window.__pn_api_key || '';
const valid = window.__pn_api_valid;
const enabled = window.__pn_ai_enabled;
const pk = window.lensDetect(key);
const pname = pk && window.LensProviders[pk] ? window.LensProviders[pk].name : 'AI';
if (key && valid && enabled) {
bar.className = 'pn-hd-pill pn-ai-ready';
dot.className = 'pn-hd-pill-dot pn-dot-green';
txt.textContent = pname + ' ready';
} else if (key && valid && !enabled) {
bar.className = 'pn-hd-pill pn-ai-warn';
dot.className = 'pn-hd-pill-dot pn-dot-yellow';
txt.textContent = 'AI paused';
} else if (key) {
bar.className = 'pn-hd-pill pn-ai-warn';
dot.className = 'pn-hd-pill-dot pn-dot-yellow';
txt.textContent = 'Verify key';
} else {
bar.className = 'pn-hd-pill pn-ai-off';
dot.className = 'pn-hd-pill-dot pn-dot-grey';
txt.textContent = 'AI off';
}
}
/* ── Panel open / close ── */
function openPanel() {
panelOpen = true;
panel.classList.add('pn-open');
fab.classList.add('pn-fab-active');
doScan();
updateStatus();
setTimeout(()=>eid('pn-input')?.focus(), 80);
}
function closePanel() {
panelOpen = false;
panel.classList.remove('pn-open');
fab.classList.remove('pn-fab-active');
}
/* ── Scan ── */
function doScan() {
sections = scan();
badge.textContent = sections.length || '?';
const ftl = eid('pn-ft-left');
if (ftl) ftl.textContent = sections.length+' sections';
updateCurrent();
renderList(eid('pn-input')?.value||'');
}
function updateCurrent() {
const mid = scrollY() + window.innerHeight * 0.3;
let cur = sections[0];
for (const s of sections) { if (s.top<=mid) cur=s; else break; }
currentId = cur ? cur.id : null;
}
/* ── Events ── */
fab.addEventListener('click', e=>{ e.stopPropagation(); panelOpen ? closePanel() : openPanel(); });
eid('pn-close').addEventListener('click', closePanel);
eid('pn-input').addEventListener('input', e=>renderList(e.target.value));
eid('pn-ai-btn').addEventListener('click', runReviews);
eid('pn-compare-btn').addEventListener('click', runCompare);
eid('pn-fineprint-btn').addEventListener('click',runFinePrint);
eid('ai-popup-close').addEventListener('click', closePopup);
overlay.addEventListener('click', closePopup);
document.addEventListener('click', e=>{
if (panelOpen && !panel.contains(e.target) && e.target!==fab && !fab.contains(e.target)) closePanel();
});
let scrollT;
window.addEventListener('scroll', ()=>{
clearTimeout(scrollT);
scrollT = setTimeout(()=>{ updateCurrent(); if(panelOpen) renderList(eid('pn-input')?.value||''); },160);
},{ passive:true });
/* ── Single unified message listener ── */
chrome.runtime.onMessage.addListener(msg => {
if (msg.type === 'TOGGLE_PANEL') {
panelOpen ? closePanel() : openPanel();
} else if (msg.type === 'SET_API_KEY') {
window.__pn_api_key = msg.key || '';
window.__pn_api_valid = !!(msg.key);
window.__pn_ai_enabled = msg.enabled !== false && !!(msg.key);
chrome.storage.local.set({ pn_api_key: msg.key || '', pn_api_valid: !!(msg.key), pn_ai_enabled: window.__pn_ai_enabled });
updateStatus();
} else if (msg.type === 'COMPARE_PROGRESS') {
const body = eid('ai-body');
if (!body) return;
const msgs = {
scraping: 'Reading '+msg.count+' product pages…',
comparing: 'Comparing '+msg.count+' products with AI…',
filtered: 'Found '+msg.kept+' similar products'+(msg.removed?' ('+msg.removed+' unrelated excluded)':'')+' …',
};
if (msgs[msg.step]) showLoading(msgs[msg.step]);
} else if (msg.type === 'COMPARE_RESULT') {
renderCompare(msg.result, msg.products);
} else if (msg.type === 'COMPARE_ERROR') {
const e = msg.error;
showError(
e==='NEED_MORE_TABS' ? 'Only '+(msg.count||0)+' product tab'+(msg.count===1?'':'s')+' found.<br>Open 2+ product pages in separate tabs.' :
e==='SCRAPE_FAILED' ? 'Could not read product data. Make sure pages are fully loaded.' :
e==='INVALID_KEY' ? 'Invalid API key — check the extension popup.' :
e==='RATE_LIMIT' ? 'Rate limit hit. Wait a moment and try again.' :
'Comparison failed: '+(e||'unknown error')
);
}
// No return true — all async results come via sendMessage from background
});
/* ── Load key from storage on init ── */
chrome.storage.local.get(['pn_api_key','pn_api_valid','pn_ai_enabled'], d => {
window.__pn_api_key = (d && d.pn_api_key) || '';
window.__pn_api_valid = !!(d && d.pn_api_valid);
window.__pn_ai_enabled = d && d.pn_ai_enabled !== false && !!(d.pn_api_valid);
updateStatus();
});
/* ── Auto-open on product pages ── */
function tryAutoOpen() {
if (!isProductPage()) return;
doScan();
setTimeout(()=>{ if(sections.length>0) openPanel(); },200);
}
setTimeout(tryAutoOpen, 800);
setTimeout(doScan, 2500);
setTimeout(doScan, 5000);
/* ── Watch SPA navigation ── */
let lastUrl = location.href, mutT;
new MutationObserver(()=>{
clearTimeout(mutT);
mutT = setTimeout(()=>{
if (location.href !== lastUrl) {
lastUrl = location.href;
closePanel();
setTimeout(tryAutoOpen, 900);
} else { doScan(); }
}, 800);
}).observe(document.body, { childList:true, subtree:false });
})();