Repository navigation
Expand file tree
/
Copy pathpopup.js
More file actions
737 lines (657 loc) · 26.9 KB
/
Copy pathpopup.js
File metadata and controls
737 lines (657 loc) · 26.9 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
// =============================================================================
// popup.js — Main popup script with tabbed interface
// =============================================================================
// This module coordinates:
// - Tab switching between SEO, Keywords, Competitors, AI, and Settings views
// - Page data scraping from the content script
// - SEO scoring and keyword extraction
// - AI suggestion generation via WebLLM
// - Settings management and data export/import
// =============================================================================
import {
scoreSEO,
extractKeywords,
analyzeReadability,
estimateKeywordDifficulty,
tokenize,
} from "./lib/seo.js";
import {
classifyIntent,
estimateVolume,
suggestLongTail,
scoreKeyword,
} from "./lib/keywords.js";
import {
compareMetadata,
findContentGaps,
analyzeTagStrategy,
} from "./lib/competitors.js";
import {
MODELS,
DEFAULT_MODEL,
loadModel,
generateSuggestions,
isWebGPUAvailable,
} from "./lib/engine.js";
// =============================================================================
// DOM helpers
// =============================================================================
const $ = (id) => document.getElementById(id);
let pageData = null;
let keywords = [];
// =============================================================================
// Tab switching
// =============================================================================
$("tabs").addEventListener("click", (e) => {
const tabBtn = e.target.closest(".tab");
if (!tabBtn) return;
// Update tab buttons
document.querySelectorAll(".tab").forEach((t) => t.classList.remove("active"));
tabBtn.classList.add("active");
// Update tab content
const tabName = tabBtn.dataset.tab;
document.querySelectorAll(".tab-content").forEach((tc) => tc.classList.remove("active"));
const target = $(`tab-${tabName}`);
if (target) target.classList.add("active");
});
// =============================================================================
// GPU badge
// =============================================================================
const gpuBadge = $("gpu-badge");
if (isWebGPUAvailable()) {
gpuBadge.textContent = "WebGPU ✓";
gpuBadge.classList.add("ok");
} else {
gpuBadge.textContent = "No WebGPU";
gpuBadge.classList.add("no");
}
// =============================================================================
// Model dropdown (main + settings)
// =============================================================================
function populateModelDropdowns() {
[$("model-select"), $("setting-model")].forEach((sel) => {
if (!sel) return;
sel.innerHTML = "";
for (const [id, label] of Object.entries(MODELS)) {
const opt = document.createElement("option");
opt.value = id;
opt.textContent = label;
sel.appendChild(opt);
}
sel.value = DEFAULT_MODEL;
});
}
populateModelDropdowns();
// =============================================================================
// Theme — light / dark toggle
// =============================================================================
function applyTheme(useLight) {
document.body.classList.toggle("theme-light", useLight);
}
// =============================================================================
// Settings — load and bind
// =============================================================================
async function loadSettings() {
try {
const settings = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });
if (settings) {
$("setting-auto").checked = settings.autoAnalyze !== false;
$("setting-badge").checked = settings.showScoreBadge !== false;
$("setting-sidebar").checked = settings.enableSidebar !== false;
$("setting-ai").checked = settings.useAI !== false;
$("setting-light-theme").checked = settings.lightTheme === true;
applyTheme(settings.lightTheme === true);
if (settings.model && $("setting-model")) {
$("setting-model").value = settings.model;
}
}
} catch (e) {
console.log("[settings] Could not load:", e.message);
}
}
async function saveSettings() {
const settings = {
autoAnalyze: $("setting-auto").checked,
showScoreBadge: $("setting-badge").checked,
enableSidebar: $("setting-sidebar").checked,
useAI: $("setting-ai").checked,
lightTheme: $("setting-light-theme").checked,
model: $("setting-model")?.value || DEFAULT_MODEL,
};
try {
await chrome.runtime.sendMessage({ type: "SAVE_SETTINGS", settings });
applyTheme(settings.lightTheme);
} catch (e) {
console.log("[settings] Could not save:", e.message);
}
}
// Bind settings change events
document.querySelectorAll("#tab-settings input[type=checkbox]").forEach((el) => {
el.addEventListener("change", saveSettings);
});
$("setting-model")?.addEventListener("change", saveSettings);
// =============================================================================
// Scrape the active tab
// =============================================================================
async function getActiveTab() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
return tab;
}
async function scrapeCurrentPage(retries = 2) {
const tab = await getActiveTab();
if (!tab || !tab.url) return null;
const isYouTube =
/youtube\.com/.test(tab.url) || /youtu\.be/.test(tab.url);
if (!isYouTube) return { ok: false, notYouTube: true };
for (let attempt = 0; attempt <= retries; attempt++) {
try {
return await chrome.tabs.sendMessage(tab.id, { type: "SCRAPE_PAGE" });
} catch (err) {
if (attempt < retries) {
// Content script not injected — inject it
try {
// Determine which content script to inject based on URL
let file = "content/watch.js";
if (tab.url.includes("studio.youtube.com")) file = "content/studio.js";
else if (tab.url.includes("/results")) file = "content/search.js";
else if (tab.url.includes("/feed/")) file = "content/feed.js";
else if (
tab.url.includes("/channel") ||
tab.url.includes("/c/") ||
tab.url.includes("/@")
) {
file = "content/channel.js";
}
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: [file],
});
// Wait a moment for script initialization
await new Promise((r) => setTimeout(r, 500));
} catch (injectErr) {
console.log("[scrape] Injection error:", injectErr.message);
}
} else {
return { ok: false, error: err.message };
}
}
}
return { ok: false, error: "Max retries exceeded" };
}
// =============================================================================
// Render SEO score
// =============================================================================
function renderScore(data) {
if (!data?.title && !data?.description) {
$("score-num").textContent = "N/A";
$("score-grade").textContent = "SEO: No data";
$("score-sub").textContent = "Could not extract video metadata";
return;
}
const { score, grade, passed, total, checks } = scoreSEO(data);
const ring = $("score-ring");
const col =
score >= 75 ? "var(--good)" : score >= 55 ? "var(--warn)" : "var(--bad)";
ring.style.setProperty("--val", score);
ring.style.setProperty("--col", col);
$("score-num").textContent = score;
$("score-grade").textContent = `SEO: ${grade}`;
$("score-sub").textContent = `${passed} of ${total} checks passed`;
const list = $("checklist");
list.innerHTML = "";
for (const c of checks) {
const li = document.createElement("li");
li.className = c.pass ? "pass" : "fail";
li.innerHTML = `<span class="icon">${c.pass ? "✓" : "!"}</span>
<span>${c.label}${c.pass ? "" : ` — <span class="hint">${c.hint}</span>`}
${c.pass || !c.action ? "" : `<br><span class="action">→ ${c.action}</span>`}
</span>`;
list.appendChild(li);
}
}
// =============================================================================
// Render readability
// =============================================================================
function renderReadability(data) {
const readability = analyzeReadability(data?.description);
const el = $("readability-score");
if (readability.score === 0) {
el.textContent = "Description too short for analysis (need 50+ chars)";
return;
}
el.innerHTML = `
<div>Score: ${readability.score}/100 — <strong>${readability.level}</strong></div>
<div class="muted small">${readability.words} words · ${readability.sentences} sentences · ${readability.avgWordsPerSentence} words/sentence</div>
`;
}
// =============================================================================
// Render video info
// =============================================================================
function renderVideoInfo(data) {
const el = $("video-info");
if (!data) {
el.textContent = "No video data available";
return;
}
const s = data.stats || {};
el.innerHTML = `
<div><strong>Title:</strong> ${data.title || "(none)"}</div>
<div><strong>Channel:</strong> ${s.channel || "(unknown)"}</div>
<div><strong>Views:</strong> ${s.views?.toLocaleString() || "N/A"} ·
<strong>Likes:</strong> ${s.likes?.toLocaleString() || "N/A"}</div>
<div><strong>Tags:</strong> ${(data.tags || []).length} tags</div>
<div><strong>Published:</strong> ${s.published || "N/A"}</div>
${data.videoId ? `<div><strong>Video ID:</strong> ${data.videoId}</div>` : ""}
`;
}
// =============================================================================
// Render keywords
// =============================================================================
function renderKeywords(data) {
keywords = extractKeywords(data);
const container = $("keywords-container");
container.innerHTML = "";
if (keywords.length === 0) {
container.innerHTML = `<span class="muted small">No keywords detected.</span>`;
return;
}
for (const k of keywords) {
const chip = document.createElement("span");
chip.className = "chip";
chip.textContent = k.word;
chip.title = `Score: ${k.score} · ${k.type} · Click to copy`;
chip.onclick = () => copyText(chip, k.word);
container.appendChild(chip);
}
}
// =============================================================================
// Copy to clipboard
// =============================================================================
function copyText(el, text) {
navigator.clipboard.writeText(text).catch(() => {});
el.classList.add("copied");
setTimeout(() => el.classList.remove("copied"), 800);
}
$("btn-copy-keywords")?.addEventListener("click", () => {
const text = keywords.map((k) => k.word).join(", ");
navigator.clipboard.writeText(text).catch(() => {});
$("btn-copy-keywords").textContent = "Copied!";
setTimeout(() => {
$("btn-copy-keywords").textContent = "Copy all keywords";
}, 1500);
});
// =============================================================================
// Keyword research
// =============================================================================
$("btn-research-keyword")?.addEventListener("click", async () => {
const input = $("keyword-input");
const kw = input.value.trim();
if (!kw) return;
const resultsEl = $("keyword-research-results");
const longtailEl = $("longtail-results");
// Score the keyword
const scored = scoreKeyword(kw, pageData?.tags || []);
resultsEl.innerHTML = `
<div style="margin-bottom:8px">
<strong>Intent:</strong> ${scored.intent.intent} (${scored.intent.confidence}% confidence)
</div>
<div style="margin-bottom:8px">
<strong>Est. volume:</strong> ${scored.volume.volume}/mo · <strong>Opportunity:</strong> ${scored.opportunity}/100
</div>
<div style="margin-bottom:8px">
<strong>Relevancy:</strong> ${scored.relevancy}% · <strong>Specificity:</strong> ${scored.specificity}% · <strong>Competition:</strong> ${scored.competition}%
</div>
`;
// Show long-tail suggestions
const longtail = suggestLongTail(kw);
const longtailSlice = longtail.slice(0, 15);
longtailEl.innerHTML =
`<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
<strong>Long-tail variations</strong>
<button class="btn small" id="btn-copy-longtail">Copy all</button>
</div>` +
longtailSlice
.map(
(s) =>
`<span class="chip" onclick="navigator.clipboard.writeText('${s.replace(
/'/g,
"\\'"
)}').then(() => this.classList.add('copied'))">${s}</span>`
)
.join("") +
`<div class="muted small" style="margin-top:4px">Click individual chips to copy · <strong>${longtail.length}</strong> total variations</div>`;
// Bind the copy-all button after it's in the DOM
setTimeout(() => {
const copyBtn = document.getElementById("btn-copy-longtail");
if (copyBtn) {
copyBtn.onclick = () => {
const text = longtailSlice.join(", ");
navigator.clipboard.writeText(text);
copyBtn.textContent = "Copied!";
setTimeout(() => { copyBtn.textContent = "Copy all"; }, 1500);
};
}
}, 0);
});
// =============================================================================
// AI generation
// =============================================================================
$("btn-generate")?.addEventListener("click", async () => {
if (!isWebGPUAvailable()) {
$("ai-not-available").classList.remove("hidden");
return;
}
$("ai-not-available").classList.add("hidden");
const btn = $("btn-generate");
const progress = $("ai-progress");
const fill = $("bar-fill");
const ptext = $("progress-text");
const results = $("ai-results");
btn.disabled = true;
progress.classList.remove("hidden");
results.innerHTML = "";
try {
const modelId = $("model-select")?.value || DEFAULT_MODEL;
await loadModel(modelId, (report) => {
const pct = Math.round((report.progress || 0) * 100);
fill.style.width = pct + "%";
ptext.textContent = report.text || `Loading model… ${pct}%`;
});
ptext.textContent = "Generating suggestions…";
fill.style.width = "100%";
const out = await generateSuggestions({
title: pageData?.title,
description: pageData?.description,
keywords: keywords.map((k) => k.word),
});
renderAI(out);
} catch (e) {
results.innerHTML = `<p class="muted small">Generation failed: ${e.message || e}</p>`;
} finally {
btn.disabled = false;
progress.classList.add("hidden");
fill.style.width = "0%";
}
});
// =============================================================================
// Render AI results
// =============================================================================
function renderAI({ titles, tags, description, hashtags }) {
const results = $("ai-results");
results.innerHTML = "";
if (titles?.length) {
const block = document.createElement("div");
block.className = "ai-block";
block.innerHTML = "<h3>Suggested titles (click to copy)</h3>";
titles.forEach((t) => {
const item = document.createElement("div");
item.className = "ai-item";
item.textContent = t;
item.onclick = () => copyText(item, t);
block.appendChild(item);
});
results.appendChild(block);
}
if (tags?.length) {
const block = document.createElement("div");
block.className = "ai-block";
block.innerHTML = "<h3>Suggested tags (click to copy all)</h3>";
const item = document.createElement("div");
item.className = "ai-item";
item.textContent = tags.join(", ");
item.onclick = () => copyText(item, tags.join(", "));
block.appendChild(item);
results.appendChild(block);
}
if (hashtags?.length) {
const block = document.createElement("div");
block.className = "ai-block";
block.innerHTML = "<h3>Hashtags (click to copy all)</h3>";
const item = document.createElement("div");
item.className = "ai-item";
item.textContent = hashtags.join(" ");
item.onclick = () => copyText(item, hashtags.join(" "));
block.appendChild(item);
results.appendChild(block);
}
if (description) {
const block = document.createElement("div");
block.className = "ai-block";
block.innerHTML = "<h3>Suggested description (click to copy)</h3>";
const item = document.createElement("div");
item.className = "ai-item";
item.style.whiteSpace = "pre-wrap";
item.textContent = description.slice(0, 1000);
item.onclick = () => copyText(item, description);
block.appendChild(item);
results.appendChild(block);
}
}
// =============================================================================
// Competitor tab — tag strategy, recommendations, and content gaps
// =============================================================================
async function renderCompetitorTab() {
const stored = await chrome.storage.local.get("manualVideoData");
const manual = stored.manualVideoData || {};
const title = manual.title || pageData?.title || "";
const description = manual.description || pageData?.description || "";
const tags = manual.tags || pageData?.tags || [];
const hasAnyData = title || description || tags.length > 0;
// --- 1. Tag strategy breakdown ---
const analysis = analyzeTagStrategy(tags);
const analysisEl = $("competitor-analysis");
const hasTags = tags.length > 0;
analysisEl.innerHTML = hasTags
? `<div style="margin-bottom:6px">
<strong>${tags.length} tags</strong> — Broad: <strong>${analysis.broad.length}</strong> · Specific: <strong>${analysis.specific.length}</strong> · Long-tail: <strong>${analysis.longTail.length}</strong>
</div>
<div style="display:flex;flex-wrap:wrap;gap:4px">
${tags.map(t => `<span class="chip" onclick="navigator.clipboard.writeText('${t.replace(/'/g,"\\'")}');this.classList.add('copied')">${t}</span>`).join("")}
</div>
<div style="margin-top:6px;color:#9aa3b2;font-size:12px">
${analysis.broad.length === 0 ? "Tip: Add some single-word broad tags for discovery." : ""}
${analysis.specific.length < 3 ? " Add more 2-3 word specific tags for relevance." : ""}
${analysis.longTail.length < 3 ? " Add long-tail phrases (4+ words) for low-competition ranking." : ""}
</div>`
: `<span class="muted">No tags entered — add tags in your video data.</span>`;
// --- 2. Recommended tags to add ---
const recEl = $("recommended-tags");
const titleTokens = tokenize(title);
if (titleTokens.length === 0 && !description) {
recEl.innerHTML = `<span class="muted">Enter a title and description to get tag recommendations.</span>`;
} else {
const existingKeywords = new Set(tags.map(t => t.toLowerCase()));
const existingWords = new Set();
tags.forEach(t => tokenize(t).forEach(w => existingWords.add(w)));
const recs = [];
const broadRecs = ["tutorial", "review", "howto", "guide", "tips", "vlog", "educational", "entertainment"]
.filter(b => !existingWords.has(b));
if (broadRecs.length > 0) recs.push({ cat: "Broad discovery", tags: broadRecs.slice(0, 4) });
const titleWordRecs = titleTokens.filter(w => !existingWords.has(w));
if (titleWordRecs.length > 0) recs.push({ cat: "From your title", tags: titleWordRecs.slice(0, 5) });
const phraseRecs = [];
for (let i = 0; i < titleTokens.length - 1; i++) {
const phrase = titleTokens[i] + " " + titleTokens[i + 1];
if (!existingKeywords.has(phrase)) phraseRecs.push(phrase);
}
if (phraseRecs.length > 0) recs.push({ cat: "Title phrases (long-tail)", tags: phraseRecs.slice(0, 4) });
const descTokens = tokenize(description);
const descRecs = descTokens.filter(w => !existingWords.has(w) && !titleTokens.includes(w));
if (descRecs.length > 0) recs.push({ cat: "From your description", tags: descRecs.slice(0, 5) });
if (recs.length === 0) {
recEl.innerHTML = `<span class="muted good">Your tags already cover all detected keywords. Good coverage!</span>`;
} else {
recEl.innerHTML = recs.map(r =>
`<div style="margin-bottom:8px">
<strong style="font-size:11px;color:#9aa3b2;text-transform:uppercase">${r.cat}</strong>
<div style="display:flex;flex-wrap:wrap;gap:4px;margin-top:4px">
${r.tags.map(t => `<span class="chip" onclick="navigator.clipboard.writeText('${t.replace(/'/g,"\\'")}');this.classList.add('copied')">${t}</span>`).join("")}
</div>
</div>`
).join("");
}
}
// --- 3. Content gaps ---
const gapEl = $("content-gaps");
if (!hasAnyData) {
gapEl.innerHTML = `<span class="muted">Enter video data to see content gaps.</span>`;
} else {
const allTokens = [...new Set([...tokenize(title), ...tokenize(description)])];
const existingSet = new Set();
tags.forEach(t => tokenize(t).forEach(w => existingSet.add(w)));
const gaps = allTokens.filter(w => !existingSet.has(w) && w.length > 3);
if (gaps.length === 0) {
gapEl.innerHTML = `<span class="good">✓ All your content keywords are covered by existing tags.</span>`;
} else {
gapEl.innerHTML =
`<div style="margin-bottom:6px">These keywords appear in your content but NOT in your tags — add them to rank for these terms:</div>
<div style="display:flex;flex-wrap:wrap;gap:4px">
${gaps.slice(0, 12).map(w =>
`<span class="chip" onclick="navigator.clipboard.writeText('${w.replace(/'/g,"\\'")}');this.classList.add('copied')">${w}</span>`
).join("")}
</div>
<div style="margin-top:6px;color:#9aa3b2;font-size:12px">
${gaps.length > 12 ? `+${gaps.length - 12} more gaps` : ""}
Click any chip to copy, then paste into Studio's tags field.
</div>`;
}
}
}
// =============================================================================
// Re-analyze / Refresh buttons
// =============================================================================
$("btn-reanalyze")?.addEventListener("click", async () => {
await initPopup(true);
});
$("btn-refresh")?.addEventListener("click", async () => {
await initPopup(true);
});
// =============================================================================
// Export / Import
// =============================================================================
$("btn-export")?.addEventListener("click", async () => {
try {
const result = await chrome.runtime.sendMessage({ type: "EXPORT_DATA" });
if (result.ok) {
const blob = new Blob([JSON.stringify(result.data, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `opentube-seo-export-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
}
} catch (e) {
console.log("[export] Error:", e.message);
}
});
$("btn-import")?.addEventListener("click", () => {
$("import-file").click();
});
$("import-file")?.addEventListener("change", async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
const result = await chrome.runtime.sendMessage({
type: "IMPORT_DATA",
data,
});
if (result.ok) {
alert(`Imported ${result.imported} data sections.`);
}
} catch (err) {
alert("Import failed: " + err.message);
}
// Reset the file input
e.target.value = "";
});
// =============================================================================
// Manual input — analyze and show results
// =============================================================================
$("btn-analyze-manual")?.addEventListener("click", async () => {
const title = $("manual-title").value.trim();
const description = $("manual-description").value.trim();
const tagsRaw = $("manual-tags").value.trim();
const tags = tagsRaw
? tagsRaw.split(",").map(t => t.trim()).filter(Boolean)
: [];
await chrome.storage.local.set({ manualVideoData: { title, description, tags } });
$("manual-section").classList.add("hidden");
$("analysis-section").classList.remove("hidden");
const manual = { title, description, tags };
renderKeywords(manual);
renderCompetitorTab();
enableAI(manual);
});
$("btn-show-manual-input")?.addEventListener("click", () => {
$("analysis-section").classList.add("hidden");
$("manual-section").classList.remove("hidden");
});
// =============================================================================
// Init — load current page data and render everything
// =============================================================================
async function initPopup(forceRefresh = false) {
// Load any stored manual data
const stored = await chrome.storage.local.get("manualVideoData");
const manual = stored.manualVideoData || {};
pageData = await scrapeCurrentPage();
const isOnYouTube = pageData && !pageData.notYouTube && pageData.ok && !pageData._empty;
if (isOnYouTube) {
// Scrape worked — merge manual data on top (so manual overrides gaps)
if (manual.title) pageData.title = manual.title;
if (manual.description) pageData.description = manual.description;
if (manual.tags?.length) pageData.tags = manual.tags;
$("not-youtube").classList.add("hidden");
$("app").classList.remove("hidden");
$("manual-section").classList.add("hidden");
$("analysis-section").classList.add("hidden");
renderAll(pageData);
} else {
// Scrape failed — show manual section or not-youtube
$("not-youtube").classList.remove("hidden");
$("app").classList.add("hidden");
if (manual.title || manual.description || manual.tags?.length) {
// Use stored manual data
$("not-youtube").classList.add("hidden");
$("manual-title").value = manual.title || "";
$("manual-description").value = manual.description || "";
$("manual-tags").value = (manual.tags || []).join(", ");
$("manual-section").classList.add("hidden");
$("analysis-section").classList.remove("hidden");
renderManualAnalysis(manual);
} else {
$("not-youtube").classList.add("hidden");
$("manual-section").classList.remove("hidden");
$("analysis-section").classList.add("hidden");
}
}
}
function renderAll(data) {
renderScore(data);
renderReadability(data);
renderVideoInfo(data);
renderKeywords(data);
renderCompetitorTab();
enableAI(data);
}
function renderManualAnalysis(manual) {
renderKeywords({ title: manual.title, description: manual.description, tags: manual.tags, comments: [] });
renderCompetitorTab();
enableAI({ title: manual.title, description: manual.description });
}
function enableAI(data) {
if (isWebGPUAvailable() && data?.title) {
$("btn-generate").disabled = false;
}
}
// =============================================================================
// Bootstrap
// =============================================================================
(async function () {
await loadSettings();
await initPopup();
})();