/** * BoostMedia AI Content Generator Admin - Links Page * * Manages internal and external link libraries for smart linking. * * @package BoostMedia_AI * @license GPL-2.0-or-later */ import { useState, useEffect, useCallback, useRef, useMemo } from 'react' import { Link2, ExternalLink, RefreshCw, Plus, Trash2, Check, X, Globe, Sparkles, Settings2, Save, Loader2, AlertTriangle, } from 'lucide-react' import { Header } from '../components/layout/Header' import { Card, CardContent, Button, Badge, HelpTooltip, CheckboxPicker, ExpandableSummary, ExpandableKeywords } from '../components/common' import { SetupBanner } from '../components/onboarding/SetupBanner' import { endpoints, getErrorMessage } from '../api/client' import { useDataLanguage } from '../lib/DataLanguageContext' import { t, tf } from '../lib/i18n' import { useLinkRules, useScopeOptions, useTaxonomyTerms, useScopePostsPicker, useCollectLinkRules, useDeleteLinkIndex, createEmptyLinkRule, areLinkRulesEqual, } from '../hooks/useLinkRules' import type { LinkRule, ScopeOption } from '../hooks/useLinkRules' interface InternalLink { id: number post_id: number url: string title: string summary: string | null keywords: string | null post_type: string ai_analyzed: number } interface ExternalLinkItem { id: number url: string title: string keyword: string context: string | null summary: string | null keywords: string[] ai_analyzed: number active: number } interface InternalLinkStats { total: number analyzed: number unanalyzed: number } interface AnalyzeBatchResponse { analyzed?: number processed?: number total?: number remaining?: number unanalyzed?: number credits_used?: number stopped_reason?: string message?: string } interface BatchProgress { total: number completed: number remaining: number creditsUsed: number startedAt: number cancelRequested: boolean } type Tab = 'internal' | 'external' function formatCoins(value: number): string { return value.toFixed(1) } function formatDuration(ms: number): string { if (!Number.isFinite(ms) || ms <= 0) { return t('Calculating...') } const totalSeconds = Math.max(1, Math.round(ms / 1000)) const minutes = Math.floor(totalSeconds / 60) const seconds = totalSeconds % 60 if (minutes <= 0) { return `${seconds}s` } return `${minutes}:${String(seconds).padStart(2, '0')}` } function getScopeGroupLabel(group: string): string { switch (group) { case 'general': return t('General') case 'content_types': return t('Content Types') case 'taxonomies': return t('Taxonomies') case 'archive_pages': return t('Archive Pages') case 'specific_items': return t('Specific Items') default: return group } } function getScopeOptionLabel(option: ScopeOption): string { const objectLabel = option.objectLabel || option.label switch (option.kind) { case 'all': return t('All content') case 'post_type': return tf('Content type: %s', objectLabel) case 'post': return tf('Specific item: %s', objectLabel) case 'taxonomy': return objectLabel case 'archive': return tf('Archive: %s', objectLabel) default: return option.label } } function buildRuleTargetKey(rule: Pick): string { return JSON.stringify({ action: rule.action, scope: rule.scope, termId: rule.termId ?? null, postId: rule.postId ?? null, }) } function hasExistingSummary(link: Pick): boolean { return typeof link.summary === 'string' && link.summary.trim() !== '' } function parseInternalLinkKeywords(raw: string | null): string[] { if (raw == null || raw === 0 as unknown) { return [] } const str = typeof raw === 'string' ? raw : String(raw) const trimmed = str.trim() if (trimmed === '' || trimmed === '0' || trimmed === '[]') { return [] } if (trimmed.startsWith('[')) { try { const parsed = JSON.parse(trimmed) if (Array.isArray(parsed)) { return Array.from( new Set( parsed .map(item => String(item || '').trim()) .filter(k => k.length > 0 && k !== '0'), ), ).slice(0, 10) } } catch { // Fall back to delimiter parsing below. } } return Array.from( new Set( trimmed .split(/\s*\|\s*|\s*,\s*|\n+/) .map(item => item.trim()) .filter(k => k.length > 0 && k !== '0'), ), ).slice(0, 10) } export default function LinksPage() { const { dataLanguage } = useDataLanguage() const [tab, setTab] = useState('internal') const [internalLinks, setInternalLinks] = useState([]) const [externalLinks, setExternalLinks] = useState([]) const [internalStats, setInternalStats] = useState({ total: 0, analyzed: 0, unanalyzed: 0 }) const [loading, setLoading] = useState(true) const [collectResult, setCollectResult] = useState(null) const [collectTone, setCollectTone] = useState<'success' | 'error'>('success') const [statsError, setStatsError] = useState(null) const [rulesActionError, setRulesActionError] = useState(null) const [analyzing, setAnalyzing] = useState(false) const [analyzeResult, setAnalyzeResult] = useState(null) const [analyzeResultTone, setAnalyzeResultTone] = useState<'success' | 'warning' | 'error'>('success') const [batchProgress, setBatchProgress] = useState(null) const cancelAnalyzeAllRef = useRef(false) const [showAddForm, setShowAddForm] = useState(false) const [newUrl, setNewUrl] = useState('') const [newTitle, setNewTitle] = useState('') const [newKeyword, setNewKeyword] = useState('') const [saving, setSaving] = useState(false) const [extAnalyzing, setExtAnalyzing] = useState(false) const [extAnalyzeResult, setExtAnalyzeResult] = useState(null) const [extAnalyzeResultTone, setExtAnalyzeResultTone] = useState<'success' | 'warning' | 'error'>('success') const [extBatchProgress, setExtBatchProgress] = useState(null) const cancelExtAnalyzeRef = useRef(false) const [selectedInternalLinkIds, setSelectedInternalLinkIds] = useState([]) const [selectedExternalIds, setSelectedExternalIds] = useState([]) const [bulkActionInFlight, setBulkActionInFlight] = useState(false) const [perPage, setPerPage] = useState(50) const [currentPage, setCurrentPage] = useState(1) const { rules: savedRules, loading: rulesLoading, error: rulesLoadError, reload: reloadRules } = useLinkRules() const { scopeOptions, loading: scopeOptionsLoading, error: scopeOptionsError } = useScopeOptions() const collectLinkRules = useCollectLinkRules() const deleteLinkIndex = useDeleteLinkIndex() const [draftRules, setDraftRules] = useState([createEmptyLinkRule()]) const isRulesDirty = useMemo(() => !areLinkRulesEqual(draftRules, savedRules), [draftRules, savedRules]) const userEditedRef = useRef(false) const prevDataLanguageRef = useRef(dataLanguage) useEffect(() => { const languageChanged = prevDataLanguageRef.current !== dataLanguage prevDataLanguageRef.current = dataLanguage if (languageChanged || !userEditedRef.current) { setDraftRules(savedRules.length > 0 ? savedRules : [createEmptyLinkRule()]) userEditedRef.current = false } }, [dataLanguage, savedRules]) const fetchRequestIdRef = useRef(0) const fetchLinks = useCallback(async () => { const thisRequest = ++fetchRequestIdRef.current setLoading(true) try { const [intRes, extRes] = await Promise.all([ endpoints.getInternalLinks(), endpoints.getExternalLinks(), ]) if (fetchRequestIdRef.current !== thisRequest) return const internalData = (intRes.data as InternalLink[]) || [] const externalData = (extRes.data as ExternalLinkItem[]) || [] setInternalLinks(internalData) setExternalLinks(externalData) try { const statsRes = await endpoints.getInternalLinkStats() if (fetchRequestIdRef.current !== thisRequest) return setInternalStats((statsRes.data as InternalLinkStats) || { total: 0, analyzed: 0, unanalyzed: 0 }) setStatsError(null) } catch { if (fetchRequestIdRef.current !== thisRequest) return const unanalyzed = internalData.filter(link => !link.ai_analyzed).length setInternalStats({ total: internalData.length, analyzed: internalData.length - unanalyzed, unanalyzed, }) setStatsError(t('Unable to load link stats')) } } catch { if (fetchRequestIdRef.current !== thisRequest) return } finally { if (fetchRequestIdRef.current === thisRequest) { setLoading(false) } } }, [dataLanguage]) useEffect(() => { void fetchLinks() }, [fetchLinks]) useEffect(() => { setSelectedInternalLinkIds(prev => { if (prev.length === 0) { return prev } const nextAvailableIds = new Set(internalLinks.map(link => link.id)) const filteredIds = prev.filter(id => nextAvailableIds.has(id)) return filteredIds.length === prev.length ? prev : filteredIds }) }, [internalLinks]) useEffect(() => { setSelectedExternalIds(prev => { if (prev.length === 0) return prev const available = new Set(externalLinks.map(l => l.id)) const filtered = prev.filter(id => available.has(id)) return filtered.length === prev.length ? prev : filtered }) }, [externalLinks]) const handleRemoveRule = (ruleId: string) => { userEditedRef.current = true setDraftRules(prev => { const next = prev.filter(rule => rule.id !== ruleId) return next.length > 0 ? next : [createEmptyLinkRule()] }) } const handleRemoveRuleGroup = useCallback((ruleIds: string[]) => { userEditedRef.current = true setDraftRules(prev => { const idsToRemove = new Set(ruleIds) const next = prev.filter(r => !idsToRemove.has(r.id)) return next.length > 0 ? next : [createEmptyLinkRule()] }) }, []) const handleReplaceGroupItems = useCallback(( groupRuleIds: string[], template: Pick, newItems: Array> ) => { userEditedRef.current = true setDraftRules(prev => { const idsToRemove = new Set(groupRuleIds) const kept = prev.filter(r => !idsToRemove.has(r.id)) if (newItems.length === 0) { return kept.length > 0 ? kept : [createEmptyLinkRule()] } const newRules: LinkRule[] = newItems.map(item => ({ ...createEmptyLinkRule(), action: template.action, scope: template.scope, termId: item.termId ?? null, termName: item.termName ?? null, postId: item.postId ?? null, postTitle: item.postTitle ?? null, })) return [...kept, ...newRules] }) }, []) const handleAddNewGroup = useCallback(( action: 'include' | 'exclude', scope: string, items: Array> ) => { userEditedRef.current = true setDraftRules(prev => { const isOnlyDefault = prev.length === 1 && prev[0].scope === 'all' && prev[0].action === 'include' && !prev[0].termId && !prev[0].postId const base = isOnlyDefault ? [] : [...prev] const existingTargets = new Set(base.map(r => buildRuleTargetKey(r))) if (items.length === 0) { const newRule: LinkRule = { ...createEmptyLinkRule(), action, scope } if (!existingTargets.has(buildRuleTargetKey(newRule))) { base.push(newRule) } } else { items.forEach(item => { const newRule: LinkRule = { ...createEmptyLinkRule(), action, scope, termId: item.termId ?? null, termName: item.termName ?? null, postId: item.postId ?? null, postTitle: item.postTitle ?? null, } if (!existingTargets.has(buildRuleTargetKey(newRule))) { base.push(newRule) existingTargets.add(buildRuleTargetKey(newRule)) } }) } return base.length > 0 ? base : [createEmptyLinkRule()] }) }, []) const handleSaveAndCollect = async () => { setRulesActionError(null) setCollectResult(null) const isDefaultEmpty = draftRules.length === 1 && draftRules[0].scope === 'all' && draftRules[0].action === 'include' && !draftRules[0].termId && !draftRules[0].postId if (isDefaultEmpty) { setRulesActionError(t('Please add at least one collection rule before collecting links.')) return } try { const result = await collectLinkRules.collect(draftRules) setCollectResult(tf('%d new, %d updated, %d removed', result.added, result.updated, result.removed)) setCollectTone('success') userEditedRef.current = false await Promise.all([reloadRules(), fetchLinks()]) } catch (error: any) { const message = error?.message || t('Error collecting links') setRulesActionError(message) setCollectResult(message) setCollectTone('error') } } const handleDeleteIndex = async () => { if (!confirm(t('Are you sure you want to delete the entire link index?'))) return setRulesActionError(null) setCollectResult(null) try { await deleteLinkIndex.remove() setCollectResult(t('Link index deleted')) setCollectTone('success') await fetchLinks() } catch (error: any) { const message = error?.message || t('Error deleting link index') setRulesActionError(message) setCollectResult(message) setCollectTone('error') } } const handleAddExternal = async () => { if (!newUrl) return setSaving(true) try { await endpoints.createExternalLink({ url: newUrl, title: newTitle, keyword: newKeyword }) setNewUrl('') setNewTitle('') setNewKeyword('') setShowAddForm(false) await fetchLinks() } catch { // ignore } finally { setSaving(false) } } const handleDeleteInternal = async (id: number) => { if (!confirm(t('Delete this link from the library?'))) return await endpoints.deleteInternalLink(id) setInternalLinks(prev => prev.filter(l => l.id !== id)) setSelectedInternalLinkIds(prev => prev.filter(linkId => linkId !== id)) setInternalStats(prev => { const deleted = internalLinks.find(link => link.id === id) if (!deleted) return prev const analyzedDelta = deleted.ai_analyzed ? 1 : 0 const unanalyzedDelta = deleted.ai_analyzed ? 0 : 1 return { total: Math.max(0, prev.total - 1), analyzed: Math.max(0, prev.analyzed - analyzedDelta), unanalyzed: Math.max(0, prev.unanalyzed - unanalyzedDelta), } }) } const selectedInternalLinkIdSet = useMemo(() => new Set(selectedInternalLinkIds), [selectedInternalLinkIds]) const totalPages = Math.max(1, Math.ceil(internalLinks.length / perPage)) const safePage = Math.min(currentPage, totalPages) const visibleInternalLinks = useMemo( () => internalLinks.slice((safePage - 1) * perPage, safePage * perPage), [internalLinks, safePage, perPage], ) const visibleInternalLinkIds = useMemo(() => visibleInternalLinks.map(link => link.id), [visibleInternalLinks]) const allVisibleSelected = visibleInternalLinkIds.length > 0 && visibleInternalLinkIds.every(id => selectedInternalLinkIdSet.has(id)) const hasSelectedInternalLinks = selectedInternalLinkIds.length > 0 const selectedInternalLinks = useMemo( () => internalLinks.filter(link => selectedInternalLinkIdSet.has(link.id)), [internalLinks, selectedInternalLinkIdSet], ) const linksMissingSummaries = useMemo( () => internalLinks.filter(link => !hasExistingSummary(link)), [internalLinks], ) const linksWithSummaries = useMemo( () => internalLinks.filter(hasExistingSummary), [internalLinks], ) const smartAnalyzeTargets = useMemo( () => hasSelectedInternalLinks ? selectedInternalLinks : linksMissingSummaries, [hasSelectedInternalLinks, selectedInternalLinks, linksMissingSummaries], ) const reanalyzeTargets = useMemo( () => hasSelectedInternalLinks ? selectedInternalLinks.filter(hasExistingSummary) : linksWithSummaries, [hasSelectedInternalLinks, selectedInternalLinks, linksWithSummaries], ) const smartAnalyzeCount = smartAnalyzeTargets.length const reanalyzeAllCount = reanalyzeTargets.length const handleToggleInternalSelection = (id: number) => { setSelectedInternalLinkIds(prev => ( prev.includes(id) ? prev.filter(item => item !== id) : [...prev, id] )) } const handleToggleVisibleInternalSelection = () => { setSelectedInternalLinkIds(prev => { const next = new Set(prev) if (allVisibleSelected) { visibleInternalLinkIds.forEach(id => next.delete(id)) } else { visibleInternalLinkIds.forEach(id => next.add(id)) } return Array.from(next) }) } const handleBulkDeleteInternal = async () => { if (bulkActionInFlight || selectedInternalLinkIds.length === 0) { return } if (!confirm(tf('Are you sure you want to delete %d selected links?', selectedInternalLinkIds.length))) { return } setBulkActionInFlight(true) try { await endpoints.bulkDeleteInternalLinks(selectedInternalLinkIds) await fetchLinks() setSelectedInternalLinkIds([]) } catch (err) { setRulesActionError(getErrorMessage(err, t('Bulk action failed'))) } finally { setBulkActionInFlight(false) } } const handleBulkRemoveFromPosts = async () => { if (bulkActionInFlight || selectedInternalLinkIds.length === 0) { return } if (!confirm(tf('Remove %d selected links from all posts? The links will remain in your inventory but will be unlinked from post content.', selectedInternalLinkIds.length))) { return } setBulkActionInFlight(true) try { const linkIds = selectedInternalLinks.map(link => `internal-${link.post_id}`) const res = await endpoints.bulkRemoveLinksFromPosts(linkIds) const data = res.data as { affected_posts: number } alert(tf('Removed links from %d posts', data.affected_posts)) } catch (err) { setRulesActionError(getErrorMessage(err, t('Bulk action failed'))) } finally { setBulkActionInFlight(false) } } const handleDeleteExternal = async (id: number) => { if (!confirm(t('Delete this link from the library?'))) return await endpoints.deleteExternalLink(id) setExternalLinks(prev => prev.filter(l => l.id !== id)) } const handleToggleActive = async (link: ExternalLinkItem) => { await endpoints.updateExternalLink(link.id, { active: link.active ? 0 : 1 }) setExternalLinks(prev => prev.map(l => l.id === link.id ? { ...l, active: l.active ? 0 : 1 } : l)) } const selectedExternalIdSet = useMemo(() => new Set(selectedExternalIds), [selectedExternalIds]) const hasSelectedExternalLinks = selectedExternalIds.length > 0 const handleToggleExternalSelection = (id: number) => { setSelectedExternalIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id], ) } const handleToggleAllExternalSelection = () => { setSelectedExternalIds(prev => { const allIds = externalLinks.map(l => l.id) const allSelected = allIds.length > 0 && allIds.every(id => new Set(prev).has(id)) return allSelected ? [] : allIds }) } const handleBulkDeleteExternal = async () => { if (bulkActionInFlight || selectedExternalIds.length === 0) return if (!confirm(tf('Are you sure you want to delete %d selected links?', selectedExternalIds.length))) return setBulkActionInFlight(true) try { await endpoints.bulkDeleteExternalLinks(selectedExternalIds) await fetchLinks() setSelectedExternalIds([]) } catch (err) { setExtAnalyzeResult(getErrorMessage(err, t('Bulk action failed'))) setExtAnalyzeResultTone('error') } finally { setBulkActionInFlight(false) } } const handleBulkRemoveExternalFromPosts = async () => { if (bulkActionInFlight || selectedExternalIds.length === 0) return if (!confirm(tf('Remove %d selected links from all posts? The links will remain in your inventory but will be unlinked from post content.', selectedExternalIds.length))) return setBulkActionInFlight(true) try { const linkIds = selectedExternalIds.map(id => `external-${id}`) const res = await endpoints.bulkRemoveLinksFromPosts(linkIds) const data = res.data as { affected_posts: number } alert(tf('Removed links from %s posts', data.affected_posts)) } catch (err) { setExtAnalyzeResult(getErrorMessage(err, t('Bulk action failed'))) setExtAnalyzeResultTone('error') } finally { setBulkActionInFlight(false) } } const isInsufficientCreditsReason = (reason?: string | null): boolean => ( String(reason || '').toLowerCase().includes('insufficient credit') ) const formatStoppedAnalysisMessage = (reason: string, analyzed: number, total: number): string => ( isInsufficientCreditsReason(reason) ? tf('Analysis stopped: insufficient credits. %s of %s pages analyzed.', analyzed, total) : tf('Analysis stopped: %s. %s of %s pages analyzed.', reason, analyzed, total) ) const runAnalysisBatches = async (targetLinks: InternalLink[], includeAnalyzed: boolean) => { const totalToAnalyze = targetLinks.length const targetIds = targetLinks.map(link => link.id) cancelAnalyzeAllRef.current = false setAnalyzing(true) setAnalyzeResult(null) setBatchProgress({ total: totalToAnalyze, completed: 0, remaining: totalToAnalyze, creditsUsed: 0, startedAt: Date.now(), cancelRequested: false, }) let analyzedCount = 0 let attempted = 0 let creditsUsed = 0 const batchWarnings: string[] = [] try { for (let offset = 0; offset < targetIds.length; offset += 3) { const batchIds = targetIds.slice(offset, offset + 3) const res = await endpoints.analyzeInternalLinks({ ids: batchIds, limit: batchIds.length, includeAnalyzed, }) const data = res.data as AnalyzeBatchResponse const batchAnalyzed = Number(data.analyzed ?? 0) const batchCredits = Number(data.credits_used ?? 0) const nextAttempted = Math.min(totalToAnalyze, offset + batchIds.length) analyzedCount += batchAnalyzed attempted = nextAttempted creditsUsed += batchCredits setBatchProgress(prev => prev ? { ...prev, completed: attempted, remaining: Math.max(0, totalToAnalyze - attempted), creditsUsed, } : prev) if (cancelAnalyzeAllRef.current) { break } if (data.stopped_reason) { batchWarnings.push(data.stopped_reason) } } if (cancelAnalyzeAllRef.current) { setAnalyzeResult(tf('Analysis cancelled after %s pages analyzed.', analyzedCount)) setAnalyzeResultTone('warning') } else if (batchWarnings.length > 0) { setAnalyzeResult(formatStoppedAnalysisMessage(batchWarnings[batchWarnings.length - 1], analyzedCount, totalToAnalyze)) setAnalyzeResultTone('warning') } else { setAnalyzeResult(tf('Analysis complete: %s pages analyzed', analyzedCount)) setAnalyzeResultTone('success') } } catch (err: unknown) { const status = typeof err === 'object' && err !== null && 'status' in err ? Number((err as { status?: number }).status) : 0 if (status === 402) { setAnalyzeResult(tf('Analyzed %s pages. Ran out of BoostCoins. Purchase more to continue.', analyzedCount)) setAnalyzeResultTone('warning') } else { setAnalyzeResult(t('Error analyzing links')) setAnalyzeResultTone('error') } } finally { cancelAnalyzeAllRef.current = false setAnalyzing(false) setBatchProgress(null) await fetchLinks() } } const handleAnalyzeWithAI = async () => { const totalToAnalyze = smartAnalyzeCount const includeAnalyzed = hasSelectedInternalLinks if (totalToAnalyze === 0) { setAnalyzeResult( hasSelectedInternalLinks ? t('No selected pages available for AI analysis') : t('No unanalyzed pages remaining'), ) setAnalyzeResultTone('success') return } const estimatedCost = formatCoins(totalToAnalyze * 0.5) let confirmationMessage = hasSelectedInternalLinks ? tf( 'Analyze %d selected pages.\nEstimated cost: ~%s BoostCoins.\nThis may take several minutes for large sites.', totalToAnalyze, estimatedCost, ) : tf( 'Analyze %d unanalyzed pages.\nEstimated cost: ~%s BoostCoins.\nThis may take several minutes for large sites.', totalToAnalyze, estimatedCost, ) try { const creditsRes = await endpoints.getCreditsStatus() const remainingCredits = Number((creditsRes.data as { boost_credits?: { remaining?: number } })?.boost_credits?.remaining ?? 0) if (remainingCredits < totalToAnalyze * 0.5) { confirmationMessage += `\n\n${tf('You have %s BoostCoins but this will cost approximately %s. Analysis will stop when credits run out.\n\nContinue?', formatCoins(remainingCredits), estimatedCost)}` } } catch { // Ignore credit lookup failures; batch analysis can still proceed. } if (!confirm(confirmationMessage)) { return } await runAnalysisBatches(smartAnalyzeTargets, includeAnalyzed) } const handleReanalyzeAll = async () => { const totalToAnalyze = reanalyzeAllCount if (totalToAnalyze === 0) { setAnalyzeResult( hasSelectedInternalLinks ? t('No selected pages have summaries to re-analyze') : t('No pages with summaries are available for re-analysis'), ) setAnalyzeResultTone('success') return } const estimatedCost = formatCoins(totalToAnalyze * 0.5) let confirmationMessage = `${ hasSelectedInternalLinks ? tf('Re-analyze %d selected pages? This will overwrite existing summaries.', totalToAnalyze) : tf('Re-analyze %d pages with existing summaries? This will overwrite those summaries.', totalToAnalyze) }\n${tf('Estimated cost: ~%s BoostCoins.', estimatedCost)}` try { const creditsRes = await endpoints.getCreditsStatus() const remainingCredits = Number((creditsRes.data as { boost_credits?: { remaining?: number } })?.boost_credits?.remaining ?? 0) if (remainingCredits < totalToAnalyze * 0.5) { confirmationMessage += `\n\n${tf('You have %s BoostCoins but this will cost approximately %s. Analysis will stop when credits run out.\n\nContinue?', formatCoins(remainingCredits), estimatedCost)}` } } catch { // Ignore credit lookup failures; batch analysis can still proceed. } if (!confirm(confirmationMessage)) { return } await runAnalysisBatches(reanalyzeTargets, true) } const handleCancelAnalyzeAll = () => { cancelAnalyzeAllRef.current = true setBatchProgress(prev => prev ? { ...prev, cancelRequested: true } : prev) setAnalyzeResult(t('Cancel requested. The current batch will finish first.')) setAnalyzeResultTone('warning') } const selectedExternalLinks = useMemo( () => externalLinks.filter(l => selectedExternalIdSet.has(l.id)), [externalLinks, selectedExternalIdSet], ) const extSmartAnalyzeTargets = useMemo( () => hasSelectedExternalLinks ? selectedExternalLinks : externalLinks.filter(l => l.active && !l.ai_analyzed), [hasSelectedExternalLinks, selectedExternalLinks, externalLinks], ) const extSmartAnalyzeCount = extSmartAnalyzeTargets.length const runExtAnalysisBatches = async (targetLinks: ExternalLinkItem[], includeAnalyzed: boolean) => { const totalToAnalyze = targetLinks.length const targetIds = targetLinks.map(l => l.id) cancelExtAnalyzeRef.current = false setExtAnalyzing(true) setExtAnalyzeResult(null) setExtBatchProgress({ total: totalToAnalyze, completed: 0, remaining: totalToAnalyze, creditsUsed: 0, startedAt: Date.now(), cancelRequested: false, }) let analyzedCount = 0 let attempted = 0 let creditsUsed = 0 try { for (let offset = 0; offset < targetIds.length; offset += 3) { const batchIds = targetIds.slice(offset, offset + 3) const res = await endpoints.analyzeExternalLinks({ ids: batchIds, limit: batchIds.length, include_analyzed: includeAnalyzed, }) const data = res.data as AnalyzeBatchResponse const batchAnalyzed = Number(data.analyzed ?? 0) const batchCredits = Number(data.credits_used ?? 0) const nextAttempted = Math.min(totalToAnalyze, offset + batchIds.length) analyzedCount += batchAnalyzed attempted = nextAttempted creditsUsed += batchCredits setExtBatchProgress(prev => prev ? { ...prev, completed: attempted, remaining: Math.max(0, totalToAnalyze - attempted), creditsUsed, } : prev) if (cancelExtAnalyzeRef.current) break if (data.stopped_reason) { setExtAnalyzeResult(formatStoppedAnalysisMessage(data.stopped_reason, analyzedCount, totalToAnalyze)) setExtAnalyzeResultTone('warning') break } } if (!cancelExtAnalyzeRef.current && !extAnalyzeResult) { setExtAnalyzeResult(tf('Analysis complete: %s links analyzed', analyzedCount)) setExtAnalyzeResultTone('success') } else if (cancelExtAnalyzeRef.current) { setExtAnalyzeResult(tf('Analysis cancelled after %s links analyzed.', analyzedCount)) setExtAnalyzeResultTone('warning') } } catch (err: unknown) { const status = typeof err === 'object' && err !== null && 'status' in err ? Number((err as { status?: number }).status) : 0 if (status === 402) { setExtAnalyzeResult(tf('Analyzed %s links. Ran out of BoostCoins. Purchase more to continue.', analyzedCount)) setExtAnalyzeResultTone('warning') } else { setExtAnalyzeResult(t('Error analyzing external links')) setExtAnalyzeResultTone('error') } } finally { cancelExtAnalyzeRef.current = false setExtAnalyzing(false) setExtBatchProgress(null) await fetchLinks() } } const handleAnalyzeExternalLinks = async () => { const totalToAnalyze = extSmartAnalyzeCount const includeAnalyzed = hasSelectedExternalLinks if (totalToAnalyze === 0) { setExtAnalyzeResult( hasSelectedExternalLinks ? t('No selected links available for AI analysis') : t('All external links already analyzed'), ) setExtAnalyzeResultTone('success') return } const estimatedCost = formatCoins(totalToAnalyze * 0.5) let confirmationMessage = hasSelectedExternalLinks ? tf( 'Analyze %d selected external links.\nEstimated cost: ~%s BoostCoins.', totalToAnalyze, estimatedCost, ) : tf( 'Analyze %d unanalyzed external links.\nEstimated cost: ~%s BoostCoins.', totalToAnalyze, estimatedCost, ) try { const creditsRes = await endpoints.getCreditsStatus() const remainingCredits = Number((creditsRes.data as { boost_credits?: { remaining?: number } })?.boost_credits?.remaining ?? 0) if (remainingCredits < totalToAnalyze * 0.5) { confirmationMessage += `\n\n${tf('You have %s BoostCoins but this will cost approximately %s. Analysis will stop when credits run out.\n\nContinue?', formatCoins(remainingCredits), estimatedCost)}` } } catch { // ignore } if (!confirm(confirmationMessage)) return await runExtAnalysisBatches(extSmartAnalyzeTargets, includeAnalyzed) } const handleCancelExtAnalyze = () => { cancelExtAnalyzeRef.current = true setExtBatchProgress(prev => prev ? { ...prev, cancelRequested: true } : prev) setExtAnalyzeResult(t('Cancel requested. The current batch will finish first.')) setExtAnalyzeResultTone('warning') } const extProgressPercent = extBatchProgress && extBatchProgress.total > 0 ? Math.min(100, (extBatchProgress.completed / extBatchProgress.total) * 100) : 0 const extEstimatedRemainingTime = extBatchProgress && extBatchProgress.completed > 0 ? formatDuration(((Date.now() - extBatchProgress.startedAt) / extBatchProgress.completed) * extBatchProgress.remaining) : t('Calculating...') const handleRemoveFromPosts = async (linkId: string) => { if (!confirm(t('Remove this link from all generated posts? The text will be kept but the link will be removed.'))) return const res = await endpoints.removeLinkFromPosts(linkId) const data = res.data as { affected_posts: number } alert(tf('Removed link from %s posts', data.affected_posts)) } const progressPercent = batchProgress && batchProgress.total > 0 ? Math.min(100, (batchProgress.completed / batchProgress.total) * 100) : 0 const estimatedRemainingTime = batchProgress && batchProgress.completed > 0 ? formatDuration(((Date.now() - batchProgress.startedAt) / batchProgress.completed) * batchProgress.remaining) : t('Calculating...') const analyzeResultStyles = { success: 'text-emerald-600 bg-emerald-50 border-emerald-200', warning: 'text-amber-700 bg-amber-50 border-amber-200', error: 'text-red-600 bg-red-50 border-red-200', } as const const pendingAnalysisCount = smartAnalyzeCount const totalInternalLinks = internalStats.total || internalLinks.length const rulesPanelLoading = rulesLoading || scopeOptionsLoading if (loading) { return (
{t('Loading...')}
) } return (
{ void fetchLinks(); void reloadRules() }} helpContent={[ t('Internal links help search engines understand your site and improve SEO rankings.'), t('Set up collection rules to gather links from your existing content.'), t('When smart linking is enabled, the AI automatically weaves relevant internal links into generated articles.'), t('You can also add external link sources for the AI to reference.'), ]} />
{tab === 'internal' && (
{collectResult && (
{collectResult}
)} {rulesActionError && !collectResult && (
{rulesActionError}
)} {(rulesLoadError || scopeOptionsError) && (
{(rulesLoadError || scopeOptionsError)?.message || t('Error loading link rules')}
)} {statsError && (
{statsError}
)} {analyzeResult && (
{analyzeResult}
)}

{t('Internal Links')}

{tf('%s pages in library', totalInternalLinks)}

{internalLinks.length > 0 && !batchProgress && ( <> {reanalyzeAllCount > 0 && ( )} {hasSelectedInternalLinks && ( <> )} )}
{internalLinks.length > 0 && !batchProgress && hasSelectedInternalLinks && (

{t('"Remove from all posts" strips link shortcodes from content (text preserved).')}

{t('"Delete selected" removes links from the inventory only — existing shortcodes in posts will render as plain text.')}

)} {internalLinks.length > 0 && !batchProgress && (
{hasSelectedInternalLinks ? tf('%d rows selected. AI actions will only work on selected rows.', selectedInternalLinkIds.length) : null}
)} {batchProgress && (
{tf('Analyzing... %s of %s pages', batchProgress.completed, batchProgress.total)}
{tf('Pages remaining: %s', batchProgress.remaining)}
{tf('Credits used: %s', formatCoins(batchProgress.creditsUsed))}
{tf('Estimated time remaining: %s', estimatedRemainingTime)}
{batchProgress.cancelRequested &&
{t('Cancel requested. The current batch will finish first.')}
}
)}
{analyzing && !batchProgress && (
{tf('%s pages need analysis', pendingAnalysisCount)}
)} {internalLinks.length === 0 ? (

{t('No internal links yet')}

{t('Click "Save & Collect Links" to scan your site')}

) : (
{visibleInternalLinks.map(link => ( ))}
{t('Title')} {t('Type')} {t('Summary')} {t('Keywords')} {t('AI')} {t('Actions')}
handleToggleInternalSelection(link.id)} className="h-4 w-4 rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary" aria-label={tf('Select %s', link.title || `#${link.post_id}`)} /> {link.title || `#${link.post_id}`} {link.post_type} {link.ai_analyzed ? ( {t('Analyzed')} ) : ( — )}
{internalLinks.length > perPage && (
{tf('Showing %s–%s of %s', (safePage - 1) * perPage + 1, Math.min(safePage * perPage, internalLinks.length), internalLinks.length, )}
{tf('%s / %s', safePage, totalPages)}
)}
)}
)} {tab === 'external' && (

{t('External Links')}

{tf('%s links configured', externalLinks.length)}

{externalLinks.length > 0 && !extBatchProgress && ( <> {hasSelectedExternalLinks && ( <> )} )}
{externalLinks.length > 0 && !extBatchProgress && hasSelectedExternalLinks && (
{tf('%d rows selected. AI actions will only work on selected rows.', selectedExternalIds.length)}
)} {extBatchProgress && (
{tf('Analyzing... %s of %s links', extBatchProgress.completed, extBatchProgress.total)}
{tf('Links remaining: %s', extBatchProgress.remaining)}
{tf('Credits used: %s', formatCoins(extBatchProgress.creditsUsed))}
{tf('Estimated time remaining: %s', extEstimatedRemainingTime)}
{extBatchProgress.cancelRequested &&
{t('Cancel requested. The current batch will finish first.')}
}
)}
{extAnalyzeResult && (
{extAnalyzeResult}
)} {showAddForm && (
setNewUrl(e.target.value)} placeholder={t('https://example.com')} className="rounded-bc border border-bc-gray-300 px-3 py-2 text-sm" dir="ltr" /> setNewTitle(e.target.value)} placeholder={t('Title (optional, auto-filled by AI)')} className="rounded-bc border border-bc-gray-300 px-3 py-2 text-sm" /> setNewKeyword(e.target.value)} placeholder={t('Keyword override (optional)')} className="rounded-bc border border-bc-gray-300 px-3 py-2 text-sm" />
)} {externalLinks.length === 0 ? (

{t('No external links yet')}

{t('Add external URLs that AI should reference in generated content')}

) : (
{externalLinks.map(link => ( ))}
0 && selectedExternalIds.length === externalLinks.length} onChange={handleToggleAllExternalSelection} className="h-4 w-4 rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary" aria-label={selectedExternalIds.length === externalLinks.length ? t('Deselect all') : t('Select all')} /> {t('Title')} {t('URL')} {t('Summary')} {t('Keywords')} {t('AI')} {t('Active')} {t('Actions')}
handleToggleExternalSelection(link.id)} className="h-4 w-4 rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary" aria-label={tf('Select %s', link.title || link.url)} /> {link.title || link.keyword || '—'} {link.url.length > 35 ? link.url.substring(0, 35) + '...' : link.url} {link.ai_analyzed ? ( {t('Analyzed')} ) : ( — )}
)} )}
) } const MAX_VISIBLE_CHIPS = 15 interface RuleGroup { key: string action: 'include' | 'exclude' scope: string scopeOption: ScopeOption | undefined rules: LinkRule[] } function groupRulesByType(rules: LinkRule[], scopeOptions: ScopeOption[]): RuleGroup[] { const groups = new Map() for (const rule of rules) { const scopeOption = scopeOptions.find(o => o.value === rule.scope) const key = `${rule.action}:${rule.scope}` if (!groups.has(key)) { groups.set(key, { key, action: rule.action, scope: rule.scope, scopeOption, rules: [] }) } groups.get(key)!.rules.push(rule) } return Array.from(groups.values()) } function getRuleGroupHeaderLabel(scopeOption: ScopeOption | undefined, scope: string): string { if (!scopeOption) return scope switch (scopeOption.kind) { case 'all': return t('All content') case 'post_type': return scopeOption.objectLabel || scopeOption.label case 'taxonomy': return `${getScopeGroupLabel(scopeOption.group)} • ${scopeOption.objectLabel || scopeOption.label}` case 'archive': return `${getScopeGroupLabel(scopeOption.group)} • ${getScopeOptionLabel(scopeOption)}` case 'post': return scopeOption.objectLabel || scopeOption.label default: return scopeOption.label } } function LinkRulesCard({ rules, scopeOptions, loading, isDirty, onRemoveRule, onRemoveRuleGroup, onReplaceGroupItems, onAddNewGroup, onSaveAndCollect, onDeleteIndex, saveLoading, deleteLoading, }: { rules: LinkRule[] scopeOptions: ScopeOption[] loading: boolean isDirty: boolean onRemoveRule: (ruleId: string) => void onRemoveRuleGroup: (ruleIds: string[]) => void onReplaceGroupItems: ( groupRuleIds: string[], template: Pick, newItems: Array> ) => void onAddNewGroup: ( action: 'include' | 'exclude', scope: string, items: Array> ) => void onSaveAndCollect: () => void onDeleteIndex: () => void saveLoading: boolean deleteLoading: boolean }) { const [showAddForm, setShowAddForm] = useState(false) const isDefaultEmpty = rules.length === 1 && rules[0].scope === 'all' && rules[0].action === 'include' && !rules[0].termId && !rules[0].postId const ruleGroups = useMemo(() => { if (isDefaultEmpty) return [] return groupRulesByType(rules, scopeOptions) }, [rules, scopeOptions, isDefaultEmpty]) return (

{t('Link Collection Rules')}

{t('Define which content is included in the internal links index')}

{t('Include or exclude by content type, taxonomy filters, archive pages, or individual items')}

{t('A narrower "Exclude" rule always overrides a broader "Include" rule')}

{loading ? (
{t('Loading...')}
) : (
{isDefaultEmpty && !showAddForm && (

{t('No rules configured. Click "Add Rule" to start.')}

)} {ruleGroups.map(group => ( onRemoveRuleGroup(group.rules.map(r => r.id))} onReplaceItems={newItems => onReplaceGroupItems( group.rules.map(r => r.id), { action: group.action, scope: group.scope }, newItems, )} disableActions={saveLoading || deleteLoading} /> ))} {showAddForm && ( { onAddNewGroup(action, scope, items) setShowAddForm(false) }} onCancel={() => setShowAddForm(false)} disableActions={saveLoading || deleteLoading} /> )}
)} {isDirty && (
{t('You have unsaved changes')}
)}
{t('Clicking "Save & Collect" saves the rules and collects internal links accordingly — unchanged content is automatically skipped')}
) } function RuleGroupCard({ group, onRemoveItem, onRemoveGroup, onReplaceItems, disableActions, }: { group: RuleGroup onRemoveItem: (ruleId: string) => void onRemoveGroup: () => void onReplaceItems: (newItems: Array>) => void disableActions: boolean }) { const [editing, setEditing] = useState(false) const scopeOption = group.scopeOption const needsTerm = !!scopeOption?.needsTerm const needsPost = !!scopeOption?.needsPost const hasItems = needsTerm || needsPost const isArchiveScope = scopeOption?.kind === 'archive' const displayItems = useMemo(() => { if (!hasItems) return [] return group.rules .map(rule => ({ ruleId: rule.id, label: needsTerm ? (rule.termName || (rule.termId ? `#${rule.termId}` : null)) : (rule.postTitle || (rule.postId ? `#${rule.postId}` : null)), })) .filter((item): item is { ruleId: string; label: string } => item.label != null) }, [group.rules, hasItems, needsTerm]) const visibleItems = displayItems.slice(0, MAX_VISIBLE_CHIPS) const hiddenCount = Math.max(0, displayItems.length - MAX_VISIBLE_CHIPS) const currentSelectedItems = useMemo(() => { if (needsTerm) { return group.rules .filter(r => r.termId != null) .map(r => ({ id: r.termId!, label: r.termName || `#${r.termId}` })) } if (needsPost) { return group.rules .filter(r => r.postId != null) .map(r => ({ id: r.postId!, label: r.postTitle || `#${r.postId}` })) } return [] }, [group.rules, needsTerm, needsPost]) const handleEditConfirm = useCallback((selected: { id: number; label: string }[]) => { onReplaceItems( selected.map(item => ({ termId: needsTerm ? item.id : null, termName: needsTerm ? item.label : null, postId: needsPost ? item.id : null, postTitle: needsPost ? item.label : null, })), ) setEditing(false) }, [needsTerm, needsPost, onReplaceItems]) return (
{getRuleGroupHeaderLabel(scopeOption, group.scope)} {group.action === 'include' ? t('Include') : t('Exclude')}
{hasItems && ( )}
{hasItems && displayItems.length > 0 && (
!disableActions && setEditing(true)} role="button" tabIndex={0} onKeyDown={e => e.key === 'Enter' && !disableActions && setEditing(true)} > {visibleItems.map(item => ( {item.label} ))} {hiddenCount > 0 && ( {tf('and %d more', hiddenCount)} )}
)} {hasItems && displayItems.length === 0 && (
!disableActions && setEditing(true)} role="button" tabIndex={0} onKeyDown={e => e.key === 'Enter' && !disableActions && setEditing(true)} > {t('Click to select items')}
)} {editing && hasItems && (
{needsTerm && scopeOption?.taxonomy && ( )} {needsPost && scopeOption?.postType && ( )}
)}
) } function GroupTermEditor({ taxonomy, scopeKind, selectedItems, disabled, onConfirm, }: { taxonomy: string scopeKind: 'taxonomy' | 'archive' selectedItems: { id: number; label: string }[] disabled: boolean onConfirm: (items: { id: number; label: string }[]) => void }) { const [searchTerm, setSearchTerm] = useState('') const { terms, loading } = useTaxonomyTerms(taxonomy) const items = useMemo(() => terms.map(term => ({ id: term.id, label: term.name, description: String(term.count), })), [terms]) return ( onConfirm(selected.map(item => ({ id: item.id, label: item.label })))} /> ) } function GroupPostEditor({ postType, selectedItems, disabled, onConfirm, }: { postType: string selectedItems: { id: number; label: string }[] disabled: boolean onConfirm: (items: { id: number; label: string }[]) => void }) { const { posts, loading, search, setSearch, hasMore, loadMore } = useScopePostsPicker(postType, 50, 50) const items = useMemo(() => posts.map(post => ({ id: post.id, label: post.title || `#${post.id}`, description: `#${post.id}`, })), [posts]) return ( onConfirm(selected.map(item => ({ id: item.id, label: item.label })))} /> ) } function AddRuleForm({ scopeOptions, onConfirm, onCancel, disableActions, }: { scopeOptions: ScopeOption[] onConfirm: ( action: 'include' | 'exclude', scope: string, items: Array> ) => void onCancel: () => void disableActions: boolean }) { const [action, setAction] = useState<'include' | 'exclude'>('include') const [scope, setScope] = useState('all') const currentScopeOption = scopeOptions.find(o => o.value === scope) const needsTerm = !!currentScopeOption?.needsTerm const needsPost = !!currentScopeOption?.needsPost const isArchiveScope = currentScopeOption?.kind === 'archive' const handleTermConfirm = (selected: { id: number; label: string }[]) => { onConfirm( action, scope, selected.map(item => ({ termId: item.id, termName: item.label, postId: null, postTitle: null })), ) } const handlePostConfirm = (selected: { id: number; label: string }[]) => { onConfirm( action, scope, selected.map(item => ({ postId: item.id, postTitle: item.label, termId: null, termName: null })), ) } return (
{needsTerm && currentScopeOption?.taxonomy && ( )} {needsPost && currentScopeOption?.postType && ( )} {!needsTerm && !needsPost && ( )}
) } function ScopeSelect({ value, options, disabled, onChange, }: { value: string options: ScopeOption[] disabled: boolean onChange: (scope: string) => void }) { const groups = useMemo(() => { const next = new Map() options.forEach(option => { const key = option.group || 'general' const current = next.get(key) || [] current.push(option) next.set(key, current) }) return Array.from(next.entries()) }, [options]) return ( ) }