import React, { useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { Loader2Icon, SparklesIcon, WandSparklesIcon } from 'lucide-react'; import { Button } from '../components/ui/button'; import EmptyState from '../components/agent-analytics/EmptyState'; import ErrorBanner from '../components/agent-analytics/ErrorBanner'; import InfoTooltip from '../components/agent-analytics/InfoTooltip'; import { getCompanyIdPushScanStatus } from '../service/company-id/company-id.service'; import CitedSourcesPanel from '../components/visibility/CitedSourcesPanel'; import CompetitorsTable from '../components/visibility/CompetitorsTable'; import FunnelCoveragePanel from '../components/visibility/FunnelCoveragePanel'; import GenerateIdeasModal from '../components/visibility/GenerateIdeasModal'; import InsufficientCreditsBanner from '../components/visibility/InsufficientCreditsBanner'; import { canSeeBetaVisibilityFeatures } from '../components/visibility/beta-access'; import { contentTypeLabel, getCurrentWeekIso, isoWeekFromTimestamp, PAGE_CONTENT_TYPES, } from '../components/visibility/helpers'; // eslint-disable-next-line import/no-named-as-default import DisclaimerDialog from '../components/visibility/DisclaimerDialog'; import MentionedVsCitedCallout from '../components/visibility/MentionedVsCitedCallout'; import NewCompetitorsBanner from '../components/visibility/NewCompetitorsBanner'; import OverviewPulse from '../components/visibility/OverviewPulse'; import ProblemsList from '../components/visibility/ProblemsList'; import PublishedArticlesList from '../components/visibility/PublishedArticlesList'; import RecommendedArticlesList from '../components/visibility/RecommendedArticlesList'; import SectionHeading from '../components/visibility/SectionHeading'; import SettingsDrawer from '../components/visibility/SettingsDrawer'; import ViewToggle, { useContentView, } from '../components/visibility/ViewToggle'; import TopCompetitorsHighlight from '../components/visibility/TopCompetitorsHighlight'; import TopWinsLosses from '../components/visibility/TopWinsLosses'; import TrackedCompetitorsPanel from '../components/visibility/TrackedCompetitorsPanel'; import TrackedPromptsList from '../components/visibility/TrackedPromptsList'; import TrendingInYourChat from '../components/visibility/TrendingInYourChat'; import VisibilityHeader from '../components/visibility/VisibilityHeader'; import VisibilityTabsList from '../components/visibility/VisibilityTabsList'; import type { VisibilityTabId } from '../components/visibility/VisibilityTabsList'; import HowToReadReport from '../components/visibility/HowToReadReport'; import KnowledgeBaseNotice from '../components/visibility/KnowledgeBaseNotice'; import { useAppStateContext } from '../context/user.data.context'; import { useContentSite } from '../lib/content-site'; import { recomaze_ai_personalization_env } from '../env'; import type { ArticleCounts, ArticleDetailResponse, ArticleSummary, BrandResponse, CompetitorLeaderboardResponse, ManualCompetitor, PageContentType, ProblemsResponse, ScanHistoryResponse, SuggestionEntry, SuggestionListResponse, VisibilitySettingsResponse, WeeklyReportResponse, } from '../service/visibility/visibility.interface'; import { InsufficientCreditsError, ScanAlreadyRunningError, ScanCooldownError, } from '../service/visibility/visibility.interface'; import { createBrand, fetchSettings, getBrand, getCompetitors, getScanRunStatus, getWeeklyReport, listArticles, listBrands, listProblems, listScans, listSuggestions, listTrackedCompetitors, startScan, } from '../service/visibility/visibility.service'; import { getStoreLanguage } from '../lib/store-language'; const SECTION_HELP = { competitors: "Every brand AI mentioned alongside yours for your monitored prompts this week. Your own brand is pinned at the top with a 'Your brand' badge so you can compare share of voice side-by-side; 'Δ vs last week' is the percentage-point change over the previous week. An empty list means AI didn't surface any brands at all this week, usually paired with a 'Problems detected' entry.", problems: "Issues the scanner found in this week's answers (AI citing competitors but not you, weak local presence, negative tone, etc.). Each problem links to the prompts that triggered it so you can decide whether to publish content, fix structured data, or tighten your tracked-prompts list.", articles: "Content ideas the agent thinks will move the needle next week, based on the prompts where AI ignored your brand. Click 'Generate' to draft the full post; the trash button next to each idea rejects it so it never comes back.", }; const SCAN_POLL_INTERVAL_MS = 5_000; const SCAN_POLL_MAX_MS = 15 * 60 * 1000; const POST_HISTORY_GRACE_MS = 3 * 60 * 1000; /** * Don't trust a "no scan running" status before this much polling has * elapsed: between dispatch and the worker picking the task up the running * marker doesn't exist yet, and releasing on that gap would unblur a scan * that is about to start. */ const SCAN_STATUS_RELEASE_MIN_MS = 30_000; /** How often the scan banner rotates to the next marketing message. */ const SCAN_MESSAGE_ROTATE_MS = 7_000; /** * Retry cadence for the brand list while a Company ID push is rebuilding a * brand that doesn't exist yet (the push provisions it in the background; * arriving here right after dispatch can beat the provisioning). */ const BRAND_PROVISION_RETRY_MS = 10_000; /** * AEO / GEO / Recomaze one-liners the scan banner cycles through while a * scan is in flight, so the wait doubles as a pitch for why the scan * matters. Rotated by ``scanMessageIndex`` every * {@link SCAN_MESSAGE_ROTATE_MS}. */ const SCAN_MARKETING_MESSAGES: string[] = [ 'More than half of searches now end without a click. The winners are the brands AI quotes directly in its answer.', 'GEO is the new SEO: instead of chasing link rankings, you earn mentions and citations inside AI generated answers.', 'AEO tip: a page that answers one buyer question clearly in its first paragraph gets cited far more often by AI engines.', 'ChatGPT, Gemini and Perplexity recommend brands they can verify. Consistent facts across your site teach them to trust yours.', 'Shoppers increasingly ask AI what to buy. Recomaze works to make your products part of that answer.', 'Every Recomaze scan probes real AI engines with real buyer prompts, so your score reflects what customers actually see.', 'AI engines favor structured, machine readable stores. Recomaze keeps your content and product data speaking their language.', 'Content that fills a visibility gap beats content for its own sake. Recomaze turns your weak prompts into targeted articles.', 'Your competitors are being recommended by AI right now. Weekly share of voice tracking shows exactly where you stand.', 'Brands mentioned in AI answers capture demand before a customer ever opens Google. That is the traffic AEO protects.', ]; /** The two lines a content site reads in its own words: it sells services, not products from a store. */ const CONTENT_SITE_SCAN_MESSAGE_SWAPS: Record = { 'Shoppers increasingly ask AI what to buy. Recomaze works to make your products part of that answer.': 'People increasingly ask AI who to hire and what to choose. Recomaze works to make your services part of that answer.', 'AI engines favor structured, machine readable stores. Recomaze keeps your content and product data speaking their language.': 'AI engines favor structured, machine readable sites. Recomaze keeps your content and your record speaking their language.', }; /** The scan banner's lines as a content site reads them. */ const CONTENT_SITE_SCAN_MARKETING_MESSAGES: string[] = SCAN_MARKETING_MESSAGES.map( message => CONTENT_SITE_SCAN_MESSAGE_SWAPS[message] ?? message ); /** Tabs for the Articles section. */ const ARTICLES_TABS: ReadonlyArray<{ id: 'recommended' | 'published'; label: string; }> = [ { id: 'recommended', label: 'Recommended' }, { id: 'published', label: 'Published' }, ]; /** * The report's own reading column. The page root no longer carries this * padding: the pinned header has to reach the very top edge of the scrolling * area, so every block BELOW it re-applies the gutters instead. */ const REPORT_COLUMN_CLASS = 'mx-auto w-full px-6 @2xl:px-10'; const ToastMessage = ({ content, onDismiss, duration = 3500, }: { content: string; onDismiss: () => void; duration?: number; }): JSX.Element => { useEffect(() => { const t = window.setTimeout(onDismiss, duration); return () => window.clearTimeout(t); }, [content, duration, onDismiss]); return (
{content}
); }; const AiVisibilityPage = (): JSX.Element => { const { token, clientId } = useAppStateContext(); const contentSite = useContentSite(); const scanMessages: string[] = contentSite ? CONTENT_SITE_SCAN_MARKETING_MESSAGES : SCAN_MARKETING_MESSAGES; const storeDomain = recomaze_ai_personalization_env?.domain || ''; const storeName = storeDomain; const [allowed, setAllowed] = useState(null); const [selectedWeek, setSelectedWeek] = useState(getCurrentWeekIso()); const [settings, setSettings] = useState( null ); const [brand, setBrand] = useState(null); const [weeklyReport, setWeeklyReport] = useState( null ); const [scanHistory, setScanHistory] = useState( null ); const [competitors, setCompetitors] = useState(null); const [trackedCompetitors, setTrackedCompetitors] = useState< ManualCompetitor[] >([]); const [problemsData, setProblemsData] = useState( null ); const [suggestions, setSuggestions] = useState( null ); const [articles, setArticles] = useState([]); const [articleCounts, setArticleCounts] = useState({ recommended: 0, published: 0, }); const [articlesTab, setArticlesTab] = useState<'recommended' | 'published'>( 'recommended' ); // Page-type filter applied to both article tabs. "all" shows every type; // the counts on the tabs stay on the full library (they don't re-derive). const [articleTypeFilter, setArticleTypeFilter] = useState< PageContentType | 'all' >('all'); const [activeTabId, setActiveTabId] = useState('overview'); const [contentView, setContentView] = useContentView(); /** * Switch panel and return to the top of the report. The tab bar lives in * the pinned header, so a merchant can switch from three screens down; the * panels are unmounted when inactive, so keeping the old offset drops them * into the middle of the new panel - or, when the new one is shorter, * clamps them to its very bottom. * * @param {VisibilityTabId} nextTabId - The panel to show. * @returns {void} */ const changeTab = useCallback((nextTabId: VisibilityTabId): void => { setActiveTabId(nextTabId); if (typeof document === 'undefined') return; const scroller = document.getElementById('main'); if (!scroller || scroller.scrollTop === 0) return; scroller.scrollTo({ top: 0, behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', }); }, []); // Weak prompt the ideas modal is focused on (red "Create content" CTA), or // null for the plain "turn your ideas into articles" entry point. const [boostSeedPrompt, setBoostSeedPrompt] = useState<{ promptText: string; currentScore: number | null; } | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [scanning, setScanning] = useState(false); // Which SCAN_MARKETING_MESSAGES entry the scan banner currently shows. const [scanMessageIndex, setScanMessageIndex] = useState(0); // A Company ID push queued a scan: the whole dashboard blocks on a // regeneration screen until the fresh results land. const [companyIdRegenerating, setCompanyIdRegenerating] = useState(false); const [outOfCredits, setOutOfCredits] = useState(false); const [toast, setToast] = useState(null); const [settingsOpen, setSettingsOpen] = useState(false); const [ideasModalOpen, setIdeasModalOpen] = useState(false); const pollRef = useRef | null>(null); const pollStartedAt = useRef(0); const baselineHistoryLen = useRef(0); const baselineReportGeneratedAt = useRef(null); const historyLandedAt = useRef(null); // Bumped by loadAll so self-fetching sections (tracked prompts) refetch on // every full refresh. Without it, the prompt list only loaded on mount: a // first scan generated the set server-side but the list stayed on its empty // state until a manual page refresh. const [promptsRefreshToken, setPromptsRefreshToken] = useState(0); const hasClientCreds = Boolean(token && clientId); useEffect(() => { if (hasClientCreds) setAllowed(true); }, [hasClientCreds]); /** Substring of the backend's one-brand-per-plan quota error. */ const BRAND_LIMIT_ERROR_SUBSTRING = 'Tracked brand limit reached'; /** * Whether a Company ID push is still rebuilding this dashboard. Best * effort: a probe that fails must never block the brand bootstrap. * * @return {Promise} ``true`` while a push is in flight. */ const isCompanyIdPushPending = async (): Promise => { try { const status = await getCompanyIdPushScanStatus( clientId as string, token as string ); return status.pending; } catch { return false; } }; /** * Read back the brand a Company ID push already provisioned, after this * page's own create lost the race for the plan's single brand slot. * * @return {Promise} The existing brand, or null. */ const adoptProvisionedBrand = async (): Promise => { try { const refreshed = await listBrands(clientId as string, token as string); return refreshed.brands[0] ?? null; } catch (adoptError) { console.warn( '[visibility] adopting the pushed brand failed:', adoptError ); return null; } }; const loadAll = useCallback(async () => { if (!hasClientCreds || !allowed) return; setLoading(true); setError(null); setPromptsRefreshToken(previousToken => previousToken + 1); try { const fetchedSettings = await fetchSettings( clientId as string, token as string ); setSettings(fetchedSettings); const brandList = await listBrands(clientId as string, token as string); let firstBrand = brandList.brands[0]; if (!firstBrand) { const primaryDomain = (storeDomain || '').trim().toLowerCase(); const looksLikeDomain = /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(primaryDomain) && !/\s/.test(primaryDomain); if (!looksLikeDomain) { setSettingsOpen(true); setLoading(false); return; } // A Company ID push provisions this same brand server-side and the // plan carries a single brand slot, so creating one here in parallel // races the worker and loses on the quota. Let the rebuilding card // own the wait; the retry loop pulls the row in when it lands. if (await isCompanyIdPushPending()) { setCompanyIdRegenerating(true); setLoading(false); return; } try { // Prefer the WordPress site locale (the storefront language // shoppers and AI assistants actually see) over the // merchant-wide ``preferred_language`` (which only tracks the // Recomaze admin UI). ``getStoreLanguage`` reads the locale // localized via ``wp_localize_script`` and normalizes it to a // supported ISO 639-1 code. const detectedStoreLanguage = getStoreLanguage(); firstBrand = await createBrand(clientId as string, token as string, { domain: primaryDomain, brand_name: storeName || undefined, language: detectedStoreLanguage || fetchedSettings.preferred_language, country: fetchedSettings.default_country || undefined, }); } catch (err: any) { console.warn( '[visibility] auto-create brand from domain failed:', err ); const backendDetail = err?.response?.data?.detail || err?.response?.data?.message || (err instanceof Error ? err.message : null); // A push that landed between the list above and this create took // the slot, so the brand the merchant is waiting for exists: take // it rather than show them a quota they never hit, on a page a // plain refresh would have rendered correctly. const adopted: BrandResponse | null = String( backendDetail || '' ).includes(BRAND_LIMIT_ERROR_SUBSTRING) ? await adoptProvisionedBrand() : null; if (!adopted) { setError( backendDetail || "Couldn't set up the brand automatically. Enter your domain in Settings." ); setSettingsOpen(true); setLoading(false); return; } firstBrand = adopted; // A push owns the scan it queued; flag the rebuild so the page // does not fire a second one at the same fresh brand. if (await isCompanyIdPushPending()) setCompanyIdRegenerating(true); } } const [ fullBrand, report, scans, leaderboard, tracked, problems, sugg, articleList, ] = await Promise.all([ getBrand(clientId as string, token as string, firstBrand.brand_id), getWeeklyReport( clientId as string, token as string, firstBrand.brand_id, selectedWeek ).catch(() => null), listScans(clientId as string, token as string, firstBrand.brand_id), getCompetitors( clientId as string, token as string, firstBrand.brand_id, selectedWeek ), listTrackedCompetitors( clientId as string, token as string, firstBrand.brand_id ), listProblems(clientId as string, token as string, firstBrand.brand_id), listSuggestions( clientId as string, token as string, firstBrand.brand_id ), listArticles(clientId as string, token as string, { brand_id: firstBrand.brand_id, }), ]); setBrand(fullBrand); setWeeklyReport(report); setScanHistory(scans); setCompetitors(leaderboard); setTrackedCompetitors(tracked.competitors); setProblemsData(problems); setSuggestions(sugg); setArticles(articleList.articles); setArticleCounts(articleList.counts); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load data.'); } finally { setLoading(false); } }, [ hasClientCreds, allowed, clientId, token, selectedWeek, storeDomain, storeName, ]); useEffect(() => { if (allowed) loadAll(); }, [loadAll, allowed]); // The Reco copilot dispatches ``copilot:data-changed`` after a turn where a // write tool ran (generate article, start scan, update settings, etc.). WordPress // has no route loaders to revalidate, so this page re-fetches its data when the // event fires - mirroring the Remix ``revalidator.revalidate()`` the copilot // used in the Shopify plugin. // // A newly started article transitions pending -> generating -> ready // asynchronously, so a single re-fetch right after the turn can run before the // article row even exists. The catch-up poll (~3s apart for ~30s) only // re-pulls the ARTICLES: a full ``loadAll`` also refetched the prompts, // leaderboard and report, so the whole page visibly churned every three // seconds while an article generated. Once the row exists the dedicated // generating-poll effect below takes over and flips it to ready. Timers are // cleared on the next event and on unmount so intervals never stack. const dataChangedPollRef = useRef | null>( null ); useEffect(() => { const stopPolling = (): void => { if (dataChangedPollRef.current) { clearInterval(dataChangedPollRef.current); dataChangedPollRef.current = null; } }; const onCopilotDataChanged = (): void => { if (!allowed) return; void loadAll(); stopPolling(); let elapsedMs = 0; dataChangedPollRef.current = setInterval(() => { elapsedMs += 3_000; void refreshArticles(); if (elapsedMs >= 30_000) stopPolling(); }, 3_000); }; window.addEventListener('copilot:data-changed', onCopilotDataChanged); return () => { window.removeEventListener('copilot:data-changed', onCopilotDataChanged); stopPolling(); }; }, [loadAll, allowed]); /** * Refresh the articles list + the backend-derived tab counts. Called * after every mutation that can flip a count (publish / unpublish / * delete / suggestion reject). The backend is the single source of * truth - the local list updates optimistically for snappy UX, the * counts come from here. * * @returns {Promise} Resolves once articles + counts state has been refreshed. */ const refreshArticles = useCallback(async () => { if (!brand) return; try { const articleList = await listArticles( clientId as string, token as string, { brand_id: brand.brand_id, // Bypass the 5-min server cache: this runs on the generation poll, so // a stale snapshot would keep a finished article stuck on "generating" // - or, worse, answer without the row at all and drop a card that is // mid-generation back to offering "Generate content". force: true, } ); setArticles(articleList.articles); setArticleCounts(articleList.counts); } catch { // Soft-fail: counts will catch up on the next loadAll. Better to // leave the stale-by-1 badge than throw a banner over the page. } }, [brand, clientId, token]); // While any article is still generating, poll the list so finished articles // surface and the per-language version chips advance on their own. The // refetch bypasses the server cache, so a mid-flight status is never read // from a stale snapshot. Capped so a stuck row can't poll forever. const generatingPollStartedAt = useRef(0); useEffect(() => { const anyGenerating = articles.some( article => article.status === 'generating' || article.status === 'pending' ); if (!anyGenerating) { generatingPollStartedAt.current = 0; return; } if (generatingPollStartedAt.current === 0) { generatingPollStartedAt.current = Date.now(); } if (Date.now() - generatingPollStartedAt.current > 10 * 60 * 1000) return; const handle = setTimeout(() => { void refreshArticles(); }, 6000); return () => clearTimeout(handle); }, [articles, refreshArticles]); const handleWeekChange = useCallback( async (weekIso: string) => { setSelectedWeek(weekIso); if (!brand) return; try { const [report, leaderboard] = await Promise.all([ getWeeklyReport( clientId as string, token as string, brand.brand_id, weekIso ).catch(() => null), getCompetitors( clientId as string, token as string, brand.brand_id, weekIso ), ]); setWeeklyReport(report); setCompetitors(leaderboard); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load week.'); } }, [brand, clientId, token] ); /** * Re-fetch the competitor leaderboard for the pinned week. Adding or * removing a tracked competitor changes which rows the board shows (a * tracked rival is forced in with a "Manually tracked" pill), so the * board has to refetch after a tracked-panel mutation. * * @returns {Promise} Resolves once the leaderboard state is refreshed. */ const refreshLeaderboard = useCallback(async () => { if (!brand) return; try { const leaderboard = await getCompetitors( clientId as string, token as string, brand.brand_id, selectedWeek ); setCompetitors(leaderboard); } catch (err) { setError( err instanceof Error ? err.message : 'Failed to refresh competitors.' ); } }, [brand, clientId, token, selectedWeek]); /** * Re-fetch the manually tracked competitors. Excluding a rival from the * leaderboard also drops it from the tracked list backend-side, so the * panel above has to refetch after a leaderboard exclusion. * * @returns {Promise} Resolves once the tracked-competitor state is refreshed. */ const refreshTrackedCompetitors = useCallback(async () => { if (!brand) return; try { const tracked = await listTrackedCompetitors( clientId as string, token as string, brand.brand_id ); setTrackedCompetitors(tracked.competitors); } catch (err) { setError( err instanceof Error ? err.message : 'Failed to refresh tracked competitors.' ); } }, [brand, clientId, token]); /** * Apply the refreshed tracked list echoed by the panel's add/remove * modals, then refresh the leaderboard so the same rival appears (or * loses its "Manually tracked" pill) without a manual page refresh. * * @param next {ManualCompetitor[]} Refreshed tracked list echoed by the backend. * @returns {void} */ const handleTrackedCompetitorsChange = useCallback( (next: ManualCompetitor[]) => { setTrackedCompetitors(next); void refreshLeaderboard(); }, [refreshLeaderboard] ); /** * Refresh both competitor views after a rival is excluded from the * leaderboard. The backend filters the domain from the board and removes * it from the tracked list, so both panels have to refetch. * * @returns {void} */ const handleCompetitorExcluded = useCallback(() => { void refreshLeaderboard(); void refreshTrackedCompetitors(); }, [refreshLeaderboard, refreshTrackedCompetitors]); const handleForceScan = async () => { if (!brand) return; setScanning(true); setOutOfCredits(false); try { await startScan(clientId as string, token as string, brand.brand_id); setToast("Scan dispatched - we'll refresh this page once it lands."); beginScanPolling(brand.brand_id); } catch (err) { if (err instanceof ScanAlreadyRunningError) { // Another tab (or a dispatch from before a refresh) owns the scan: // keep the lock on and ride the in-flight one to completion. beginScanPolling(brand.brand_id); return; } if (err instanceof InsufficientCreditsError) { setOutOfCredits(true); } else if (err instanceof ScanCooldownError) { // Not a failure: the last scan is under a day old and nothing it // measures changed, so the page says when the next one opens. setToast(err.message); } else { setError(err instanceof Error ? err.message : 'Failed to start scan.'); } setScanning(false); } }; /** * Poll history + weekly report until the in-flight scan's data lands, then * refresh everything and release the scanning/regenerating locks. Shared by * the Force scan button and the Company ID push probe. */ const beginScanPolling = (brandId: string) => { // Only one polling session may exist: without this, a second start (the // Company ID push probe racing a resumed poll, or a manual force scan // during one) orphaned the first interval - its handle was overwritten, // so its terminal branches cleared the NEW interval and the orphan kept // firing loadAll + "All data refreshed" every 5s forever. if (pollRef.current) clearInterval(pollRef.current); baselineHistoryLen.current = scanHistory?.history?.length ?? 0; baselineReportGeneratedAt.current = weeklyReport?.generated_at ?? null; historyLandedAt.current = null; pollStartedAt.current = Date.now(); const intervalHandle = setInterval(async () => { // Self-ownership check: if a newer session took the ref between ticks, // this interval is stale - kill itself instead of double-refreshing. if (pollRef.current !== intervalHandle) { clearInterval(intervalHandle); return; } try { const [scans, report] = await Promise.all([ listScans(clientId as string, token as string, brandId), getWeeklyReport( clientId as string, token as string, brandId, selectedWeek ).catch(() => null), ]); setScanHistory(scans); const historyGrew = scans.history.length > baselineHistoryLen.current; const reportRefreshed = report !== null && report.generated_at !== null && report.generated_at !== baselineReportGeneratedAt.current; if (historyGrew && historyLandedAt.current === null) { historyLandedAt.current = Date.now(); await loadAll(); setToast('Scan complete - waiting for the weekly report.'); } if (reportRefreshed) { clearInterval(intervalHandle); pollRef.current = null; await loadAll(); setToast('All data refreshed.'); setScanning(false); setCompanyIdRegenerating(false); return; } // Server-truth early release: the worker says nothing is executing, // so whatever the run was going to produce, it already has. This // deliberately does NOT require the absence of a scan row: when the // row lands but the weekly report never refreshes - a failed or // unchanged aggregation - the merchant would otherwise sit behind // the blur for the full grace window over a worker that finished // minutes ago. The floor covers the dispatch-to-start gap where the // running marker legitimately does not exist yet. if ( !reportRefreshed && Date.now() - pollStartedAt.current >= SCAN_STATUS_RELEASE_MIN_MS ) { try { const runStatus = await getScanRunStatus( clientId as string, token as string, brandId ); if (!runStatus.running) { clearInterval(intervalHandle); pollRef.current = null; await loadAll(); setScanning(false); setCompanyIdRegenerating(false); setToast('Scan ended - refreshed with the latest data.'); return; } } catch { // Best-effort probe - keep polling on failure. } } const totalTimedOut = Date.now() - pollStartedAt.current >= SCAN_POLL_MAX_MS; const graceExpired = historyLandedAt.current !== null && Date.now() - historyLandedAt.current >= POST_HISTORY_GRACE_MS; if (totalTimedOut || graceExpired) { clearInterval(intervalHandle); pollRef.current = null; await loadAll(); setScanning(false); setCompanyIdRegenerating(false); setToast( graceExpired ? 'Scan complete - some KPIs may need a moment to finalize.' : 'Scan is taking longer than usual - reloaded with the latest data.' ); } } catch { // Transient error - keep polling. } }, SCAN_POLL_INTERVAL_MS); pollRef.current = intervalHandle; }; // Once creds and the brand are known, ask whether a Company ID push // queued a scan that is still rebuilding this dashboard's data; failing // that, whether ANY scan is mid-flight for this brand (e.g. the page was // refreshed while one ran). Either way the blur lock + polling resume // instead of rendering an idle dashboard while the worker is still // rebuilding the numbers. const pushProbeFiredRef = useRef(false); useEffect(() => { if (!hasClientCreds || !brand || pushProbeFiredRef.current) return; pushProbeFiredRef.current = true; let cancelled = false; (async () => { try { const status = await getCompanyIdPushScanStatus( clientId as string, token as string ); if (cancelled) return; if (status.pending && !scanning) { setCompanyIdRegenerating(true); setScanning(true); beginScanPolling(status.brand_id ?? brand.brand_id); return; } } catch { // Best-effort probe; fall through to the scan-status check. } try { const runStatus = await getScanRunStatus( clientId as string, token as string, brand.brand_id ); if (cancelled || !runStatus.running || scanning) return; setScanning(true); beginScanPolling(brand.brand_id); } catch { // Best-effort probe; the dashboard just renders normally. } })(); return () => { cancelled = true; }; // Fires once, when brand + creds are first available together. }, [brand, hasClientCreds, scanning, clientId, token]); // A Company ID push provisions a missing brand in the background: arriving // right after dispatch can beat the provisioning, so while the pending // probe says a rebuild is in flight and no brand row exists yet, re-pull // everything on a short cadence - the dashboard then appears the moment // provisioning lands instead of waiting for a manual refresh. useEffect(() => { if (!companyIdRegenerating || brand) return; const provisionRetry = setInterval(() => { void loadAll(); }, BRAND_PROVISION_RETRY_MS); return () => clearInterval(provisionRetry); }, [companyIdRegenerating, brand, loadAll]); // Provisioning ends the moment the brand row lands, and from there the // push's own forced scan is what the merchant is still waiting on. The // rebuilding card hands over to the scan blur here; without it the card // resolves into an idle dashboard while the worker is still mid-write. const rebuildHandoverRef = useRef(false); useEffect(() => { if (!companyIdRegenerating || !brand) return; if (rebuildHandoverRef.current || pollRef.current) return; rebuildHandoverRef.current = true; setScanning(true); beginScanPolling(brand.brand_id); }, [companyIdRegenerating, brand]); useEffect( () => () => { if (pollRef.current) clearInterval(pollRef.current); }, [] ); // While a scan is in flight, rotate the banner through the AEO / GEO // marketing messages so the wait stays informative. useEffect(() => { if (!scanning) return; setScanMessageIndex(0); const rotator = setInterval(() => { setScanMessageIndex( previousIndex => (previousIndex + 1) % SCAN_MARKETING_MESSAGES.length ); }, SCAN_MESSAGE_ROTATE_MS); return () => clearInterval(rotator); }, [scanning]); const brandNameLabel = useMemo( () => brand?.brand_name || brand?.domain || 'AI Visibility', [brand] ); const floorWeekIso = useMemo( () => isoWeekFromTimestamp(brand?.created_at), [brand?.created_at] ); // Articles that finished generating and are waiting to be read - the count // badged on the Content tab. Derived from the list the page already holds // rather than a second round-trip. const contentReadyCount = useMemo( () => articles.filter(article => article.status === 'ready').length, [articles] ); const requiresSetup = Boolean(brand) && (!brand?.language || !brand?.country); const autoOpenedRef = useRef(false); useEffect(() => { if (requiresSetup && !autoOpenedRef.current && !loading) { autoOpenedRef.current = true; setSettingsOpen(true); } }, [requiresSetup, loading]); // Deep-link from the Dashboard ("Finish setup" CTA) lands here with // ``?settings=open`` so the drawer pops open without waiting for the // requiresSetup heuristic. HashRouter routes look like // ``#/ai-visibility?settings=open`` so we read the query off the hash. useEffect(() => { if (typeof window === 'undefined') return; const hash: string = window.location.hash || ''; const queryIndex: number = hash.indexOf('?'); if (queryIndex === -1) return; const params: URLSearchParams = new URLSearchParams( hash.slice(queryIndex + 1) ); if (params.get('settings') === 'open') { setSettingsOpen(true); params.delete('settings'); const nextQuery: string = params.toString(); const nextHash: string = hash.slice(0, queryIndex) + (nextQuery ? `?${nextQuery}` : ''); window.history.replaceState( null, '', `${window.location.pathname}${nextHash}` ); } }, []); // ``?tab=`` deep-links a specific panel (e.g. from the copilot or a // dashboard link). Only known tab values are honored; anything else leaves // the default "overview" in place. We don't write the tab back to the URL // on click, so this stays a one-way deep link. HashRouter routes look like // ``#/ai-visibility?tab=citations`` so we read the query off the hash. useEffect(() => { if (typeof window === 'undefined') return; const hash: string = window.location.hash || ''; const queryIndex: number = hash.indexOf('?'); if (queryIndex === -1) return; const requestedTab = new URLSearchParams(hash.slice(queryIndex + 1)).get( 'tab' ); if ( requestedTab === 'overview' || requestedTab === 'prompts' || requestedTab === 'citations' || requestedTab === 'content' || requestedTab === 'chat' ) { setActiveTabId(requestedTab); } }, []); if (allowed === null || !hasClientCreds) { return (
); } /** * Merge a freshly-ready article into the list so the "Ready" badge in * Recommended flips without a full reload. * * @param article {ArticleDetailResponse} The article that just transitioned to ``ready``. * @returns {void} */ const handleArticleReady = (article: ArticleDetailResponse) => { setArticles(previousArticles => { const others = previousArticles.filter( existingArticle => existingArticle.article_id !== article.summary.article_id ); return [article.summary, ...others]; }); void refreshArticles(); setToast('Content is ready.'); }; /** * Drop a rejected suggestion from local state so the row disappears * without waiting for a re-fetch of the suggestions list. * * @param rejectedSuggestionId {string} Identifier of the suggestion just rejected on the backend. * @returns {void} */ const handleSuggestionRejected = (rejectedSuggestionId: string) => { setSuggestions(previousSuggestions => previousSuggestions ? { ...previousSuggestions, suggestions: previousSuggestions.suggestions.filter( existingSuggestion => existingSuggestion.suggestion_id !== rejectedSuggestionId ), } : previousSuggestions ); void refreshArticles(); setToast('Content idea removed.'); }; /** * Merge ideas generated from a brief into the Recommended list so the new * idea cards appear without a refetch. Already-present ideas (matched by * ``suggestion_id``) are replaced, and the fresh ones are prepended so they * surface at the top of the list. * * @param newIdeas {SuggestionEntry[]} Ideas the brief modal just generated. * @returns {void} */ const handleIdeasGenerated = (newIdeas: SuggestionEntry[]) => { if (newIdeas.length === 0) return; const newIds = new Set(newIdeas.map(idea => idea.suggestion_id)); setSuggestions(previousSuggestions => { const existing = (previousSuggestions?.suggestions ?? []).filter( existingSuggestion => !newIds.has(existingSuggestion.suggestion_id) ); return { suggestions: [...newIdeas, ...existing] }; }); }; /** * Drop a hard-deleted article from local state so the row's "Open * article" → "Generate article" flip happens without a re-fetch. * * @param deletedArticleId {string} Identifier of the article just hard-deleted on the backend. * @returns {void} */ const handleArticleDeleted = (deletedArticleId: string) => { // The backend cascades the rejection to the source suggestion, so // mirror that locally - drop the idea card from the Recommended tab // in the same gesture (the badge count is refreshed from the server // below, so we only need the visible list to stay honest). const removed = articles.find( existingArticle => existingArticle.article_id === deletedArticleId ); const suggestionIdToDrop = removed?.triggered_by_suggestion_id ?? null; setArticles(previousArticles => previousArticles.filter( existingArticle => existingArticle.article_id !== deletedArticleId ) ); if (suggestionIdToDrop) { setSuggestions(previousSuggestions => previousSuggestions ? { ...previousSuggestions, suggestions: previousSuggestions.suggestions.filter( existingSuggestion => existingSuggestion.suggestion_id !== suggestionIdToDrop ), } : previousSuggestions ); } void refreshArticles(); setToast('Content deleted.'); }; /** * Patch a single article in local state when the merchant flips it * between ``ready`` and ``published`` from inside the modal. Keeps the * Recommended/Published tabs in sync without a full refetch. * * @param article {ArticleDetailResponse} The article whose status just toggled. * @returns {void} */ const handleArticlePublishedChanged = (article: ArticleDetailResponse) => { setArticles(previousArticles => { const others = previousArticles.filter( existingArticle => existingArticle.article_id !== article.summary.article_id ); return [article.summary, ...others]; }); void refreshArticles(); setToast( article.summary.status === 'published' ? 'Content marked as published.' : 'Content moved back to Recommended.' ); }; // Narrow the rendered list to the selected page type; both tabs read this so // a "Service" filter scopes Recommended and Published alike. Rows written // before the column existed read as "blog". const typeFilteredArticles = articleTypeFilter === 'all' ? articles : articles.filter( article => (article.content_type ?? 'blog') === articleTypeFilter ); // A Company ID push is provisioning a brand that doesn't exist yet: render // the rebuilding card while the 10s retry loop pulls the brand list. Once // the brand row lands, the normal dashboard renders behind the scan // blur + banner (the probe already flipped the scanning lock on). if (companyIdRegenerating && !brand) { return (

Rebuilding AI Visibility from your Company ID…

We're setting up your brand and running a fresh scan with what you just pushed. This takes a few minutes - the dashboard appears automatically.

); } return ( <> {/* The page owns no padding of its own: the pinned header has to span the full content area and reach the very top edge of the scrolling
. Everything below it re-applies the reading column. */}
{/* Any in-flight scan blurs the dashboard behind a veil with a sweeping light band, while the crisp info banner above it carries the status copy. The scan polling loop lifts the lock once the fresh results land. */} {scanning && (
)} {scanning && (

{companyIdRegenerating ? 'Rebuilding AI Visibility from your Company ID' : 'Visibility scan in progress'}

{companyIdRegenerating ? "We're regenerating your prompt set and running a fresh scan with what you just pushed. This usually takes between 4 and 8 minutes; the dashboard unblurs automatically when the new results land." : "We're probing AI engines for your brand. A full scan usually takes between 4 and 8 minutes; the dashboard unblurs automatically when the fresh results land."}

{scanMessages[scanMessageIndex]}

)}
setSettingsOpen(true)} requiresSetup={requiresSetup} tabs={ } info={ <> {brand && ( )} {(brand?.knowledge_base ?? '').trim().length > 0 && !scanning && } } />
setOutOfCredits(false)} /> {error && } {activeTabId === 'overview' && (
{/* This week's numbers sit on top of the history that produced them - the strip is the chart's latest tick. */} {scanHistory && weeklyReport && ( )}
Brands the engines recommend for your prompts } /> {competitors && competitors.competitors.length > 0 && ( )} {brand && ( )} {competitors && brand ? ( ) : ( !loading && ( ) )}
)} {activeTabId === 'prompts' && (
{brand && ( ) : null } weekIso={weeklyReport?.week_iso ?? selectedWeek} refreshToken={promptsRefreshToken} onBoostPrompt={prompt => { setBoostSeedPrompt(prompt); setIdeasModalOpen(true); }} /> )}
)} {activeTabId === 'citations' && (
{/* Funnel coverage (Beta). */} {brand && canSeeBetaVisibilityFeatures(clientId as string) && ( )} {/* Cited sources (Beta). */} {brand && canSeeBetaVisibilityFeatures(clientId as string) && ( )}
)} {activeTabId === 'content' && (
{/* Articles - Recommended (suggestions) vs Published. */}
Pages worth writing, ranked by what you lost } action={ <> {/* The disclaimer lives where the content does. */} {brand && ( )} } /> {/* Page-type filter shared by both article tabs. */}
{( ['all', ...PAGE_CONTENT_TYPES] as Array< PageContentType | 'all' > ).map(value => ( ))}
{brand && (
{ARTICLES_TABS.map(tab => { const isSelected = articlesTab === tab.id; const count = articleCounts[tab.id]; return ( ); })}
{articlesTab === 'recommended' && ( )} {articlesTab === 'published' && ( )}
)}
{/* Problems detected this week. */}

Problems detected this week

)} {activeTabId === 'chat' && (
{/* Trending in your chat. */} {brand && ( )}
)}
{brand && ( { setIdeasModalOpen(next); if (!next) setBoostSeedPrompt(null); }} clientId={clientId as string} token={token as string} brandId={brand.brand_id} language={brand.language || 'en'} onIdeasGenerated={handleIdeasGenerated} onArticleStarted={refreshArticles} seedPrompt={boostSeedPrompt} /> )} setSettingsOpen(false)} brand={brand} settings={settings} clientId={clientId as string} token={token as string} fallbackDomain={storeDomain || undefined} fallbackLanguage={getStoreLanguage()} onBrandSaved={setBrand} onSettingsSaved={setSettings} />
{toast && ( setToast(null)} duration={3500} /> )} ); }; export default AiVisibilityPage;