import { useEffect, useLayoutEffect, useMemo, useRef, useState, useCallback, useId } from 'react'
import { ChevronDown, RefreshCw, Trash2 } from 'lucide-react'
import { useNavigate, useParams, useSearch } from '@tanstack/react-router'
import { Link } from '@tanstack/react-router'

import { carryVisibilitySearch, measurementViewSearch, parseMeasurementViewSearch, parseVisibilitySelection, patchVisibilitySelection, shouldResetMeasurementView } from '../lib/measurement-view-url.js'
import {
  canUseResearchWorkspace,
  effectiveQueryWorkspace,
  isMeasurementScoped,
  PROJECT_SCOPE_COPY,
  projectScopeSlot,
  selectedScopeOption,
  unavailableTrackingScope,
  type QueryWorkspace,
} from '../lib/project-scope.js'
import { useQueryClient } from '@tanstack/react-query'
import { COMPETITOR_BULK_ADD_REFUSAL_REASON, COMPETITOR_BULK_ADD_WINDOW_HOURS, compileQueryClassifier, effectiveBrandNames, normalizeQueryText, parseVisibilityReportScopeErrorDetails, RunKinds, RunStatuses, UserRoles } from '@canonry/canonry-contracts'
import type { CloudRunTrafficSetup, MeasurementOverviewSort, RunPreviewDto } from '@canonry/canonry-contracts'

import { Button } from '../components/ui/button.js'
import { Card } from '../components/ui/card.js'
import { CitationBadge } from '../components/shared/CitationBadge.js'
import { useDrawer } from '../hooks/use-drawer.js'
import * as Dialog from '@radix-ui/react-dialog'
import { WriteButton } from '../components/shared/AccessControls.js'
import { InfoTooltip } from '../components/shared/InfoTooltip.js'
import { WorkspaceTabs } from '../components/shared/WorkspaceTabs.js'
import { MentionShare } from '../components/project/MentionShare.js'
import {
  CompetitorLandscape,
  type CompetitorLandscapeRow,
  type CompetitorLandscapeWindow,
} from '../components/project/CompetitorLandscape.js'
import { ProviderBadge } from '../components/shared/ProviderBadge.js'
import { ToneBadge } from '../components/shared/ToneBadge.js'
import { SentimentScopeProvider } from '../components/project/SentimentSection.js'
import { sentimentSelectionFromVisibility, sentimentSelectionForSimpleEvidence } from '../queries/sentiment.js'
import { EvidenceTable, QueryEvidenceSummary } from '../components/project/EvidenceTable.js'
import { BingSection } from '../components/project/BingSection.js'
import { ActivitySection } from '../components/project/ActivitySection.js'
import { ServerTrafficSection } from '../components/project/ServerTrafficSection.js'
import { GscSection } from '../components/project/GscSection.js'
import { GbpSection } from '../components/project/GbpSection.js'
import { BacklinksSection } from '../components/project/BacklinksSection.js'
import { SeoDataSection } from '../components/project/SeoDataSection.js'
import { JourneysSection } from '../components/project/JourneysSection.js'
import { CitationVisibilitySection } from '../components/project/CitationVisibilitySection.js'
import { PastSweeps } from '../components/project/PastSweeps.js'
import { useVisibilityReportFirstPage, VisibilityOverview, VisibilityTrendSection } from '../components/project/VisibilityTrendSection.js'
import { VisibilityScopePicker } from '../components/project/VisibilityScopePicker.js'
import { QueriesSection } from '../components/project/DiscoverySection.js'
import { EmbedQueriesSection } from '../components/project/EmbedQueriesSection.js'
import { SiteHealthSection } from '../components/project/SiteHealthSection.js'
import { ProjectHistorySection } from '../components/project/ProjectHistorySection.js'
import { ConversionIntegrityWorkspace } from '../components/project/ConversionIntegrityWorkspace.js'
import { GoogleAdsPerformanceSection } from '../components/project/GoogleAdsPerformanceSection.js'
import { AdvancedMeasurementSection } from '../components/project/advanced-measurement/AdvancedMeasurementSection.js'
import { AdvancedMeasurementLanding } from '../components/project/advanced-measurement/AdvancedMeasurementLanding.js'
import {
  advancedMeasurementSetupActionLabel,
  advancedProjectTagDetail,
  resolveAdvancedMeasurementMode,
} from '../components/project/advanced-measurement/model.js'
import { adaptVersionOneMeasurementReport } from '../components/project/advanced-measurement/v1-report-adapter.js'
import {
  adaptV2MeasurementOverview,
  areV2OverviewPagesCompatible,
} from '../components/project/advanced-measurement/v2-overview-adapter.js'
import { formatTimestamp, siteCitationLabel, splitPercentSign } from '../lib/format-helpers.js'
import { METRIC_TONE_TEXT_CLASS } from '../lib/tone-helpers.js'
import { CITATION_NOT_MEASURED } from '../lib/citation-not-measured-copy.js'
import type { QueryClassLookup } from '../lib/answer-movement.js'
import { addToast } from '../lib/toast-store.js'
import { asyncHandler } from '../lib/async-handler.js'
import { ProjectSettingsSection } from '../components/project/ProjectSettingsSection.js'
import { ProjectEngineSettingsSection, SiteHealthScanSettingsSection } from '../components/project/ProjectEngineSettingsSection.js'
import { ManagedSweepStatus, managedSweepDate } from '../components/project/ManagedSweepStatus.js'
import { RunAdmissionNoticeView, RunPreviewSummary, useRunAdmission, useRunPreview } from '../components/project/RunAdmissionNotice.js'
import { providerDisplayName } from '../lib/visibility-trend-helpers.js'
import { ScheduleSection } from '../components/project/ScheduleSection.js'
import { NotificationsSection } from '../components/project/NotificationsSection.js'
import {
  fetchTimeline,
  deleteProject as apiDeleteProject,
  appendQueries as apiAppendQueries,
  removeQueries as apiRemoveQueries,
  appendCompetitors as apiAppendCompetitors,
  removeCompetitorById as apiRemoveCompetitorById,
  updateProject as apiUpdateProject,
  inspectBingSitemap,
  triggerBingSync,
  triggerGscSync,
  fetchRunDetail,
  apiErrorDetails,
  heyClient,
  getEmbedConfig,
  getViewerResearchConfig,
  isEmbed,
  isDashboardManagedSweeps,
  isPublicDemo,
  type ApiBingConnection,
  type ApiGoogleConnection,
  type ApiProject,
} from '../api.js'
import { effectiveEmbedProjectTabs, embedQueryLimit, isEmbedProjectTabAllowed, resolveProjectPageTab } from '../embed.js'
import {
  getApiV1CdpStatusOptions,
  getApiV1ProjectsByNameBingStatusOptions,
  getApiV1ProjectsByNameAnalyticsCompetitorsOptions,
  postApiV1ProjectsByNameMeasurementPlanDraftActionsPinCompetitorMutation,
  getApiV1ProjectsByNameGoogleConnectionsOptions,
  getApiV1ProjectsByNameMeasurementOverviewInfiniteOptions,
  getApiV1ProjectsByNameMeasurementPlanOptions,
  getApiV1ProjectsByNameSchedulesOptions,
  getApiV1ProjectsByNameAgentReadinessRunsOptions,
  getApiV1ProjectsByNameMeasurementReportOptions,
  getApiV1ProjectsByNameMeasurementSetupOptions,
  getApiV1ProjectsByNameQueriesOptions,
  getApiV1ProjectsByNameQueryTrackingOptions,
  getApiV1ProjectsByNameQueryKey,
} from '@canonry/canonry-api-client/react-query'
import { useAppendQueries, useTriggerRun } from '../queries/mutations.js'
import { GSC_STALE_MS } from '../queries/query-client.js'
import { invalidateProjectQueryDomain } from '../queries/query-invalidation.js'
import { keepPreviousData, useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'
import { getApiV1ProjectsOptions } from '@canonry/canonry-api-client/react-query'
import { useProjectDashboard } from '../queries/use-project-dashboard.js'
import { useCompetitorLandscapeRefresh } from '../queries/competitor-landscape-refresh.js'
import { useInitialDashboard } from '../contexts/dashboard-context.js'
import { useAccount } from '../contexts/account-context.js'
import {
  CDP_PROVIDER_NAME,
  normalizeProviderName,
  resolveAiVisibilityProviderReadiness,
} from '../lib/ai-visibility-provider-readiness.js'
import type { ProjectCommandCenterVm, RunHistoryPoint } from '../view-models.js'

export type ProjectPageTab = 'overview' | 'portfolio' | 'search-console' | 'seo-data' | 'journeys' | 'conversions' | 'local' | 'queries' | 'client-queries' | 'discovery' | 'activity' | 'traffic' | 'backlinks' | 'agent-readiness' | 'history' | 'settings'

export function ProjectSweepConfirmation({ open, projectLabel, onOpenChange, onConfirm, onClosed, disabled, leftOut = [], preview, previewPending = false, previewFailed = false, onRetryPreview = () => {} }: {
  open: boolean
  projectLabel: string
  onOpenChange: (open: boolean) => void
  onConfirm: () => void
  onClosed?: () => void
  disabled: boolean
  /** Providers this sweep will not call because each keeps failing on its account. */
  leftOut?: readonly string[]
  preview?: RunPreviewDto
  previewPending?: boolean
  previewFailed?: boolean
  onRetryPreview?: () => void
}) {
  if (isEmbed() || isDashboardManagedSweeps()) return null
  return <Dialog.Root open={open} onOpenChange={onOpenChange}><Dialog.Portal>
    <Dialog.Overlay className="fixed inset-0 z-50 bg-overlay-scrim/70 backdrop-blur-sm" />
    <Dialog.Content className="material-modal fixed left-1/2 top-1/2 z-50 max-h-[85dvh] w-[calc(100%-2rem)] max-w-xl -translate-x-1/2 -translate-y-1/2 overflow-y-auto p-5" onCloseAutoFocus={event => { if (onClosed) { event.preventDefault(); onClosed() } }}>
      <div className="space-y-2">
        <Dialog.Title className="text-heading-20 text-heading">Review AI Visibility check</Dialog.Title>
        <Dialog.Description className="text-copy-14 text-secondary">
          Checks {projectLabel} using the scope below. View filters do not limit the check. Provider charges apply.
          {leftOut.length > 0
            ? ` ${leftOut.map(name => providerDisplayName(name)).join(' and ')} ${leftOut.length === 1 ? 'is' : 'are'} left out: ${leftOut.length === 1 ? 'it keeps failing on its account' : 'they keep failing on their accounts'}.`
            : null}
        </Dialog.Description>
      </div>
      <div className="mt-5"><RunPreviewSummary preview={preview} pending={previewPending} failed={previewFailed} onRetry={onRetryPreview} /></div>
      <p className="mt-4 text-copy-13 text-secondary">Runs once. Your schedule stays unchanged.</p>
      <div className="mt-6 flex flex-wrap gap-3">
        <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
        <WriteButton disabled={disabled || previewPending || previewFailed || preview?.canStart !== true} onClick={onConfirm}>Run project-wide check</WriteButton>
      </div>
    </Dialog.Content>
  </Dialog.Portal></Dialog.Root>
}

type SearchConsoleWorkspace = 'google' | 'bing'

/**
 * Patch the cached `useProjectDashboard` detail entries for a single project
 * with a freshly-saved project object.
 *
 * The detail key is `['project-dashboard-full', projectId, latestRunIdsKey]`
 * (see `use-project-dashboard.ts`), so a project has one entry per run-ids
 * revision and the id MUST be part of the match. A head-only predicate wrote
 * the saved project into every other project's cached entry; because
 * `commandCenter` is built from that entry, the settings form on a
 * previously-visited project then rendered — and saved to — the wrong project.
 */
/**
 * How often the "Refresh search data" flow polls a triggered sweep, and how long it
 * waits before reporting the run as still in flight.
 *
 * The old 120s deadline was shorter than a normal sweep: a paced Bing run over
 * ~45 URLs is around 90s healthy and a throttled one ran 335s, so the poll gave
 * up on runs that were about to succeed and reported "still running" instead of
 * the real outcome. The run itself is server-side and unaffected by this — only
 * whether the user is told what happened.
 */
const REFRESH_POLL_INTERVAL_MS = 2_000
const REFRESH_POLL_TIMEOUT_MS = 300_000

function competitorDraftIdempotencyKey(): string {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
  return `competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`
}

export function patchProjectDashboardCache(
  queryClient: ReturnType<typeof useQueryClient>,
  updated: ApiProject,
): void {
  queryClient.setQueriesData({
    predicate: query => query.queryKey[0] === 'project-dashboard-full' && query.queryKey[1] === updated.id,
  }, (current: unknown) => {
    if (!current || typeof current !== 'object' || !('project' in current)) return current
    return { ...current, project: updated }
  })
}

function SearchConsoleSection({
  projectName,
}: {
  projectName: string
}) {
  const tabsId = useId()
  const queryClient = useQueryClient()
  const [workspace, setWorkspace] = useState<SearchConsoleWorkspace>('google')
  const [loading, setLoading] = useState(true)
  const [refreshState, setRefreshState] = useState<'idle' | 'syncing' | 'reloading'>('idle')
  const [error, setError] = useState<string | null>(null)
  const abortRef = useRef<AbortController | null>(null)
  const [googleConnection, setGoogleConnection] = useState<ApiGoogleConnection | null>(null)
  const [bingConnection, setBingConnection] = useState<ApiBingConnection | null>(null)
  const [workspaceRefreshNonce, setWorkspaceRefreshNonce] = useState(0)

  async function loadConnectionState(silent = false) {
    if (!silent) setLoading(true)
    setError(null)

    try {
      const [connections, bingStatus] = await Promise.all([
        queryClient.fetchQuery({
          ...getApiV1ProjectsByNameGoogleConnectionsOptions({ client: heyClient, path: { name: projectName } }),
          staleTime: GSC_STALE_MS,
        }).catch(() => [] as ApiGoogleConnection[]),
        queryClient.fetchQuery({
          ...getApiV1ProjectsByNameBingStatusOptions({ client: heyClient, path: { name: projectName } }),
          staleTime: GSC_STALE_MS,
        }).catch(() => null),
      ])

      const gscConnection = connections.find((connection) => connection.connectionType === 'gsc') ?? null
      setGoogleConnection(gscConnection)
      setBingConnection(bingStatus)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load search engine connections')
    } finally {
      setLoading(false)
    }
  }

  /**
   * Trigger live queries against both Google (GSC sync job) and Bing (per-URL re-inspection),
   * run them in parallel, wait for both to settle, then reload coverage data.
   */
  async function handleRefresh() {
    if (refreshState !== 'idle') return
    abortRef.current?.abort()
    const controller = new AbortController()
    abortRef.current = controller
    const signal = controller.signal

    setRefreshState('syncing')
    setError(null)
    addToast({
      title: 'Refreshing search coverage',
      detail: 'Queueing Google and Bing checks, then reloading the workspaces.',
      tone: 'neutral',
      dedupeKey: `search-console-refresh:${projectName}`,
      dedupeMode: 'replace',
    })

    const failures: string[] = []
    // Things that are neither success nor failure: work that is still running
    // and will land on its own. Reporting these keeps a slow-but-healthy sync
    // from reading as either "done" or "broken".
    const notices: string[] = []

    try {
      // --- Google: trigger a background GSC sync job and poll to completion ---
      async function syncGoogle() {
        if (!googleConnection) return
        const run = await triggerGscSync(projectName)
        if (!run?.id) return

        const deadline = Date.now() + REFRESH_POLL_TIMEOUT_MS

        while (Date.now() < deadline) {
          if (signal.aborted) return
          await new Promise<void>((resolve) => setTimeout(resolve, REFRESH_POLL_INTERVAL_MS))
          if (signal.aborted) return
          const detail = await fetchRunDetail(run.id).catch(() => null)
          if (!detail) break
          if (['completed', 'failed', 'cancelled'].includes(detail.status)) {
            if (detail.status !== 'completed') failures.push(`Google sync ${detail.status}`)
            return
          }
        }

        // Deadline reached with the run still going. This used to fall out of
        // the loop recording nothing, so the refresh reported success while the
        // panels below reloaded pre-sync numbers — indistinguishable from "the
        // button did nothing". Say what is actually true instead: the sync is
        // still running and its data will appear on its own.
        notices.push('Google sync is still running — search data will appear shortly')
      }

      // --- Bing: trigger the server-side sweep and poll, like syncGoogle ---
      //
      // This used to loop here, issuing one HTTP call per URL from the browser.
      // Every failure mode traced to that: the sweep died when you navigated
      // away (it is client JS guarded by `signal.aborted`), a cached bundle
      // silently kept the old batch size, and the burst size was tuned in the
      // UI against a limit enforced on the server. Bing throttles per HOST,
      // shared by every project on the instance, so a browser is the wrong
      // place to decide the rate.
      //
      // `bing-inspect-sitemap` already walks the sitemap server-side at ~1
      // req/sec. Triggering it means the run survives closing the tab, the
      // pacing lives in one place, and the CLI/MCP get the same capability —
      // the UI/CLI parity rule this loop was violating.
      async function syncBing() {
        if (!bingConnection?.connected) return
        const run = await inspectBingSitemap(projectName).catch(() => null)
        if (!run?.id) {
          failures.push('Bing check could not be started')
          return
        }

        const deadline = Date.now() + REFRESH_POLL_TIMEOUT_MS

        while (Date.now() < deadline) {
          if (signal.aborted) return
          await new Promise<void>((resolve) => setTimeout(resolve, REFRESH_POLL_INTERVAL_MS))
          if (signal.aborted) return
          const detail = await fetchRunDetail(run.id).catch(() => null)
          if (!detail) break
          if (['completed', 'failed', 'cancelled', 'partial'].includes(detail.status)) {
            if (detail.status === 'failed') failures.push('Bing check failed')
            else if (detail.status === 'partial') notices.push('Bing check finished with some pages unverified')
            return
          }
        }

        // Still running at the deadline. The run continues in the engine — say
        // so rather than reporting a failure the user cannot act on.
        notices.push('Bing check is still running. Coverage will update shortly.')
      }

      // --- Bing data: queue the stored-data sync (traffic, queries, crawl, sitemaps, settings) ---
      //
      // Separate from the URL check above: that one inspects pages, this one
      // stores Bing's own reports. Both run server-side and paced per key.
      async function syncBingData() {
        if (!bingConnection?.connected || !bingConnection.siteUrl) return
        const run = await triggerBingSync(projectName).catch(() => null)
        if (!run?.id) {
          failures.push('Bing data sync could not be started')
          return
        }
        const deadline = Date.now() + REFRESH_POLL_TIMEOUT_MS
        while (Date.now() < deadline) {
          if (signal.aborted) return
          await new Promise<void>((resolve) => setTimeout(resolve, REFRESH_POLL_INTERVAL_MS))
          if (signal.aborted) return
          const detail = await fetchRunDetail(run.id).catch(() => null)
          if (!detail) break
          if (['completed', 'failed', 'cancelled', 'partial'].includes(detail.status)) {
            if (detail.status === 'failed') failures.push('Bing data sync failed')
            else if (detail.status === 'partial') notices.push('Bing data sync finished with some sections missing')
            return
          }
        }
        notices.push('Bing data sync is still running. Search data will update shortly.')
      }

      const results = await Promise.allSettled([syncGoogle(), syncBing(), syncBingData()])
      for (const r of results) {
        if (r.status === 'rejected') {
          failures.push(r.reason instanceof Error ? r.reason.message : 'Sync failed')
        }
      }

      // Invalidate BEFORE the abort check, deliberately.
      //
      // The sweeps ran on the server and the stored coverage changed whether or
      // not this component is still mounted. Discarding the invalidation on
      // unmount is what made a completed refresh look like it never happened:
      // the user navigated away, the cached payload stayed "fresh" for its 60s
      // staleTime, and coming back re-served the PRE-refresh numbers. Cache
      // state is app-wide, so it must not be conditional on this view's life.
      await Promise.all([
        invalidateProjectQueryDomain(queryClient, 'gsc'),
        invalidateProjectQueryDomain(queryClient, 'bing'),
        // Both syncs rewrite the stored sitemap lists the cards compare.
        invalidateProjectQueryDomain(queryClient, 'sitemaps'),
      ])

      if (signal.aborted) return

      // Everything below touches THIS component's state, so it stays guarded.
      setRefreshState('reloading')
      await loadConnectionState(true)
      setWorkspaceRefreshNonce((current) => current + 1)

      if (failures.length > 0) {
        const message = `Partial refresh: ${[...failures, ...notices].join('; ')}`
        setError(message)
        addToast({
          title: 'Search coverage partially refreshed',
          detail: message,
          tone: 'caution',
          dedupeKey: `search-console-refresh:${projectName}`,
          dedupeMode: 'replace',
        })
      } else if (notices.length > 0) {
        // Nothing failed, but the refresh did NOT finish — so it must not claim
        // it did. This branch titled itself "Search coverage refreshed" while
        // the detail said the sweep was still running or had left pages
        // unverified, and it was the only signal a 0-of-45 sweep produced.
        // A user reading the title alone was told the opposite of the truth.
        addToast({
          title: 'Search coverage refresh incomplete',
          detail: notices.join('; '),
          tone: 'caution',
          dedupeKey: `search-console-refresh:${projectName}`,
          dedupeMode: 'replace',
        })
      } else {
        addToast({
          title: 'Search coverage refreshed',
          detail: 'Google and Bing workspaces are reloaded with the latest stored coverage.',
          tone: 'positive',
          dedupeKey: `search-console-refresh:${projectName}`,
          dedupeMode: 'replace',
        })
      }
    } catch (err) {
      if (!signal.aborted) {
        const message = err instanceof Error ? err.message : 'Refresh failed'
        setError(message)
        addToast({
          title: 'Search coverage refresh failed',
          detail: message,
          tone: 'negative',
          dedupeKey: `search-console-refresh:${projectName}`,
          dedupeMode: 'replace',
        })
      }
    } finally {
      if (!signal.aborted) {
        setRefreshState('idle')
      }
    }
  }

  useEffect(() => {
    void loadConnectionState()
    return () => {
      abortRef.current?.abort()
    }
  }, [projectName])

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <WorkspaceTabs
          id={tabsId}
          label="Search engine workspaces"
          value={workspace}
          onChange={setWorkspace}
          className="flex flex-wrap gap-2"
          tabClassName="project-subnav-link"
          activeTabClassName="project-subnav-link-active"
          options={[
            ['google', 'Google'],
            ['bing', 'Bing'],
          ]}
        />
        {!isEmbed() && (
          <WriteButton
            type="button"
            variant="outline"
            size="sm"
            aria-label="Refresh search data"
            disabled={loading || refreshState !== 'idle'}
            onClick={() => void handleRefresh()}
          >
            <RefreshCw className={`h-3.5 w-3.5 ${refreshState !== 'idle' ? 'animate-spin' : ''}`} aria-hidden="true" />
            {loading ? 'Loading…' : refreshState === 'syncing' ? 'Refreshing search data…' : refreshState === 'reloading' ? 'Reloading workspaces…' : 'Refresh search data'}
          </WriteButton>
        )}
      </div>

      {error && (
        <div className="rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative">
          {error}
        </div>
      )}

      <div id={`${tabsId}-panel`} role="tabpanel" aria-labelledby={`${tabsId}-${workspace}`} tabIndex={0}>
      {workspace === 'google' && (
        <GscSection projectName={projectName} refreshNonce={workspaceRefreshNonce} />
      )}

      {workspace === 'bing' && (
        <BingSection projectName={projectName} refreshNonce={workspaceRefreshNonce} />
      )}
      </div>
    </div>
  )
}

/**
 * The queries Citation gaps counts out of: those with an answer whose sources
 * were checked. The API's gap score uses the same population.
 */
function citationGapBase(queryCounts: ProjectCommandCenterVm['queryCounts']): number {
  return queryCounts.total - queryCounts.citationNotMeasured
}

function OverviewMetricRow({
  label,
  summary,
  displayValue,
  tooltip,
}: {
  label: string
  summary: ProjectCommandCenterVm['mentionSummary']
  displayValue?: React.ReactNode
  tooltip?: string
}) {
  // A ratio gauge's value arrives already formatted ("66.7%"); the sign is
  // set apart, never appended, so a count or a label ("No data") shows as sent.
  const { figure, sign } = splitPercentSign(summary.value)
  const progress = summary.progress !== undefined
    ? Math.min(Math.max(summary.progress, 0), 100)
    : 0

  return (
    <div className="aeo-hero-row">
      <p className="aeo-hero-row-label">
        {label}
        {(tooltip || summary.tooltip) && <InfoTooltip text={tooltip || summary.tooltip || ''} />}
      </p>
      <p className={`aeo-hero-row-value ${METRIC_TONE_TEXT_CLASS[summary.tone]}`}>
        {displayValue ?? (
          <>
            {figure}
            {sign ? <span className="text-faint">{sign}</span> : null}
          </>
        )}
      </p>
      <div className="aeo-hero-row-bar" aria-hidden="true">
        <div
          className={`metric-card-bar-fill progress-fill-${summary.tone}`}
          style={{ width: `${progress}%` }}
        />
      </div>
    </div>
  )
}

/** The competitor comparison's empty state, exported so tests assert the shipped strings. */
export const COMPETITOR_COMPARISON_COPY = {
  emptyTitle: 'No competitors set',
  emptyDetail: 'Mention and citation gaps need at least one tracked competitor.',
  add: 'Add competitors',
} as const

function OverviewDisclosure({
  id,
  title,
  meta,
  defaultOpen = false,
  children,
}: {
  id?: string
  title: string
  meta?: string
  defaultOpen?: boolean
  children: React.ReactNode
}) {
  const titleId = useId()
  const metaId = useId()
  return (
    <details id={id} className="overview-disclosure page-section-divider scroll-mt-24" open={defaultOpen || undefined}>
      {/* The summary is the toggle, so it takes its name from the heading
          alone; the meta line is its description. */}
      <summary className="overview-disclosure-summary" aria-labelledby={titleId} aria-describedby={meta ? metaId : undefined}>
        <h2 id={titleId} className="overview-disclosure-title">{title}</h2>
        <span className="overview-disclosure-meta">
          {meta && <span id={metaId}>{meta}</span>}
          <ChevronDown className="overview-disclosure-icon" size={16} aria-hidden="true" />
        </span>
      </summary>
      <div className="overview-disclosure-body">{children}</div>
    </details>
  )
}

function OverviewSignals({
  insights,
  suggestedQueries,
  onManageQueries,
  siteDomain,
}: {
  /**
   * Set where these signals sit beside per-property numbers: their citation
   * state is the older site-wide flag, so each badge names the domain and
   * "any page" instead of a bare "Cited".
   */
  siteDomain?: string
  insights: ProjectCommandCenterVm['insights']
  suggestedQueries: ProjectCommandCenterVm['suggestedQueries']
  onManageQueries?: () => void
}) {
  const { openEvidence } = useDrawer()

  const visibleSuggestions = onManageQueries ? suggestedQueries.rows : []

  if (insights.length === 0 && visibleSuggestions.length === 0) return null

  const renderInsight = (insight: ProjectCommandCenterVm['insights'][number]) => (
    <div key={insight.id} className="py-3">
      <div className="flex items-start justify-between gap-4">
        <div className="min-w-0">
          <p className="text-copy-14-strong text-heading">{insight.title}</p>
          {insight.detail ? <p className="mt-1 max-w-3xl text-copy-14 text-secondary">{insight.detail}</p> : null}
        </div>
        <ToneBadge tone={insight.tone}>{insight.actionLabel}</ToneBadge>
      </div>

      {insight.affectedPhrases.length > 0 ? (
        <details className="mt-2">
          <summary className="w-fit cursor-pointer text-label-14-strong text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60">
            Evidence · {insight.affectedPhrases.length} affected {insight.affectedPhrases.length === 1 ? 'query' : 'queries'}
          </summary>
          <ul className="mt-2 divide-y divide-subtle border-y border-subtle">
            {insight.affectedPhrases.map((phrase, index) => (
              <li key={phrase.evidenceId || `${insight.id}-${index}`} className="flex flex-wrap items-center gap-2 py-2">
                <CitationBadge state={phrase.citationState} {...(siteDomain && phrase.siteCitation !== false ? { label: siteCitationLabel(siteDomain, phrase.citationState) } : {})} />
                <span className="min-w-0 flex-1 text-label-14 text-strong">{phrase.query}</span>
                {phrase.provider ? <ProviderBadge provider={phrase.provider} /> : null}
                {!isEmbed() && phrase.evidenceId ? (
                  <Button type="button" variant="ghost" size="sm" onClick={event => { event.currentTarget.focus({ preventScroll: true }); void openEvidence(phrase.evidenceId) }}>
                    View evidence
                  </Button>
                ) : null}
              </li>
            ))}
          </ul>
        </details>
      ) : null}
    </div>
  )

  const renderSuggestion = (suggestion: ProjectCommandCenterVm['suggestedQueries']['rows'][number]) => (
    <div key={suggestion.query} className="flex items-start justify-between gap-4 py-3">
      <div className="min-w-0">
        <p className="text-label-12-strong normal-case text-muted">Suggested query</p>
        <p className="mt-1 text-copy-14-strong text-strong">{suggestion.query}</p>
        <p className="mt-1 text-copy-14 text-secondary">{suggestion.reason}</p>
      </div>
      {onManageQueries ? <Button type="button" variant="outline" size="sm" onClick={onManageQueries}>Review in Queries</Button> : null}
    </div>
  )

  const primaryInsights = insights.slice(0, 1)
  const primarySuggestions = visibleSuggestions.slice(0, 1)
  const remainingInsights = insights.slice(1)
  const remainingSuggestions = visibleSuggestions.slice(1)
  const remainingCount = remainingInsights.length + remainingSuggestions.length

  return (
    <section className="visibility-disclosure-panel" aria-labelledby="overview-signals-title">
      <div className="section-head">
        <h2 id="overview-signals-title">Latest signals</h2>
      </div>

      <div className="divide-y divide-default border-y border-default">
        {primaryInsights.map(renderInsight)}
        {primarySuggestions.map(renderSuggestion)}
      </div>
      {remainingCount > 0 ? (
        <details className="mt-2">
          <summary className="w-fit cursor-pointer text-label-14-strong text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60">
            {remainingCount} more {remainingCount === 1 ? 'signal' : 'signals'}
          </summary>
          <div className="mt-2 divide-y divide-default border-y border-default">
            {remainingInsights.map(renderInsight)}
            {remainingSuggestions.map(renderSuggestion)}
          </div>
        </details>
      ) : null}
    </section>
  )
}

/**
 * Thin shell that guards on project-dashboard readiness. The real
 * component (`ProjectPageContent`) declares all the page's ~60 hooks,
 * and React requires the same hook count on every render of a given
 * component instance. Inlining the early-return-then-hooks pattern
 * here (as the original code did before this refactor) trips React
 * error #310 the first time the query cache is cold, because the
 * loading-branch render calls fewer hooks than the loaded-branch
 * render that follows. See PR #592 for the matching fix on the
 * pre-refactor code path.
 */
export function ProjectPage(props: { tab: ProjectPageTab }) {
  const { projectName: routeIdentifier } = useParams({ from: '/projects/$projectName' })
  // The URL carries the project name (the canonical identifier). Match by name
  // first; fall back to matching by id so a legacy UUID-shaped URL that wasn't
  // caught by the route-level redirect (e.g. cold cache, SSR) still resolves.
  // Prefer the SSR/test fixture (synchronous, no query needed); otherwise hit
  // the shared `/projects` cache that `useDashboardOverview` populates.
  const contextDashboard = useInitialDashboard()
  const nameFromContext = contextDashboard?.dashboard.projects.find(
    p => p.project.name === routeIdentifier || p.project.id === routeIdentifier,
  )?.project.name ?? null
  const projectsListQuery = useQuery({
    ...getApiV1ProjectsOptions({ client: heyClient }),
    enabled: !nameFromContext,
  })
  const lookupProjectName = nameFromContext
    ?? projectsListQuery.data?.find(p => p.name === routeIdentifier || p.id === routeIdentifier)?.name
    ?? null
  const embed = getEmbedConfig()
  const resolvedTab = resolveProjectPageTab(props.tab, embed)
  // The server overview supplies Simple's primary metrics, but Advanced only
  // exposes it through the collapsed Project signals disclosure. Wait until
  // the plan resolves (or that disclosure opens) before starting the read.
  const [overviewRequestedForProject, setOverviewRequestedForProject] = useState<string | null>(null)
  const overviewRequested = lookupProjectName !== null && overviewRequestedForProject === lookupProjectName
  const requestOverview = useCallback(() => {
    if (lookupProjectName) setOverviewRequestedForProject(lookupProjectName)
  }, [lookupProjectName])
  const {
    commandCenter: model,
    isLoading: dashboardLoading,
    overviewLoading,
    overviewError,
    isError: dashboardError,
    latestVisibilityRevision,
    competitorHistoryRevision,
    refetch,
  } = useProjectDashboard(lookupProjectName, { overview: resolvedTab === 'overview' && overviewRequested })
  const isLoading = (!nameFromContext && projectsListQuery.isLoading) || dashboardLoading

  // Not-found state: both context and the projects-list query resolved
  // (loading is done), but neither could match the URL's identifier to a
  // known project. Render the explicit not-found rather than the
  // indefinite skeleton so the user can navigate away.
  const isNotFound = !lookupProjectName
    && !nameFromContext
    && projectsListQuery.isSuccess
    && !dashboardLoading

  if (isNotFound) {
    return (
      <div className="page-container">
        <Card className="surface-card empty-card">
          <h1>Project not found</h1>
          <p>Could not find a project named "{routeIdentifier}".</p>
          <Button asChild>
            <Link to="/">Return to overview</Link>
          </Button>
        </Card>
      </div>
    )
  }

  if (!model && (dashboardError || projectsListQuery.isError)) {
    return <div className="page-container" role="alert">
      <p>Could not load this project.</p>
      <Button type="button" variant="outline" onClick={() => { void Promise.all([projectsListQuery.refetch(), refetch()]) }}>Retry</Button>
    </div>
  }

  if (!model || isLoading) {
    return (
      <div className="page-skeleton">
        <div className="page-skeleton-header">
          <div className="skeleton-text h-6 w-48" />
          <div className="skeleton-text-sm w-32" />
        </div>
        <div className="grid grid-cols-3 gap-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="page-skeleton-card flex flex-col items-center">
              <div className="skeleton-circle size-20" />
              <div className="skeleton-text w-16 mt-3" />
            </div>
          ))}
        </div>
        <div className="page-skeleton-card">
          <div className="skeleton-text w-28" />
          <div className="space-y-2 mt-2">
            {[1, 2, 3, 4].map((j) => (
              <div key={j} className="skeleton-text-sm w-full" />
            ))}
          </div>
        </div>
      </div>
    )
  }

  return <ProjectPageContent
    model={model}
    refetch={refetch}
    latestVisibilityRevision={latestVisibilityRevision}
    competitorHistoryRevision={competitorHistoryRevision}
    overviewLoading={overviewLoading}
    overviewError={overviewError}
    overviewRequested={overviewRequested}
    onRequestOverview={requestOverview}
    {...props}
  />
}

export type ProjectTabItem = { key: ProjectPageTab; label: string; href: string }

/**
 * The project sections in tab-row order. The row keeps the sections an
 * operator returns to, AI Visibility first and Queries last; the rest open
 * from More, and a narrow panel moves the row's later sections into More too.
 * `key` is a wire value for embed allowlists and saved URLs. Journeys reads
 * private visitor evidence, so view-only accounts never get it, and it is
 * absent from the embed allowlist, so embeds drop it too.
 */
export function projectSectionTabs(projectTabBase: string, { journeys }: { journeys: boolean }): { primary: ProjectTabItem[]; overflow: ProjectTabItem[] } {
  return {
    primary: [
      { key: 'overview', label: 'AI Visibility', href: projectTabBase },
      { key: 'search-console', label: 'Search engines', href: `${projectTabBase}/search-console` },
      { key: 'seo-data', label: 'SEO', href: `${projectTabBase}/seo-data` },
      { key: 'activity', label: 'Activity', href: `${projectTabBase}/activity` },
      // `agent-readiness` is the route and embed token; the retired `/technical-aeo`
      // route redirects here, and embeds that still list `technical-aeo` keep the tab.
      { key: 'agent-readiness', label: 'Agent Readiness', href: `${projectTabBase}/agent-readiness` },
      ...(journeys ? [{ key: 'journeys' as const, label: 'Journeys', href: `${projectTabBase}/journeys` }] : []),
      { key: 'traffic', label: 'Server traffic', href: `${projectTabBase}/traffic` },
      { key: 'queries', label: 'Queries', href: `${projectTabBase}/queries` },
    ],
    overflow: [
      { key: 'conversions', label: 'Conversions', href: `${projectTabBase}/conversions` },
      { key: 'local', label: 'Local presence', href: `${projectTabBase}/local` },
      { key: 'backlinks', label: 'Backlinks', href: `${projectTabBase}/backlinks` },
      { key: 'history', label: 'Change history', href: `${projectTabBase}/history` },
    ],
  }
}

export function ProjectSubnav({ items, overflowItems, settingsItem, activeTab }: {
  items: ProjectTabItem[]
  overflowItems: ProjectTabItem[]
  settingsItem: ProjectTabItem | null
  activeTab: ProjectPageTab
}) {
  const navRef = useRef<HTMLElement>(null)
  const measurementRef = useRef<HTMLDivElement>(null)
  const [layout, setLayout] = useState<{ visibleKeys: ProjectPageTab[]; settingsInMore: boolean } | null>(null)
  // An open section that normally lives in More is shown as a tab before More,
  // so the row always names the current page.
  const { rowItems, menuOverflowItems } = useMemo(() => {
    const activeOverflowItem = overflowItems.find(item => item.key === activeTab)
    return {
      rowItems: activeOverflowItem ? [...items, activeOverflowItem] : items,
      menuOverflowItems: overflowItems.filter(item => item !== activeOverflowItem),
    }
  }, [items, overflowItems, activeTab])

  useLayoutEffect(() => {
    const nav = navRef.current
    const measurements = measurementRef.current
    if (!nav || !measurements) return
    const measure = () => {
      const available = nav.getBoundingClientRect().width
      if (!available) return // Hidden surfaces are measured when they become visible.
      const gap = Number.parseFloat(getComputedStyle(nav).columnGap) || 0
      const widths = new Map([...measurements.querySelectorAll<HTMLElement>('[data-project-tab]')]
        .map(element => [element.dataset.projectTab!, element.getBoundingClientRect().width]))
      const widthOf = (key: string) => widths.get(key) ?? 0
      const totalWidth = (keys: string[]) => keys.reduce((total, key) => total + widthOf(key), 0) + Math.max(0, keys.length - 1) * gap
      const allKeys = [...rowItems.map(item => item.key), ...(menuOverflowItems.length ? ['more'] : []), ...(settingsItem ? [settingsItem.key] : [])]
      let visibleKeys = rowItems.map(item => item.key)
      let settingsInMore = false
      if (totalWidth(allKeys) > available) {
        // Keep the selected section in view, even when it is near the end of
        // the tab list. Settings joins More only on very narrow panels, and
        // never while it is the open section.
        const active = rowItems.find(item => item.key === activeTab)
        const selected = active ? [active.key] : []
        settingsInMore = Boolean(settingsItem && settingsItem.key !== activeTab
          && totalWidth([...selected, 'more', settingsItem.key]) > available)
        const trailing = ['more', ...(settingsItem && !settingsInMore ? [settingsItem.key] : [])]
        for (const item of rowItems) {
          if (item.key === active?.key) continue
          if (totalWidth([...selected, item.key, ...trailing]) > available) break
          selected.push(item.key)
        }
        visibleKeys = rowItems.filter(item => selected.includes(item.key)).map(item => item.key)
      }
      setLayout(previous => previous?.settingsInMore === settingsInMore && previous.visibleKeys.join() === visibleKeys.join()
        ? previous
        : { visibleKeys, settingsInMore })
    }
    measure()
    if (typeof ResizeObserver === 'undefined') {
      window.addEventListener('resize', measure)
      return () => window.removeEventListener('resize', measure)
    }
    const observer = new ResizeObserver(measure)
    observer.observe(nav)
    observer.observe(measurements) // Font loading or changed labels can alter item widths.
    return () => observer.disconnect()
  }, [rowItems, menuOverflowItems, settingsItem, activeTab])

  // The open section stays in the row even before a new active tab is measured.
  const settingsInMore = Boolean(layout?.settingsInMore) && settingsItem?.key !== activeTab
  const visibleItems = layout
    ? rowItems.filter(item => item.key === activeTab || layout.visibleKeys.includes(item.key))
    : rowItems
  const menuItems = [
    ...rowItems.filter(item => !visibleItems.includes(item)),
    ...menuOverflowItems,
    ...(settingsInMore && settingsItem ? [settingsItem] : []),
  ]

  return (
    <nav className="project-subnav" aria-label="Project sections" ref={navRef}>
      <div className="project-subnav-measure" aria-hidden="true">
        <div className="project-subnav-measure-row" ref={measurementRef}>
          {[...rowItems, ...(settingsItem ? [settingsItem] : [])].map(item => (
            <span className="project-subnav-link" key={item.key} data-project-tab={item.key}>{item.label}</span>
          ))}
          <span className="project-subnav-link project-subnav-more-trigger" data-project-tab="more">
            More<ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />
          </span>
        </div>
      </div>
      {visibleItems.map(item => (
        <Link
          key={item.key}
          to={item.href}
          search={previous => ({ ...previous, onboarding: undefined })}
          // AI Visibility is the project root, the parent of every other
          // section. The router's default prefix match would mark it current
          // on every section too, so only an exact match counts; `activeTab`
          // decides the current page.
          activeOptions={{ exact: true }}
          className={`project-subnav-link ${item.key === activeTab ? 'project-subnav-link-active project-subnav-current' : ''}`}
          aria-current={item.key === activeTab ? 'page' : undefined}
        >
          <span className="project-subnav-label">{item.label}</span>
        </Link>
      ))}
      <div className="project-subnav-trailing">
        <ProjectSubnavMore items={menuItems} />
        {settingsItem && !settingsInMore && (
          <Link
            to={settingsItem.href}
            search={previous => ({ ...previous, onboarding: undefined })}
            className={`project-subnav-link ${activeTab === 'settings' ? 'project-subnav-link-active' : ''}`}
            aria-current={activeTab === 'settings' ? 'page' : undefined}
          >
            {settingsItem.label}
          </Link>
        )}
      </div>
    </nav>
  )
}

/**
 * Trailing overflow ("More") menu for sections that do not fit in the tab row.
 * A standard disclosure: button toggles a `role="menu"`, closes on outside
 * pointerdown, Escape, or item selection. Self-contained so its hooks don't
 * sit below ProjectPageContent's early returns. Lives here (not in its own
 * file) because it's a one-off for this subnav.
 */
function ProjectSubnavMore({ items }: { items: ProjectTabItem[] }) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)
  const triggerRef = useRef<HTMLButtonElement>(null)
  const initialFocus = useRef<'first' | 'last'>('first')
  const menuId = useId()
  const itemKeys = items.map(item => item.key).join()
  useEffect(() => { setOpen(false) }, [itemKeys])
  useEffect(() => {
    if (!open) return
    const menuItems = ref.current?.querySelectorAll<HTMLElement>('[role="menuitem"]')
    const selected = initialFocus.current === 'last' ? menuItems?.[menuItems.length - 1] : menuItems?.[0]
    selected?.focus()
  }, [open])
  useEffect(() => {
    if (!open) return
    const onPointerDown = (event: PointerEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) setOpen(false)
    }
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setOpen(false)
        triggerRef.current?.focus()
      }
    }
    document.addEventListener('pointerdown', onPointerDown)
    document.addEventListener('keydown', onKeyDown)
    return () => {
      document.removeEventListener('pointerdown', onPointerDown)
      document.removeEventListener('keydown', onKeyDown)
    }
  }, [open])

  if (items.length === 0) return null

  return (
    <div className="project-subnav-more" ref={ref}>
      <button
        type="button"
        ref={triggerRef}
        className="project-subnav-link project-subnav-more-trigger"
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls={open ? menuId : undefined}
        onClick={() => { initialFocus.current = 'first'; setOpen(prev => !prev) }}
        onKeyDown={event => {
          if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return
          event.preventDefault()
          initialFocus.current = event.key === 'ArrowUp' ? 'last' : 'first'
          setOpen(true)
        }}
      >
        More
        <ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />
      </button>
      {open ? (
        <div className="project-subnav-menu" role="menu" id={menuId} aria-label="More project sections"
          onKeyDown={event => {
            const menuItems = [...event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]')]
            const current = menuItems.indexOf(document.activeElement as HTMLElement)
            const next = event.key === 'Home' ? 0
              : event.key === 'End' ? menuItems.length - 1
                : event.key === 'ArrowDown' ? (current + 1) % menuItems.length
                  : event.key === 'ArrowUp' ? (current - 1 + menuItems.length) % menuItems.length : null
            if (next !== null) {
              event.preventDefault()
              menuItems[next]?.focus()
            }
          }}
          onBlur={event => {
            if (!ref.current?.contains(event.relatedTarget as Node | null)) setOpen(false)
          }}
        >
          {items.map((item) => (
            <Link
              key={item.key}
              to={item.href}
              search={previous => ({ ...previous, onboarding: undefined })}
              role="menuitem"
              tabIndex={-1}
              className="project-subnav-menu-item"
              onClick={() => setOpen(false)}
            >
              {item.label}
            </Link>
          ))}
        </div>
      ) : null}
    </div>
  )
}

/**
 * Same window Agent Readiness's own scan picker reads. Deep enough that a run of
 * failures does not hide the completed scan underneath them.
 */
const MAP_SITE_SCAN_HISTORY_LIMIT = 20

/** The newest saved sweeps the sentiment backfill offers. */
const SENTIMENT_BACKFILL_SWEEP_OPTIONS = 5

function ProjectPageContent({
  tab: requestedTab,
  model,
  refetch,
  latestVisibilityRevision,
  competitorHistoryRevision,
  overviewLoading,
  overviewError,
  overviewRequested,
  onRequestOverview,
}: {
  tab: ProjectPageTab
  model: ProjectCommandCenterVm
  refetch: () => Promise<void>
  latestVisibilityRevision: string
  competitorHistoryRevision: string
  overviewLoading: boolean
  overviewError: boolean
  overviewRequested: boolean
  onRequestOverview: () => void
}) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const { account, canWrite, isAdmin } = useAccount()
  const [sweepConfirmationProject, setSweepConfirmationProject] = useState<string | null>(null)
  const sweepOpener = useRef<HTMLButtonElement | null>(null)
  const initialDashboard = useInitialDashboard()
  const projectName = model.project.name
  const hasInitialProjectDashboard = initialDashboard?.dashboard.projects.some(entry => entry.project.name === projectName) ?? false
  const projectSearchParams = useSearch({ strict: false }) as Record<string, unknown> & {
    connectCloudRun?: CloudRunTrafficSetup
    manageQueries?: boolean
    runId?: string
    siteHealthRunId?: string
    scope?: string
    class?: string
  }
  const visibilitySelection = parseVisibilitySelection(projectSearchParams)
  const measurementScoped = isMeasurementScoped(visibilitySelection)
  const embedProjectTabs = useMemo(() => effectiveEmbedProjectTabs(getEmbedConfig()), [])
  const queryLimit = useMemo(() => embedQueryLimit(getEmbedConfig()), [])
  const tab = useMemo(() => resolveProjectPageTab(requestedTab, getEmbedConfig()), [requestedTab])
  const showVisibilityChecks = tab === 'overview' && !isEmbed()
  const managedSweeps = isDashboardManagedSweeps()
  const measurementSetupQuery = useQuery({
    ...getApiV1ProjectsByNameMeasurementSetupOptions({ client: heyClient, path: { name: projectName } }),
    // The overview needs run readiness and the measurement mode. Portfolio,
    // Settings and scoped URLs also use setup to resolve measurement context.
    enabled: !isEmbed()
      && Boolean(projectName)
      && (tab === 'overview' || tab === 'portfolio' || tab === 'settings' || measurementScoped),
    staleTime: 0,
    refetchOnMount: 'always',
    refetchOnWindowFocus: 'always',
  })
  const initialConfiguredApiProviders = initialDashboard
    ? initialDashboard.dashboard.settings.providerStatuses
      .filter(provider => provider.state !== 'needs-config')
      .map(provider => normalizeProviderName(provider.name))
    : undefined
  const serverProviderReady = measurementSetupQuery.data?.answerVisibilityProviderReady
  const configuredApiProviders = initialConfiguredApiProviders
  const projectProviders = model.project.providers.map(normalizeProviderName)
  const selectedApiProviderReady = configuredApiProviders?.some(provider => (
    projectProviders.length === 0 || projectProviders.includes(provider)
  )) === true
  const selectionCanUseCdp = projectProviders.length === 0 || projectProviders.includes(CDP_PROVIDER_NAME)
  const cdpStatusQuery = useQuery({
    ...getApiV1CdpStatusOptions({ client: heyClient }),
    // The setup response owns live readiness. The direct CDP read remains only
    // as a first-paint fallback while a fixture or cold request has no setup
    // response yet.
    enabled: showVisibilityChecks
      && !managedSweeps
      && canWrite
      && serverProviderReady === undefined
      && selectionCanUseCdp
      && !selectedApiProviderReady,
    staleTime: 60_000,
    retry: false,
  })
  // The server returns `browserVersion` from the registered adapter's health
  // check even when Chrome is currently disconnected. The unregistered branch
  // omits it. `connected` is therefore live browser health, not run preflight.
  const cdpConfigured = !selectionCanUseCdp
    ? false
    : cdpStatusQuery.isSuccess
      ? typeof cdpStatusQuery.data.browserVersion === 'string'
      : cdpStatusQuery.isError ? false : undefined
  const providerReady = serverProviderReady ?? resolveAiVisibilityProviderReadiness({
    projectProviders,
    configuredApiProviders,
    cdpConfigured,
  })
  const competitorDomains = useMemo(() => model.competitors.map(c => c.domain), [model.competitors])
  const competitorAliases = useMemo<Record<string, readonly string[]>>(
    () => Object.fromEntries(model.competitors.map(c => [c.domain, c.aliases ?? []])),
    [model.competitors],
  )
  // Names detected from stored answers, shown labelled "auto" beside the curated ones.
  const competitorAutoAliases = useMemo<Record<string, readonly string[]>>(
    () => Object.fromEntries(model.competitors.map(c => [c.domain, c.autoAliases ?? []])),
    [model.competitors],
  )
  // Every name a competitor answers to (curated and auto): both change mention
  // share, so both key the cached trend frames.
  const competitorIdentityNames = useMemo<Record<string, readonly string[]>>(
    () => Object.fromEntries(model.competitors.map(c => [c.domain, [...(c.aliases ?? []), ...(c.autoAliases ?? [])]])),
    [model.competitors],
  )
  // "Local presence" is always shown — GbpSection renders a setup guide when no
  // Google Business Profile is connected, so the tab is the entry point to
  // connecting one rather than being hidden until after connection.
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [deleting, setDeleting] = useState(false)
  const appendQueries = useAppendQueries()
  const updateVisibilitySearch = useCallback((patch: Record<string, unknown>, options?: { replace?: boolean }) => {
    void navigate({ to: '.', search: previous => patchVisibilitySelection(previous, patch), replace: options?.replace === true })
  }, [navigate])
  // Tracked Queries take their scope control from the query-tracking workspace.
  // Every role loads it, and the Queries body observes this same key.
  const requestedQueryWorkspace: QueryWorkspace = projectSearchParams.queryWorkspace === 'research' || (tab === 'discovery' && projectSearchParams.queryWorkspace === undefined) ? 'research' : 'tracked'
  const queryWorkspace = effectiveQueryWorkspace(requestedQueryWorkspace, canUseResearchWorkspace(account?.role, account?.role === 'viewer' ? getViewerResearchConfig() : null))
  const trackingWorkspaceQuery = useQuery({
    ...getApiV1ProjectsByNameQueryTrackingOptions({ client: heyClient, path: { name: projectName } }),
    enabled: !isEmbed() && (tab === 'queries' || tab === 'discovery') && queryWorkspace === 'tracked',
  })
  const manageQueriesRequested = projectSearchParams.manageQueries === true
  const releaseInitialSiteHealthRun = useCallback(() => {
    void navigate({
      to: '.',
      replace: true,
      search: (previous: Record<string, unknown>) => ({ ...previous, siteHealthRunId: undefined }),
    })
  }, [navigate])
  const [managingQueries, setManagingQueries] = useState(manageQueriesRequested)
  const [newQueryText, setNewQueryText] = useState('')
  const [querySaving, setQuerySaving] = useState(false)
  const [removingQuery, setRemovingQuery] = useState<string | null>(null)
  const [competitorLandscapeWindow, setCompetitorLandscapeWindow] = useState<CompetitorLandscapeWindow>('30d')
  const [locationFilter, setLocationFilter] = useState<string | undefined>(undefined)
  const [evidenceProvider, setEvidenceProvider] = useState('')
  const [compareLocations, setCompareLocations] = useState(false)
  const [locationTimeline, setLocationTimeline] = useState<import('../api.js').ApiTimelineEntry[] | null>(null)
  const [_locationTimelineLoading, setLocationTimelineLoading] = useState(false)
  // Scope and query class come from the URL so a market is a place you can
  // link, bookmark and reload — at hundreds of markets, re-picking one after
  // every navigation IS the interaction. `search` stays local: it changes on
  // every keystroke and belongs in neither the URL nor the history stack.
  const urlMeasurementView = parseMeasurementViewSearch(projectSearchParams)
  const [advancedMeasurementSearch, setAdvancedMeasurementSearch] = useState<string | undefined>(undefined)
  // Sort is a within-view refinement, not what the page is ABOUT, so it stays
  // in component state rather than the URL alongside scope and class.
  const [advancedMeasurementSort, setAdvancedMeasurementSort] = useState<MeasurementOverviewSort | undefined>(undefined)
  const setAdvancedMeasurementView = useCallback((next: {
    scope: 'all' | 'group'
    groupKey?: string
    queryClass: 'all' | 'non-brand' | 'branded'
    search?: string
    sort?: MeasurementOverviewSort
  }) => {
    setAdvancedMeasurementSearch(next.search)
    if (next.sort) setAdvancedMeasurementSort(next.sort)
    // Scope and class are deliberate, low-frequency choices, so they PUSH:
    // pressing back after picking a market should return to the previous
    // market, which is what a reader expects of a control that changes what
    // the page is about.
    void navigate({
      to: '.',
      search: (prev: Record<string, unknown>) => ({ ...prev, ...measurementViewSearch(next) }),
      replace: false,
    })
  }, [navigate])
  const [hasExpandedAdvancedProperty, setHasExpandedAdvancedProperty] = useState(false)

  const projectLabel = model?.project.displayName || model?.project.name || projectName
  const triggerRunMutation = useTriggerRun()
  const runPreview = useRunPreview(projectName, showVisibilityChecks && !managedSweeps && sweepConfirmationProject === projectName)
  const portfolioQueriesQuery = useQuery({
    ...getApiV1ProjectsByNameQueriesOptions({ client: heyClient, path: { name: projectName } }),
    enabled: tab === 'portfolio' && Boolean(projectName),
    staleTime: 0,
    refetchOnMount: 'always',
  })
  const activeMeasurementPlanQuery = useQuery({
    ...getApiV1ProjectsByNameMeasurementPlanOptions({ client: heyClient, path: { name: projectName } }),
    // The public demo reads it on every tab: its context row tags an advanced
    // project wherever it renders, including a deep link.
    enabled: !isEmbed()
      && Boolean(projectName)
      && (isPublicDemo() || tab === 'portfolio' || tab === 'overview' || tab === 'settings' || (canWrite && measurementScoped)),
    staleTime: 0,
    refetchOnMount: 'always',
  })
  const activeMeasurementPlan = activeMeasurementPlanQuery.data?.active ?? null

  // A bookmark outlives the group it names. Once the plan has actually loaded
  // and we can see which groups exist, a URL naming one that does not is
  // resolved to all-properties BEFORE any request goes out — otherwise the page
  // asks the server for a scope that cannot exist and paints a skeleton at
  // someone who simply followed an old link. While the plan is still in flight
  // the key is left alone: absence of an answer is not evidence the group is
  // gone.
  const planGroupKeysLoaded = activeMeasurementPlanQuery.data !== undefined
  const planGroupKeys = new Set(
    activeMeasurementPlan && Number(activeMeasurementPlan.plan.schemaVersion) === 2
      ? (activeMeasurementPlan.plan as { groups?: { stableKey: string }[] }).groups?.map(group => group.stableKey) ?? []
      : [],
  )
  const measurementScopeIsStale = urlMeasurementView.scope === 'group'
    && Boolean(urlMeasurementView.groupKey)
    && planGroupKeysLoaded
    && !planGroupKeys.has(urlMeasurementView.groupKey!)
  const advancedMeasurementView = {
    ...(measurementScopeIsStale
      ? { scope: 'all' as const, queryClass: urlMeasurementView.queryClass }
      : urlMeasurementView),
    ...(advancedMeasurementSearch ? { search: advancedMeasurementSearch } : {}),
  }
  const activeMeasurementPlanSchemaVersion = activeMeasurementPlan === null
    ? null
    : Number(activeMeasurementPlan.plan.schemaVersion)
  const activeMeasurementRevision = activeMeasurementPlan?.revision ?? 0
  // Reset the view only when the plan it belongs to actually CHANGES. The
  // identity is null until the plan resolves, and the first identity we ever
  // see is not a change — see `shouldResetMeasurementView`, which is where the
  // two "not a change" cases are pinned by tests.
  const measurementPlanIdentity = planGroupKeysLoaded
    ? `${projectName}:${activeMeasurementRevision}`
    : null
  const lastMeasurementPlanIdentity = useRef<string | null>(null)
  useEffect(() => {
    const previous = lastMeasurementPlanIdentity.current
    if (measurementPlanIdentity !== null) lastMeasurementPlanIdentity.current = measurementPlanIdentity
    if (!shouldResetMeasurementView(previous, measurementPlanIdentity)) return
    setAdvancedMeasurementView({ scope: 'all', queryClass: 'all' })
    setHasExpandedAdvancedProperty(false)
  }, [measurementPlanIdentity, setAdvancedMeasurementView])
  const advancedMeasurementOverviewQueryInput = {
    client: heyClient,
    path: { name: projectName },
    query: {
      scope: advancedMeasurementView.scope,
      ...(advancedMeasurementView.groupKey ? { groupKey: advancedMeasurementView.groupKey } : {}),
      queryClass: advancedMeasurementView.queryClass,
      ...(advancedMeasurementView.search ? { search: advancedMeasurementView.search } : {}),
      ...(advancedMeasurementSort ? { sort: advancedMeasurementSort } : {}),
      limit: 50,
    },
  } as const
  const advancedMeasurementOverviewQuery = useInfiniteQuery({
    ...getApiV1ProjectsByNameMeasurementOverviewInfiniteOptions(advancedMeasurementOverviewQueryInput),
    // V2 results now come from visibility-report. Keep the legacy query shape
    // only for the retained landing presentation; do not double-read evidence.
    enabled: false,
    initialPageParam: advancedMeasurementOverviewQueryInput,
    getNextPageParam: (lastPage, pages) => {
      if (!lastPage.properties.nextCursor) return undefined
      const displayedRunId = pages[0]?.measurement.displayedRunId
      return {
        path: advancedMeasurementOverviewQueryInput.path,
        query: {
          ...advancedMeasurementOverviewQueryInput.query,
          cursor: lastPage.properties.nextCursor,
          ...(displayedRunId ? { runId: displayedRunId } : {}),
        },
      }
    },
    placeholderData: keepPreviousData,
    staleTime: 0,
    refetchOnMount: 'always',
  })
  const advancedMeasurementDisplayedRunId = advancedMeasurementOverviewQuery.data?.pages[0]?.measurement.displayedRunId
  const advancedMeasurementReportQuery = useQuery({
    ...getApiV1ProjectsByNameMeasurementReportOptions({
      client: heyClient,
      path: { name: projectName },
      query: {
        revision: activeMeasurementRevision,
        ...(advancedMeasurementDisplayedRunId
          ? { runId: advancedMeasurementDisplayedRunId }
          : {}),
      },
    }),
    enabled: tab === 'overview'
      && Boolean(projectName)
      && activeMeasurementPlan !== null
      && activeMeasurementPlanSchemaVersion === 1,
    staleTime: 0,
    refetchOnMount: 'always',
  })
  const hasCachedMeasurementPlan = activeMeasurementPlanQuery.data !== undefined
  const hasCachedPortfolioQueries = portfolioQueriesQuery.data !== undefined
  const isActiveMeasurementPlanLoading = activeMeasurementPlanQuery.isPending && !hasCachedMeasurementPlan
  const isActiveMeasurementPlanError = activeMeasurementPlanQuery.isError && !hasCachedMeasurementPlan
  const isPortfolioQueriesLoading = portfolioQueriesQuery.isPending && !hasCachedPortfolioQueries
  const isPortfolioQueriesError = portfolioQueriesQuery.isError && !hasCachedPortfolioQueries
  const hasCachedAdvancedMeasurementReport = advancedMeasurementReportQuery.data !== undefined
  const advancedMeasurementMode = resolveAdvancedMeasurementMode({
    activePlanSchemaVersion: measurementSetupQuery.data?.activeSchemaVersion ?? activeMeasurementPlanSchemaVersion,
    hasDraft: measurementSetupQuery.data?.draft !== null && measurementSetupQuery.data?.draft !== undefined,
  })
  const isSimpleOverview = advancedMeasurementMode.surface === 'simple-overview'
  // Demo only: it tells a visitor switching projects why this one looks different.
  const advancedProjectTag = isPublicDemo() && activeMeasurementPlan?.plan.schemaVersion === 2
    ? advancedProjectTagDetail(activeMeasurementPlan.plan)
    : null
  /**
   * Which overview to show is not known until one of the two plan reads lands.
   * Until then the expression above is `undefined ?? null`, and `null` is what
   * `resolveAdvancedMeasurementMode` reads as "this project has no plan" — so a
   * project WITH a plan rendered the legacy overview first and swapped it out a
   * moment later. Pending and absent cannot share a value here.
   *
   * Known as soon as EITHER read has data, because the setup read only refines
   * a decision the plan read can already make (it is the `??` fallback above).
   * Waiting on both would hold a skeleton over an answer already in hand.
   *
   * `isLoading`, not `isPending`: both queries are disabled on tabs that do not
   * read the plan, and a disabled TanStack v5 query reports `isPending` forever,
   * which would strand those tabs on a skeleton. `isLoading` is false when
   * disabled and false while refetching over cached data, so this fires once per
   * cold load and never again. Once both have settled — data or error — `null`
   * means what it says, and the legacy overview is the right answer.
   */
  const isMeasurementModeUnresolved =
    measurementSetupQuery.data === undefined
    && activeMeasurementPlanQuery.data === undefined
    && (activeMeasurementPlanQuery.isLoading || measurementSetupQuery.isLoading)
  useEffect(() => {
    if (tab === 'overview' && isSimpleOverview && !isMeasurementModeUnresolved) onRequestOverview()
  }, [isMeasurementModeUnresolved, isSimpleOverview, onRequestOverview, tab])
  const scopeSlot = projectScopeSlot({
    tab,
    surface: isMeasurementModeUnresolved ? 'unresolved' : advancedMeasurementMode.surface,
    embedded: isEmbed(),
    scoped: measurementScoped,
    queryWorkspace,
    tracking: trackingWorkspaceQuery.isError
      ? { state: 'error' }
      : trackingWorkspaceQuery.data
        ? { state: 'ready', mode: trackingWorkspaceQuery.data.mode, scopeUnavailable: unavailableTrackingScope(trackingWorkspaceQuery.data, visibilitySelection) }
        : { state: 'pending' },
  })
  // The workspace below reads this exact first page, so the row adds no request.
  const reportScopeQuery = useVisibilityReportFirstPage(projectName, visibilitySelection, { enabled: scopeSlot.kind === 'report-picker' })
  const needsSimpleEvidence = tab === 'overview' && isSimpleOverview && !isMeasurementModeUnresolved
  const evidenceDashboard = useProjectDashboard(projectName, { evidence: needsSimpleEvidence })
  const visibilityEvidence = evidenceDashboard.commandCenter?.visibilityEvidence ?? model.visibilityEvidence
  // One query classifier for the trend and the class-split cards. Evidence rows
  // carry the class the query table shows; anything else (a removed query, a
  // stored basket key) goes through the brand matcher the metrics route uses.
  const classifyQuery = useMemo<QueryClassLookup>(() => {
    const known = new Map(visibilityEvidence.map(row => [normalizeQueryText(row.query), row.queryClass ?? null]))
    const classifier = compileQueryClassifier(effectiveBrandNames(model.project))
    return text => {
      const hit = known.get(normalizeQueryText(text))
      return hit !== undefined ? hit : classifier?.classify(text) ?? null
    }
  }, [visibilityEvidence, model.project])
  // Query text as written, so the trend can name a stored (lowercase) basket key.
  const trackedQueryTexts = useMemo(() => [...new Set([
    ...visibilityEvidence.map(row => row.query),
    ...model.movementComparison.addedQueries,
    ...model.movementComparison.removedQueries,
  ])], [visibilityEvidence, model.movementComparison])
  // The trend splits by query class only when there is something on each side
  // and a brand name the metrics route can classify with.
  const trendQueryClassSplit = useMemo(() => {
    if (!compileQueryClassifier(effectiveBrandNames(model.project))) return false
    const classes = new Set(visibilityEvidence.map(row => classifyQuery(row.query)))
    return classes.has('branded') && classes.has('non-brand')
  }, [model.project, visibilityEvidence, classifyQuery])
  // Real sweeps only, to date the sweep before a model or query change. Every
  // one back from the latest, so newer failed runs never leave a gap.
  const recentSweepTimes = useMemo(() => model.visibilitySweeps.map(run => run.createdAt), [model.visibilitySweeps])
  // Advanced competitor reads are explicit. A market keeps its frozen market
  // identities AND the project pins that the stored-evidence API unions into
  // its denominator. All markets is a separate raw-evidence aggregate, never
  // an average of market percentages.
  const competitorLandscapeGroupKey = activeMeasurementPlanSchemaVersion === 2
    && visibilitySelection.measurementScope === 'group'
    ? visibilitySelection.measurementScopeKey
    : undefined
  const isAdvancedAllMarkets = activeMeasurementPlanSchemaVersion === 2
    && visibilitySelection.measurementScope === 'project'
  const selectedCompetitorLandscapeGroup = useMemo(() => {
    if (activeMeasurementPlan?.plan.schemaVersion !== 2 || !competitorLandscapeGroupKey) return undefined
    return activeMeasurementPlan.plan.groups.find(group => group.stableKey === competitorLandscapeGroupKey)
  }, [activeMeasurementPlan, competitorLandscapeGroupKey])
  const competitorLandscapeQueryInput = {
    client: heyClient,
    path: { name: projectName },
    query: {
      window: competitorLandscapeWindow,
      // Simple projects have no class control, so the card asks for the one
      // class a competitive reading can be built on. Pooling branded queries in
      // would hand the project its own name back as market share.
      queryClass: activeMeasurementPlanSchemaVersion === 2 && visibilitySelection.queryClass !== 'unknown' ? visibilitySelection.queryClass : 'non-brand' as const,
      ...(competitorLandscapeGroupKey ? { groupKey: competitorLandscapeGroupKey } : {}),
      ...(isAdvancedAllMarkets ? { scope: 'all-markets' as const } : {}),
    },
  } as const
  const competitorLandscapeAvailable = tab === 'overview'
    && !visibilitySelection.marketKey
    && Boolean(projectName)
    && (isSimpleOverview || planGroupKeysLoaded)
    && !isMeasurementModeUnresolved
    && (isSimpleOverview || (
      (visibilitySelection.measurementScope === 'project' || activeMeasurementPlanSchemaVersion === 2 && visibilitySelection.measurementScope === 'group')
      && visibilitySelection.queryClass !== 'unknown'
      && (activeMeasurementPlanSchemaVersion === 2 || visibilitySelection.queryClass !== 'branded')
    ))
  const [competitorHistoryOpenForProject, setCompetitorHistoryOpenForProject] = useState<string | null>(null)
  useEffect(() => {
    if (!competitorLandscapeAvailable) setCompetitorHistoryOpenForProject(null)
  }, [competitorLandscapeAvailable])
  useEffect(() => {
    setCompetitorHistoryOpenForProject(null)
  }, [projectName])
  const competitorHistoryOpen = competitorHistoryOpenForProject === projectName
  // "Add competitors" in the comparison's empty state opens Competitor history,
  // where competitors are pinned and added, and moves focus to its toggle once
  // it is open.
  const competitorHistoryRef = useRef<HTMLDetailsElement>(null)
  const [competitorHistoryFocusPending, setCompetitorHistoryFocusPending] = useState(false)
  useEffect(() => {
    if (!competitorHistoryFocusPending || !competitorHistoryOpen) return
    setCompetitorHistoryFocusPending(false)
    competitorHistoryRef.current?.querySelector<HTMLElement>(':scope > summary')?.focus()
  }, [competitorHistoryFocusPending, competitorHistoryOpen])
  const competitiveTitleId = useId()
  const competitiveMetaId = useId()
  // Historical evidence is read when its disclosure opens.
  const competitorLandscapeReadEnabled = competitorLandscapeAvailable && competitorHistoryOpen
  const competitorLandscapeQuery = useQuery({
    ...getApiV1ProjectsByNameAnalyticsCompetitorsOptions(competitorLandscapeQueryInput),
    enabled: competitorLandscapeReadEnabled,
    staleTime: 0,
    refetchOnMount: 'always',
    // CLI/agent classification and pin changes do not emit browser mutations.
    refetchOnWindowFocus: 'always',
  })
  useCompetitorLandscapeRefresh(projectName, JSON.stringify([
    competitorHistoryRevision,
    model.competitors.map(competitor => `${competitor.domain}=${[...(competitor.aliases ?? []), ...(competitor.autoAliases ?? [])].join('|')}`).sort(),
    model.project.canonicalDomain, model.project.ownedDomains, model.project.aliases, model.project.displayName,
    activeMeasurementRevision,
    measurementSetupQuery.data?.draft?.etag ?? null,
  ]), competitorLandscapeReadEnabled)
  const competitorLandscapeError = !competitorLandscapeQuery.isError
    ? undefined
    : competitorLandscapeQuery.data === undefined
      ? 'Could not load competitors over time. Your pinned competitors remain available.'
      : 'Could not refresh competitors over time. Showing the last available data.'
  const projectPinnedCompetitorFallback = useMemo<CompetitorLandscapeRow[]>(() => (
    model.competitors.map(competitor => ({
      domain: competitor.domain,
      label: competitor.domain,
      surfaceClass: 'direct-competitor',
      pinned: true,
      mentionCount: 0,
      shareOfVoice: null,
      citationCount: competitor.citationCount,
      answeredResults: competitor.totalQueries,
      firstSeenAt: null,
      lastSeenAt: null,
      sampleUrls: [],
    }))
  ), [model.competitors])
  const advancedPinnedCompetitorFallback = useMemo<CompetitorLandscapeRow[]>(() => {
    if (activeMeasurementPlan?.plan.schemaVersion !== 2) return projectPinnedCompetitorFallback
    const marketCompetitors = competitorLandscapeGroupKey
      ? (selectedCompetitorLandscapeGroup?.competitors ?? [])
      : activeMeasurementPlan.plan.groups.flatMap(group => group.competitors)
    const merged = new Map<string, CompetitorLandscapeRow>()
    for (const competitor of marketCompetitors) {
      const key = competitor.domain.trim().toLowerCase()
      if (!key || merged.has(key)) continue
      merged.set(key, {
        domain: competitor.domain,
        label: competitor.label,
        surfaceClass: 'direct-competitor',
        pinned: true,
        mentionCount: 0,
        shareOfVoice: null,
        citationCount: 0,
        answeredResults: 0,
        firstSeenAt: null,
        lastSeenAt: null,
        sampleUrls: [],
      })
    }
    for (const competitor of projectPinnedCompetitorFallback) {
      const key = competitor.domain.trim().toLowerCase()
      if (!key || merged.has(key)) continue
      merged.set(key, competitor)
    }
    return [...merged.values()]
  }, [activeMeasurementPlan, competitorLandscapeGroupKey, projectPinnedCompetitorFallback, selectedCompetitorLandscapeGroup])
  const competitorLandscapePinnedFallback = activeMeasurementPlanSchemaVersion === 2
    ? advancedPinnedCompetitorFallback
    : projectPinnedCompetitorFallback
  const pinAdvancedCompetitorMutation = useMutation({
    ...postApiV1ProjectsByNameMeasurementPlanDraftActionsPinCompetitorMutation({ client: heyClient }),
    meta: { skipGlobalErrorToast: true },
  })
  const measurementSetupDisplayState = measurementSetupQuery.data !== undefined
    ? 'success' as const
    : measurementSetupQuery.isError
      ? 'error' as const
      : 'pending' as const
  const advancedMeasurementOverviewPagesInconsistent = useMemo(() => {
    const pages = advancedMeasurementOverviewQuery.data?.pages
    return pages ? !areV2OverviewPagesCompatible(pages) : false
  }, [advancedMeasurementOverviewQuery.data])
  const mergedAdvancedMeasurementOverview = useMemo(() => {
    const pages = advancedMeasurementOverviewQuery.data?.pages
    const firstPage = pages?.[0]
    const lastPage = pages?.at(-1)
    if (!firstPage || !lastPage || advancedMeasurementOverviewPagesInconsistent) return undefined
    return {
      ...firstPage,
      properties: {
        ...firstPage.properties,
        items: pages.flatMap(page => page.properties.items),
        nextCursor: lastPage.properties.nextCursor,
      },
    }
  }, [advancedMeasurementOverviewPagesInconsistent, advancedMeasurementOverviewQuery.data])
  const advancedMeasurementReport = useMemo(() => {
    if (!activeMeasurementPlan) return undefined
    if (activeMeasurementPlan.plan.schemaVersion === 1) {
      return advancedMeasurementReportQuery.data
        ? adaptVersionOneMeasurementReport(activeMeasurementPlan, advancedMeasurementReportQuery.data)
        : undefined
    }
    return mergedAdvancedMeasurementOverview
      ? adaptV2MeasurementOverview({
          overview: mergedAdvancedMeasurementOverview,
          activePlan: activeMeasurementPlan,
          sort: advancedMeasurementSort,
          report: advancedMeasurementReportQuery.data,
          reportState: mergedAdvancedMeasurementOverview.measurement.displayedRunId === undefined
            ? 'ready'
            : advancedMeasurementReportQuery.isFetching && advancedMeasurementReportQuery.data === undefined
            ? 'loading'
            : advancedMeasurementReportQuery.isError && advancedMeasurementReportQuery.data === undefined
            ? 'error'
            : advancedMeasurementReportQuery.data
              ? 'ready'
              : 'loading',
        })
      : undefined
  }, [
    activeMeasurementPlan,
    advancedMeasurementReportQuery.data,
    advancedMeasurementReportQuery.isError,
    advancedMeasurementReportQuery.isFetching,
    mergedAdvancedMeasurementOverview,
  ])
  const advancedMeasurementReportState = activeMeasurementPlanSchemaVersion === 2
    ? advancedMeasurementOverviewPagesInconsistent
      ? 'error' as const
      : advancedMeasurementOverviewQuery.isPending
      ? 'loading' as const
      : advancedMeasurementOverviewQuery.isError && advancedMeasurementReport === undefined
        ? 'error' as const
        : 'ready' as const
    : advancedMeasurementReportQuery.isPending && !hasCachedAdvancedMeasurementReport
      ? 'loading' as const
      : advancedMeasurementReportQuery.isError && !hasCachedAdvancedMeasurementReport
        ? 'error' as const
        : 'ready' as const
  const hasActiveVisibilitySweep = (model?.recentRuns ?? []).some(
    r => r.kind === RunKinds['answer-visibility'] && (r.status === RunStatuses.running || r.status === RunStatuses.queued),
  )
  // Manual launches use the project roster; schedules may select other providers.
  const runAdmission = useRunAdmission(projectName, showVisibilityChecks && !managedSweeps, 'manual').data
  const scheduledRunAdmission = useRunAdmission(projectName, showVisibilityChecks, 'scheduled').data
  const admissionScopesDiffer = runAdmission && scheduledRunAdmission
    && JSON.stringify(runAdmission) !== JSON.stringify(scheduledRunAdmission)
  const sweepsOnHold = runAdmission?.refused === true
  const sweepLeavesOut = runAdmission && !runAdmission.refused ? Object.keys(runAdmission.providers) : []
  // `queryCounts` is derived from the authoritative latest completed/partial
  // visibility-run snapshot group. `recentRuns` is only a five-row
  // presentation slice and can contain five newer failures while a valid
  // baseline still exists.
  const hasVisibilityBaseline = model.queryCounts.total > 0

  // Show every configured location as a filter chip, regardless of whether the
  // current evidence aggregate has rows for it. Multi-location sweeps can land
  // a chip-less location whenever the latest-run aggregate drops snapshots; we
  // still want the user to be able to select it (the table renders an empty
  // state if there are no matching rows).
  const configuredLocationLabels = useMemo(
    () => (model?.project.locations ?? []).map((loc: { label: string }) => loc.label),
    [model?.project.locations],
  )
  const locationLabelsInEvidence = useMemo(() => new Set(visibilityEvidence.map(e => e.location ?? '')), [visibilityEvidence])
  const hasNullLocationEvidence = locationLabelsInEvidence.has('')
  // The authoritative tracked-query set — every query the project tracks,
  // including ones added but not yet run (build-dashboard seeds a "pending"
  // evidence row for those). Sorted for a stable order in the manage panel.
  const trackedQueries = useMemo(
    () => [...new Set(visibilityEvidence.map(e => e.query))].sort((a, b) => a.localeCompare(b)),
    [visibilityEvidence],
  )
  const hasTrackedQueries = trackedQueries.length > 0 || model.queryCounts.total > 0
  const draftRequiresPublication = measurementSetupQuery.data?.requiresPublication === true
  const hasMeasurementPlanQueries = activeMeasurementPlan !== null
  const hasVisibilityInputs = hasTrackedQueries || hasMeasurementPlanQueries
  const visibilityInputsPending = canWrite
    && !hasVisibilityInputs
    && ((activeMeasurementPlanQuery.data === undefined && activeMeasurementPlanQuery.isPending)
      || (needsSimpleEvidence && evidenceDashboard.evidenceLoading))
  const providerReadinessFailed = canWrite && measurementSetupQuery.isError && !measurementSetupQuery.isFetching
  const sweepReadinessPending = canWrite
    && !providerReadinessFailed
    && (visibilityInputsPending
      || providerReady === undefined
      || measurementSetupQuery.isFetching)
  const sweepPrerequisitesReady = !sweepReadinessPending
    && !providerReadinessFailed
    && hasVisibilityInputs
    && !draftRequiresPublication
    && providerReady === true
  const sweepSetupRequired = canWrite && !sweepReadinessPending && !sweepPrerequisitesReady
  // "Check Agent Readiness" invites the operator to do something not done yet,
  // so it needs the one fact the sweep-readiness flags never carry: whether
  // this project already has an Agent Readiness audit scan.
  //
  // Scan history, not the crawl summary: a scorecard-only scan published no
  // crawl, so the crawl summary reports no scan for a project that has one and
  // the button comes back. Scan history is the list of readable scans and
  // already excludes probes.
  const mapSiteCandidate = showVisibilityChecks && !managedSweeps && sweepSetupRequired && !hasVisibilityInputs
  const siteAuditScansQuery = useQuery({
    ...getApiV1ProjectsByNameAgentReadinessRunsOptions({
      client: heyClient,
      path: { name: projectName },
      query: { limit: MAP_SITE_SCAN_HISTORY_LIMIT },
    }),
    enabled: mapSiteCandidate && Boolean(projectName),
    retry: false,
  })
  const hasReadableSiteAudit = siteAuditScansQuery.isSuccess
    && siteAuditScansQuery.data.scans.some(
      scan => scan.status === 'completed' || scan.status === 'partial',
    )
  // Absent evidence is not evidence of absence: offer the button only once the
  // read has actually come back without a scan to open.
  const showMapSite = mapSiteCandidate && siteAuditScansQuery.isSuccess && !hasReadableSiteAudit
  // `/projects/:name` opens on AI Visibility, which for a project in this state
  // is entirely empty, while the Agent Readiness score the operator just waited
  // for sits two tabs away. Point at the evidence they actually have.
  const showViewPageHealth = mapSiteCandidate && hasReadableSiteAudit
  // The collection read returns [] when no schedule exists. This keeps fresh
  // projects quiet while still discovering a scheduled-but-never-run project
  // after queries or providers are removed.
  const sweepSchedulesQuery = useQuery({
    ...getApiV1ProjectsByNameSchedulesOptions({ client: heyClient, path: { name: projectName } }),
    enabled: showVisibilityChecks && !managedSweeps && Boolean(projectName),
    retry: false,
  })
  // Only claim a next sweep when one is genuinely coming: a schedule that
  // exists, is enabled, and carries a next-run time. A disabled schedule still
  // returns a row with a stale `nextRunAt`, and announcing that would promise a
  // sweep that never fires.
  const sweepSchedule = sweepSchedulesQuery.data?.find(
    schedule => schedule.kind === RunKinds['answer-visibility'],
  )
  // Date only, in the schedule's own timezone. A timezone the formatter rejects
  // yields no label, never "null" or a time in the viewer's zone.
  const nextSweepDate = sweepSchedule?.enabled && sweepSchedule.nextRunAt
    ? managedSweepDate(sweepSchedule.nextRunAt, sweepSchedule.timezone)
    : null
  const nextSweepLabel = nextSweepDate ? `Next AI Visibility check ${nextSweepDate}` : null
  const distinctLocationsForCompare = useMemo(() => {
    // "Compare" needs ≥2 locations with selectable data. Prefer evidence-backed
    // locations, but fall back to configured locations so a fresh project that
    // hasn't aggregated evidence yet still surfaces the compare control once
    // it has multiple locations configured.
    const evidenceLabels = [...locationLabelsInEvidence].filter(Boolean)
    if (evidenceLabels.length > 1) return evidenceLabels
    return configuredLocationLabels
  }, [locationLabelsInEvidence, configuredLocationLabels])

  useEffect(() => {
    if (!needsSimpleEvidence || locationFilter === undefined || locationFilter === '' || !projectName) {
      setLocationTimeline(null)
      setLocationTimelineLoading(false)
      return
    }
    setLocationTimelineLoading(true)
    fetchTimeline(projectName, locationFilter, 20)
      .then(tl => { setLocationTimeline(tl); setLocationTimelineLoading(false) })
      .catch(() => { setLocationTimeline(null); setLocationTimelineLoading(false) })
  }, [locationFilter, projectName, needsSimpleEvidence])

  // Build a runHistory override map keyed by query::provider from the location-scoped timeline
  const locationRunHistoryMap = useMemo<Map<string, RunHistoryPoint[]> | null>(() => {
    if (!locationTimeline) return null
    const map = new Map<string, RunHistoryPoint[]>()
    for (const entry of locationTimeline) {
      for (const [provider, runs] of Object.entries(entry.providerRuns ?? {})) {
        map.set(`${entry.query}::${provider}`, runs.map(r => ({
          runId: r.runId,
          citationState: r.citationState,
          createdAt: r.createdAt,
          answerMentioned: r.answerMentioned,
          visibilityState: r.visibilityState as RunHistoryPoint['visibilityState'] | undefined,
          visibilityTransition: r.visibilityTransition,
          mentionState: r.mentionState as RunHistoryPoint['mentionState'] | undefined,
          mentionTransition: r.mentionTransition,
        })))
      }
      // Fallback: query-level history when no per-provider data
      if (!entry.providerRuns || Object.keys(entry.providerRuns).length === 0) {
        map.set(`${entry.query}::`, entry.runs.map(r => ({
          runId: r.runId,
          citationState: r.citationState,
          createdAt: r.createdAt,
          answerMentioned: r.answerMentioned,
          visibilityState: r.visibilityState as RunHistoryPoint['visibilityState'] | undefined,
          visibilityTransition: r.visibilityTransition,
          mentionState: r.mentionState as RunHistoryPoint['mentionState'] | undefined,
          mentionTransition: r.mentionTransition,
        })))
      }
    }
    return map
  }, [locationTimeline])

  const filteredEvidence = useMemo(() => {
    const filtered = locationFilter !== undefined
      ? visibilityEvidence.filter(e => locationFilter === '' ? !e.location : e.location === locationFilter)
      : visibilityEvidence
    if (!locationRunHistoryMap) return filtered
    return filtered.map(item => {
      const history = locationRunHistoryMap.get(`${item.query}::${item.provider}`)
        ?? locationRunHistoryMap.get(`${item.query}::`)
      return history ? { ...item, runHistory: history } : item
    })
  }, [visibilityEvidence, locationFilter, locationRunHistoryMap])

  // `if (!model)` branch removed — the wrapper guarantees `model` is set
  // by the time we render `ProjectPageContent`. The wrapper also owns the
  // "project not found" state (when both context and /projects list have
  // resolved but neither matched the URL's identifier).

  async function handleTriggerRun() {
    if (runPreview.isError || runPreview.isFetching || runPreview.data?.canStart !== true || sweepConfirmationProject !== projectName || !canWrite || !showVisibilityChecks || managedSweeps || triggerRunMutation.isPending || hasActiveVisibilitySweep || sweepsOnHold || !sweepPrerequisitesReady) return
    try {
      await triggerRunMutation.mutateAsync({
        projectName,
        projectLabel,
        sourceAction: 'project-run',
      })
      setSweepConfirmationProject(null)
    } catch {
      // Mutation hook surfaces the toast and error state.
    }
  }

  function openAiVisibilitySetup() {
    if (draftRequiresPublication) {
      void navigate({ to: '/projects/$projectName/portfolio', params: { projectName } })
      return
    }
    void navigate({
      to: '/setup',
      search: {
        project: projectName,
        track: 'ai-visibility',
      },
    })
  }

  function openSiteHealth() {
    void navigate({
      to: '/projects/$projectName/agent-readiness',
      params: { projectName },
    })
  }

  async function handleDeleteProject() {
    setDeleting(true)
    try {
      await apiDeleteProject(projectName)
      addToast({
        title: 'Project deleted',
        detail: `${projectLabel} was removed.`,
        tone: 'positive',
        dedupeKey: `project:delete:${projectName}`,
        dedupeMode: 'drop',
      })
      await navigate({ to: '/' })
    } catch (err) {
      console.error('Failed to delete project:', err)
    } finally {
      setDeleting(false)
    }
  }

  async function handleAddQueries() {
    const queries = newQueryText.split('\n').map(k => k.trim()).filter(Boolean)
    if (queries.length === 0) return
    setQuerySaving(true)
    try {
      await apiAppendQueries(projectName, queries)
      setNewQueryText('')
    } finally {
      setQuerySaving(false)
    }
  }

  async function handleRemoveQuery(query: string) {
    setRemovingQuery(query)
    try {
      await apiRemoveQueries(projectName, [query])
    } catch (err) {
      addToast({
        title: 'Could not remove query',
        detail: err instanceof Error ? err.message : `Failed to remove "${query}"`,
        tone: 'negative',
        dedupeKey: 'query:remove',
        dedupeMode: 'replace',
      })
    } finally {
      setRemovingQuery(null)
    }
  }

  async function handleAddCompetitor(domainInput: string) {
    const domain = domainInput.trim()
    if (!domain) return false
    try {
      await apiAppendCompetitors(projectName, [domain])
      return true
    } catch (err) {
      let failure: unknown = err
      const details = apiErrorDetails(err)
      if (details?.reason === COMPETITOR_BULK_ADD_REFUSAL_REASON) {
        const trackedBefore = typeof details.trackedBefore === 'number' ? details.trackedBefore : '?'
        const trackedAfter = typeof details.trackedAfter === 'number' ? details.trackedAfter : '?'
        const windowHours = typeof details.windowHours === 'number' ? details.windowHours : COMPETITOR_BULK_ADD_WINDOW_HOURS
        const accepted = window.confirm(`This add would grow tracked competitors from ${trackedBefore} to ${trackedAfter} within ${windowHours} hours. Continue?`)
        if (accepted) {
          try {
            await apiAppendCompetitors(projectName, [domain], { acknowledgeBulkAdd: true })
            return true
          } catch (retryError) {
            failure = retryError
          }
        }
      }
      addToast({
        title: 'Could not add competitor',
        detail: failure instanceof Error ? failure.message : `Failed to add ${domain}`,
        tone: 'negative',
        dedupeKey: 'competitor:add',
        dedupeMode: 'replace',
      })
      return false
    }
  }

  async function handleRemoveCompetitor(domain: string) {
    const competitor = model.competitors.find(c => c.domain === domain)
    if (!competitor) {
      addToast({
        title: 'Could not remove competitor',
        detail: `Could not find ${domain} in the tracked competitor list`,
        tone: 'negative',
        dedupeKey: 'competitor:remove',
        dedupeMode: 'replace',
      })
      return false
    }

    try {
      await apiRemoveCompetitorById(projectName, competitor.id)
      return true
    } catch (err) {
      addToast({
        title: 'Could not remove competitor',
        detail: err instanceof Error ? err.message : `Failed to remove ${competitor.domain}`,
        tone: 'negative',
        dedupeKey: 'competitor:remove',
        dedupeMode: 'replace',
      })
      return false
    }
  }

  async function handlePinAdvancedCompetitor(domainInput: string) {
    const domain = domainInput.trim()
    if (
      !domain
      || !competitorLandscapeGroupKey
      || activeMeasurementPlanSchemaVersion !== 2
      || !canWrite
      || isEmbed()
      || pinAdvancedCompetitorMutation.isPending
    ) return false

    try {
      const result = await pinAdvancedCompetitorMutation.mutateAsync({
        client: heyClient,
        path: { name: projectName },
        headers: { 'Idempotency-Key': competitorDraftIdempotencyKey() },
        body: {
          expectedActiveRevision: activeMeasurementRevision,
          groupKey: competitorLandscapeGroupKey,
          domain,
        },
      })
      // The active revision is deliberately frozen. The stored-evidence read
      // exposes the pending draft pin straight away, and Setup picks up the
      // draft state for the explicit publish step.
      void Promise.allSettled([
        measurementSetupQuery.refetch(),
      ])
      addToast({
        title: result.draftCreated ? 'Competitor added to a market draft' : 'Market competitor updated',
        detail: `Publish the Advanced Measurement draft before ${domain} is used in future market runs.`,
        tone: 'positive',
        dedupeKey: `competitor:market-pin:${competitorLandscapeGroupKey}:${domain}`,
        dedupeMode: 'replace',
      })
      return true
    } catch (err) {
      addToast({
        title: 'Could not add market competitor',
        detail: err instanceof Error ? err.message : `Failed to add ${domain} to the market draft.`,
        tone: 'negative',
        dedupeKey: 'competitor:market-pin:error',
        dedupeMode: 'replace',
      })
      return false
    }
  }

  async function handleUpdateProject(pName: string, updates: { displayName?: string; canonicalDomain?: string; ownedDomains?: string[]; aliases?: string[]; country?: string; language?: string; locations?: Array<{ label: string; city: string; region: string; country: string; timezone?: string }>; defaultLocation?: string | null; providers?: string[]; providerModels?: Record<string, string>; siteAuditMaxPages?: number | null; siteAuditDomains?: string[] }) {
    const updated = await apiUpdateProject(pName, updates)
    queryClient.setQueryData(getApiV1ProjectsByNameQueryKey({ client: heyClient, path: { name: pName } }), updated)
    // Scoped to the edited project's own cache entries — see the helper.
    patchProjectDashboardCache(queryClient, updated)
    return updated
  }

  // Quiet underline tabs in `projectSectionTabs` order. The bar keeps the
  // sections an operator returns to; everything else is in More, and an open
  // More section shows as a tab before it, so the bar always names the current
  // page. Narrow widths can move primary sections into More, never the open
  // one. Operators reach Settings from the sidebar; only embeds get a Settings
  // tab, at the far right.
  const projectTabBase = `/projects/${encodeURIComponent(model.project.name)}`
  const sectionTabs = projectSectionTabs(projectTabBase, { journeys: account?.role !== UserRoles.viewer })
  // In embed mode the effective allowlist narrows the subnav to the curated
  // client-facing tabs. Settings also requires write access outside embed/demo.
  const projectTabItems = [
    ...sectionTabs.primary.filter((item) => isEmbedProjectTabAllowed(item.key, embedProjectTabs)),
    ...(queryLimit !== undefined ? [{ key: 'client-queries' as const, label: 'Queries', href: `${projectTabBase}/client-queries` }] : []),
  ]
  const projectOverflowTabItems = sectionTabs.overflow.filter((item) =>
    isEmbedProjectTabAllowed(item.key, embedProjectTabs),
  )
  const canViewProjectSettings = canWrite || isEmbed() || isPublicDemo()
  const projectSettingsTab = canViewProjectSettings && isEmbedProjectTabAllowed('settings', embedProjectTabs)
    ? { key: 'settings' as const, label: 'Settings', href: `${projectTabBase}/settings` }
    : null

  function renderVisibilityOverview(overview: React.ReactNode) {
    // Simple keeps its own layout even when a unified report is available.
    // Advanced retains the report workspace and its existing legacy fallback.
    // The overview keys its results by the selection and keeps its toolbar mounted.
    const content = isSimpleOverview ? overview : (
      <VisibilityOverview
        projectName={projectName}
        selection={visibilitySelection}
        showUnmeasuredFallback={!activeMeasurementPlan && !hasVisibilityBaseline
          && visibilitySelection.measurementScope === 'project'
          && visibilitySelection.queryClass === 'all'
          && !visibilitySelection.provider && !visibilitySelection.model && !visibilitySelection.location
          && !visibilitySelection.from && !visibilitySelection.to && !visibilitySelection.revision
          && !visibilitySelection.measurementRunId && !visibilitySelection.queryKey && !visibilitySelection.marketKey}
        onSelectionChange={updateVisibilitySearch}
        onManageQueries={!isEmbed() ? () => { void navigate({ to: '/projects/$projectName/queries', params: { projectName }, search: previous => ({ ...previous, queryWorkspace: 'tracked', trackingQueryId: undefined, measurementMarketKey: undefined }) }) } : undefined}
        renderPropertyLink={!isEmbed() ? ({ id, label }) => (
          <Link to="/projects/$projectName/properties/$targetKey" params={{ projectName, targetKey: id }} search={carryVisibilitySearch} aria-label={`Property details for ${label}`} className="inline-flex min-h-11 items-center text-label-14 text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400">
            Property details
          </Link>
        ) : undefined}
        // Embeds and managed dashboards name neither date. A sweep already under way brings
        // new numbers before the scheduled one, so it names no date either.
        trackingChangedAt={isEmbed() || managedSweeps ? undefined : activeMeasurementPlan?.createdAt}
        nextSweepDate={isEmbed() || managedSweeps || hasActiveVisibilitySweep ? undefined : nextSweepDate ?? undefined}
        fallback={overview}
      />
    )
    if (isEmbed()) return content
    let sentimentSelection = sentimentSelectionFromVisibility(visibilitySelection, isSimpleOverview ? 'simple' : 'advanced', typeof projectSearchParams.sentimentEvaluationDefinitionId === 'string' ? projectSearchParams.sentimentEvaluationDefinitionId : undefined)
    if (isSimpleOverview) {
      sentimentSelection.location = locationFilter === '' ? 'none' : locationFilter
      sentimentSelection = sentimentSelectionForSimpleEvidence(sentimentSelection, filteredEvidence, evidenceProvider)
    }
    return <SentimentScopeProvider hasSourceEvidence={!isSimpleOverview || Boolean(sentimentSelection.runId || sentimentSelection.runIds?.length)} evidenceReady={!isSimpleOverview || !(evidenceDashboard.isLoading || evidenceDashboard.evidenceLoading || evidenceDashboard.evidenceError)} waitForResolvedRun={!isSimpleOverview} projectName={projectName} runOptions={model.visibilitySweeps.slice(0, SENTIMENT_BACKFILL_SWEEP_OPTIONS).map(run => ({ id: run.id, label: formatTimestamp(run.finishedAt ?? run.createdAt) }))} selection={sentimentSelection}>{content}</SentimentScopeProvider>
  }

  // The context row's measurement scope slot. Each tab owns recovery for a
  // saved scope that no longer exists; the row only names it.
  function renderScopeSlot(): React.ReactNode {
    switch (scopeSlot.kind) {
      case 'report-picker': {
        if (reportScopeQuery.error) {
          // Any other failure belongs to the workspace alert below.
          return parseVisibilityReportScopeErrorDetails(apiErrorDetails(reportScopeQuery.error))
            ? <p className="text-copy-13 text-secondary">{PROJECT_SCOPE_COPY.savedScopeUnavailable}</p>
            : null
        }
        const report = reportScopeQuery.data
        if (!report) return <div className="skeleton-text h-11 w-56" role="status" aria-label="Loading measurement scope" />
        if (report.selection.availability.state !== 'available' || report.scopeOptions.length <= 1) return null
        // The URL owns the choice, so the trigger never snaps back while the
        // next report loads over the previous one.
        const selected = selectedScopeOption(report.scopeOptions, visibilitySelection) ?? report.selection.scope
        return (
          <VisibilityScopePicker
            labelVisibility="sr-only"
            options={report.scopeOptions}
            selected={selected}
            marketKey={visibilitySelection.marketKey}
            onSelect={(scope, marketKey) => updateVisibilitySearch({ measurementScope: scope.kind, measurementScopeKey: scope.kind === 'project' ? undefined : scope.id, measurementMarketKey: marketKey })}
          />
        )
      }
      case 'tracking-picker': {
        const options = trackingWorkspaceQuery.data?.scopeOptions ?? []
        const selected = selectedScopeOption(options, visibilitySelection)
        // Tracked assignments have no market intersection, so a new scope drops the market.
        return selected ? (
          <VisibilityScopePicker
            labelVisibility="sr-only"
            options={options}
            selected={selected}
            onSelect={scope => updateVisibilitySearch({ measurementScope: scope.kind, measurementScopeKey: scope.kind === 'project' ? undefined : scope.id })}
          />
        ) : null
      }
      case 'scope-unavailable':
        return <p className="text-copy-13 text-secondary">{PROJECT_SCOPE_COPY.savedScopeUnavailable}</p>
      case 'project-wide':
        return (
          <span className="flex items-center gap-1">
            <span className="text-label-13 text-secondary">{PROJECT_SCOPE_COPY.projectWide}</span>
            <InfoTooltip text={PROJECT_SCOPE_COPY.projectWideHelp} />
          </span>
        )
      case 'none':
        return null
    }
  }

  // Overview's date range: only an Advanced portfolio's explicit historical
  // range, shown in the embed header. Simple shows no range label: its cards
  // read different windows (latest sweep, the chart's own window), so no one
  // label is true of the page. An Advanced range is a filter token in the
  // operator's results toolbar.
  const overviewRangeLabel = tab === 'overview' && !isSimpleOverview && (visibilitySelection.from || visibilitySelection.to)
    ? `${visibilitySelection.from?.slice(0, 10) ?? 'First measurement'} to ${visibilitySelection.to?.slice(0, 10) ?? 'Latest measurement'}`
    : null
  const scopeSlotContent = renderScopeSlot()
  const competitorLandscapeCard = competitorLandscapeAvailable ? (
    <CompetitorLandscape
      window={competitorLandscapeWindow}
      landscape={competitorLandscapeQuery.data}
      pinnedFallback={competitorLandscapePinnedFallback}
      competitorAliases={competitorAliases}
      competitorAutoAliases={competitorAutoAliases}
      canWrite={canWrite}
      isEmbed={isEmbed()}
      onWindowChange={setCompetitorLandscapeWindow}
      // A group write is an additive, revision-guarded draft action.
      // All-markets has no single safe market target, so it stays
      // read-only even for an operator.
      onPin={competitorLandscapeGroupKey && canWrite && !isEmbed()
        ? handlePinAdvancedCompetitor
        : !isAdvancedAllMarkets && canWrite && !isEmbed()
          ? handleAddCompetitor
          : undefined}
      onUnpin={competitorLandscapeGroupKey || isAdvancedAllMarkets || !canWrite || isEmbed()
        ? undefined
        : handleRemoveCompetitor}
      onAddCompetitor={competitorLandscapeGroupKey && canWrite && !isEmbed()
        ? handlePinAdvancedCompetitor
        : !isAdvancedAllMarkets && canWrite && !isEmbed()
          ? handleAddCompetitor
          : undefined}
      error={competitorLandscapeError}
      onRetry={competitorLandscapeReadEnabled ? () => { void competitorLandscapeQuery.refetch() } : undefined}
      isLoading={competitorLandscapeReadEnabled && competitorLandscapeQuery.isPending && competitorLandscapeQuery.data === undefined}
      scopeLabel={competitorLandscapeGroupKey
        ? `${selectedCompetitorLandscapeGroup?.label ?? competitorLandscapeGroupKey} group`
        : isAdvancedAllMarkets ? 'All markets' : 'Project-wide'}
      advancedPortfolio={!isSimpleOverview}
    />
  ) : null

  // Query evidence's actions sit in a row above the Sentiment block (Manage
  // sentiment lives in that block's title row), and the query editor they open
  // sits directly under the block. Embeds are read-only.
  const evidenceActions = isEmbed() ? null : (
    <>
      <WriteButton type="button" variant="outline" size="sm" onClick={() => setManagingQueries(!managingQueries)}>
        {managingQueries ? 'Done' : 'Manage queries'}
      </WriteButton>
    </>
  )
  const evidenceQueryEditor = !isEmbed() && managingQueries ? (
    <div className="mb-3 material-base p-3">
      {trackedQueries.length > 0 ? (
        <ul className="mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto">
          {trackedQueries.map((q) => (
            <li key={q} className="flex items-center justify-between gap-3 px-3 py-2">
              <span className="min-w-0 truncate text-label-14 text-strong" title={q}>{q}</span>
              <button
                type="button"
                className="shrink-0 rounded px-1.5 py-0.5 text-button-14 text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50"
                aria-label={`Remove query ${q}`}
                title={`Stop tracking "${q}"`}
                disabled={removingQuery !== null}
                onClick={() => { void handleRemoveQuery(q) }}
              >
                {removingQuery === q ? 'Removing…' : 'Remove'}
              </button>
            </li>
          ))}
        </ul>
      ) : (
        <p className="mb-3 text-copy-13 text-muted">No queries tracked yet. Add some below.</p>
      )}
      <textarea
        className="w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-copy-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none"
        rows={3}
        placeholder="Enter queries to add, one per line"
        value={newQueryText}
        onChange={(e) => setNewQueryText(e.target.value)}
      />
      <div className="mt-2 flex items-center justify-between">
        <p className="text-copy-13 text-muted">{newQueryText.split('\n').filter(k => k.trim()).length} to add</p>
        <WriteButton type="button" size="sm" disabled={!newQueryText.trim() || querySaving} onClick={asyncHandler(handleAddQueries)}>
          {querySaving ? 'Adding...' : 'Add queries'}
        </WriteButton>
      </div>
    </div>
  ) : null

  return (
    <div className="page-container">
      {isEmbed() ? (
        // Embeds have no topbar, so they keep the in-page header: identity and
        // context only, never an action.
        <div className="page-header">
          <div className="page-header-left">
            <h1 className="page-title">{model.project.displayName || model.project.name}</h1>
            <p className="page-subtitle">
              {model.project.canonicalDomain} · {model.contextLabel}
            </p>
          </div>
          <div className={managedSweeps ? 'page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end' : 'page-header-right'}>
            {overviewRangeLabel !== null ? <p className="text-copy-14 text-muted">{overviewRangeLabel}</p> : null}
          </div>
        </div>
      ) : (
        // The topbar breadcrumb names the project. The row keeps the page's one
        // h1 for assistive tech and narrow screens.
        <div className="project-context-row">
          <h1 className="project-context-title md:sr-only">{model.project.displayName || model.project.name}</h1>
          {scopeSlotContent !== null ? <div className="project-context-scope">{scopeSlotContent}</div> : null}
          {model.project.canonicalDomain ? <span className="project-context-domain">{model.project.canonicalDomain}</span> : null}
          {advancedProjectTag !== null ? (
            <span className="project-mode-tag">
              <span className="project-mode-tag-label">Advanced</span>
              <span className="project-mode-tag-detail">{advancedProjectTag}</span>
            </span>
          ) : null}
          {showMapSite || showViewPageHealth ? (
            <div className="project-context-actions" data-project-actions>
              <WriteButton type="button" onClick={openSiteHealth}>
                {showMapSite ? 'Check Agent Readiness' : 'View Agent Readiness score'}
              </WriteButton>
            </div>
          ) : null}
        </div>
      )}

      <ProjectSubnav
        items={projectTabItems}
        overflowItems={projectOverflowTabItems}
        settingsItem={isEmbed() ? projectSettingsTab : null}
        activeTab={tab}
      />

      {tab === 'portfolio' && !isEmbed() ? (
        <AdvancedMeasurementSection
          key={projectName}
          projectName={projectName}
          projectDomain={model.project.canonicalDomain}
          canEdit={canWrite}
          queries={portfolioQueriesQuery.data ?? []}
          isQueryLoading={isPortfolioQueriesLoading}
          isQueryError={isPortfolioQueriesError}
          onRetryQueries={() => { void portfolioQueriesQuery.refetch() }}
          publishedPlan={activeMeasurementPlan}
          sweepActive={hasActiveVisibilitySweep}
          executionProviders={model.project.providers}
          executionProviderModels={model.project.providerModels}
          onCreateQueries={async texts => {
            // The shared mutation carries the write guard and invalidates both
            // the projects list and the per-project detail. Calling the raw
            // client skipped all of that, so other surfaces kept showing the
            // old basket.
            await appendQueries.mutateAsync({ projectName, queries: [...texts] })
            // The step selects from this list, so it has to reflect the new
            // queries before the operator can apply them. A refetch failure
            // must not read as success, hence throwOnError.
            const refreshed = await portfolioQueriesQuery.refetch({ throwOnError: true })
            // The caller pairs each query back to the Property it was written
            // for, and can only do that once the ids exist.
            return refreshed.data ?? []
          }}
          onManageProjectQueries={() => {
            // Local state does not survive this navigation: it remounts the page
            // and resets, which left the operator on Overview with the manager
            // shut. The URL carries the intent instead.
            void navigate({
              to: '/projects/$projectName',
              params: { projectName },
              search: { manageQueries: true },
            })
          }}
          onPublished={() => {
            void Promise.all([
              measurementSetupQuery.refetch(),
              activeMeasurementPlanQuery.refetch(),
            ]).finally(() => {
              void navigate({ to: '/projects/$projectName', params: { projectName } })
            })
          }}
        />
      ) : tab === 'overview' ? (
        <>
        {showVisibilityChecks ? (
          <div role="group" aria-label="AI Visibility checks" className="visibility-checks">
            {managedSweeps ? <ManagedSweepStatus projectName={projectName} running={hasActiveVisibilitySweep} /> : (
              <>
                {nextSweepLabel ? <p className="text-copy-14 text-secondary">{nextSweepLabel}</p> : null}
                <WriteButton
                  type="button"
                  variant="outline"
                  disabled={triggerRunMutation.isPending || hasActiveVisibilitySweep || sweepReadinessPending || (sweepsOnHold && !providerReadinessFailed && !sweepSetupRequired)}
                  onClick={providerReadinessFailed
                    ? () => { void measurementSetupQuery.refetch() }
                    : sweepSetupRequired
                      ? openAiVisibilitySetup
                      : event => { sweepOpener.current = event.currentTarget; setSweepConfirmationProject(projectName) }}
                >
                  {triggerRunMutation.isPending
                    ? 'Starting…'
                    : hasActiveVisibilitySweep
                      ? 'AI Visibility check running…'
                      : sweepReadinessPending
                        ? 'Checking AI engines…'
                        : providerReadinessFailed
                          ? 'Retry engine check'
                          : sweepSetupRequired
                            ? draftRequiresPublication ? 'Review and publish plan' : 'Set up AI Visibility'
                            : sweepsOnHold
                              ? 'AI Visibility checks on hold'
                              : 'Run AI Visibility check'}
                </WriteButton>
                <ProjectSweepConfirmation
                  open={sweepConfirmationProject === projectName}
                  projectLabel={projectLabel}
                  onOpenChange={open => setSweepConfirmationProject(open ? projectName : null)}
                  onConfirm={asyncHandler(handleTriggerRun)}
                  onClosed={() => sweepOpener.current?.focus()}
                  disabled={triggerRunMutation.isPending || hasActiveVisibilitySweep || sweepsOnHold || !sweepPrerequisitesReady}
                  leftOut={sweepLeavesOut}
                  preview={runPreview.data}
                  previewPending={runPreview.isFetching}
                  previewFailed={runPreview.isError}
                  onRetryPreview={() => { void runPreview.refetch() }}
                />
              </>
            )}
          </div>
        ) : null}
        {/* Above both overviews and their loading state: a refused or partial sweep is the project's state, whichever portfolio it is. */}
        {showVisibilityChecks ? <>
          {scheduledRunAdmission ? <RunAdmissionNoticeView admission={scheduledRunAdmission} canFix={canWrite && isAdmin} selection={admissionScopesDiffer || !runAdmission ? 'scheduled' : undefined} /> : null}
          {runAdmission && (admissionScopesDiffer || !scheduledRunAdmission) ? <RunAdmissionNoticeView admission={runAdmission} canFix={canWrite && isAdmin} selection="manual" /> : null}
        </> : null}
        {isMeasurementModeUnresolved || (isSimpleOverview && !hasInitialProjectDashboard && (!overviewRequested || overviewLoading)) ? (
          <div role="status" aria-live="polite">
            <span className="sr-only">Loading project overview</span>
            <div className="h-32 animate-pulse rounded-md bg-surface-subtle" aria-hidden="true" />
          </div>
        ) : isSimpleOverview && overviewError ? (
          <div role="alert" className="page-section-divider">
            <p>Could not load AI visibility.</p>
            <Button type="button" variant="outline" onClick={() => { void refetch() }}>Retry</Button>
          </div>
        ) : (
        <>
          {isActiveMeasurementPlanError ? (
            <div role="alert" className="mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative">
              <span>Could not check the advanced measurement setup. Existing project-wide results remain available.</span>
              <Button type="button" size="sm" variant="outline" onClick={() => { void activeMeasurementPlanQuery.refetch() }}>
                Retry setup check
              </Button>
            </div>
          ) : null}
          {renderVisibilityOverview(<AdvancedMeasurementLanding
            key={`${projectName}:${activeMeasurementRevision}`}
            mode={advancedMeasurementMode}
            canEdit={canWrite && !isEmbed() && !isActiveMeasurementPlanLoading && !isActiveMeasurementPlanError}
            simpleOverview={(
              <>
          <section className="mb-6">
            <VisibilityTrendSection
              projectName={model.project.name}
              competitorDomains={competitorDomains}
              competitorAliases={competitorIdentityNames}
              analyticsRevision={latestVisibilityRevision}
              queryTexts={trackedQueryTexts}
              classifyQuery={classifyQuery}
              sweepTimes={recentSweepTimes}
              queryClassSplit={trendQueryClassSplit}
            />
          </section>

          {hasVisibilityBaseline && <><section className="mb-6"><details className="av-history" open={competitorDomains.length > 0}>
            {/* The summary is the toggle, so it takes its name from the heading
                alone; the check it reads is its description. */}
            <summary className="av-card-head" aria-labelledby={competitiveTitleId} aria-describedby={competitiveMetaId}>
              <h2 id={competitiveTitleId} className="av-card-title">{competitorDomains.length > 0 ? 'Where competitors are winning' : 'Compare competitors'}</h2>
              <span className="inline-flex items-center gap-2">
                <span id={competitiveMetaId} className="av-card-meta">Latest check</span>
                <ChevronDown className="overview-disclosure-icon" size={16} aria-hidden="true" />
              </span>
            </summary>

            <div className="competitive-summary">
                <MentionShare
                  key={model.project.name}
                  summary={model.mentionShareSummary}
                  projectLabel={model.project.displayName || model.project.name}
                  competitorDomains={competitorDomains}
                />

                {competitorDomains.length > 0 ? (
                  <div className="competitive-gaps">
                    <p className="competitive-gaps-scope">All queries</p>
                    <div className="aeo-hero-rows">
                      <OverviewMetricRow
                        label="Mention gaps"
                        summary={model.mentionGaps}
                        displayValue={<><span className="text-primary">{model.mentionGaps.value}</span><span className="text-secondary"> / {model.queryCounts.total}</span><span className="sr-only"> queries, all queries</span></>}
                        tooltip="Across all queries, branded and non-brand: a competitor was mentioned in an answer and your brand was not mentioned by any engine. The mention-share query type does not filter these counts."
                      />
                      <OverviewMetricRow
                        label="Citation gaps"
                        summary={model.gapQueries}
                        displayValue={citationGapBase(model.queryCounts) === 0
                          // No answer carries sources, so there is no base to count gaps out of.
                          ? <><span className="whitespace-nowrap text-label-13 text-secondary">{CITATION_NOT_MEASURED.label}</span><span className="sr-only">, all queries</span></>
                          : <><span className="text-primary">{model.gapQueries.value}</span><span className="text-secondary"> / {citationGapBase(model.queryCounts)}</span><span className="sr-only"> queries, all queries</span></>}
                        tooltip="Across all queries, branded and non-brand: a competitor was cited as a source and your domain was not cited by any engine. The mention-share query type does not filter these counts."
                      />
                    </div>
                  </div>
                ) : (
                  // A gap counts only tracked competitors, so with none tracked
                  // both counts are zero whatever the answers said. Zeros with
                  // bars would read as winning; say what is missing instead.
                  <div className="competitive-gaps">
                    <p className="text-label-14-strong text-strong">{COMPETITOR_COMPARISON_COPY.emptyTitle}</p>
                    <p className="mt-1 text-copy-14 text-secondary">{COMPETITOR_COMPARISON_COPY.emptyDetail}</p>
                    {competitorLandscapeAvailable && canWrite && !isEmbed() ? (
                      <Button type="button" variant="outline" size="sm" className="mt-3" onClick={() => {
                        setCompetitorHistoryOpenForProject(projectName)
                        setCompetitorHistoryFocusPending(true)
                      }}>
                        {COMPETITOR_COMPARISON_COPY.add}
                      </Button>
                    ) : null}
                  </div>
                )}
              </div>
          </details></section>

          <div className="mb-6">
            <CitationVisibilitySection projectName={model.project.name} revision={latestVisibilityRevision} />
          </div>
</>}
          <OverviewDisclosure
            id="evidence-section"
            title="Query evidence"
            meta={`${model.queryCounts.total} measured ${model.queryCounts.total === 1 ? 'query' : 'queries'}`}
            defaultOpen
          >
            {model.project.locations.length > 0 && (
              <div className="filter-row mb-3" role="toolbar" aria-label="Location filters">
                <button
                  className={`filter-chip ${locationFilter === undefined ? 'filter-chip-active' : ''}`}
                  type="button"
                  aria-pressed={locationFilter === undefined}
                  onClick={() => { setLocationFilter(undefined) }}
                >
                  All locations
                </button>
                {model.project.locations.map((loc: { label: string }) => (
                  <button
                    key={loc.label}
                    className={`filter-chip ${locationFilter === loc.label ? 'filter-chip-active' : ''}`}
                    type="button"
                    aria-pressed={locationFilter === loc.label}
                    onClick={() => { setLocationFilter(loc.label); setCompareLocations(false) }}
                  >
                    {loc.label}
                  </button>
                ))}
                {hasNullLocationEvidence && (
                  <button
                    className={`filter-chip ${locationFilter === '' ? 'filter-chip-active' : ''}`}
                    type="button"
                    aria-pressed={locationFilter === ''}
                    onClick={() => { setLocationFilter(''); setCompareLocations(false) }}
                  >
                    No location
                  </button>
                )}
                {distinctLocationsForCompare.length > 1 && locationFilter === undefined && (
                  <button
                    className={`filter-chip filter-chip-compare ${compareLocations ? 'filter-chip-active' : ''}`}
                    type="button"
                    aria-pressed={compareLocations}
                    onClick={() => setCompareLocations(v => !v)}
                    title="Side-by-side location comparison"
                  >
                    Compare
                  </button>
                )}
              </div>
            )}
            {evidenceDashboard.evidenceLoading || evidenceDashboard.evidenceError ? (
              <>
                {evidenceActions && <QueryEvidenceSummary actions={evidenceActions} />}
                {evidenceQueryEditor}
                {evidenceDashboard.evidenceLoading ? (
                  <p role="status" className="text-copy-14 text-secondary">Loading query evidence…</p>
                ) : (
                  <div role="alert" className="text-label-14 text-secondary">
                    <p>Could not load query evidence.</p>
                    <Button type="button" variant="outline" onClick={() => { void evidenceDashboard.refetch() }}>Retry</Button>
                  </div>
                )}
              </>
            ) : (
              <EvidenceTable evidence={filteredEvidence} compareLocations={compareLocations} providerSelection={evidenceProvider} onProviderSelectionChange={setEvidenceProvider} addedQueries={model.movementComparison.addedQueries} actions={evidenceActions} actionPanel={evidenceQueryEditor} />
            )}
          </OverviewDisclosure>

          {!isEmbed() && (
            <div className="page-section-divider">
              <PastSweeps runs={model.recentRuns} projectName={model.project.name} collapsed />
            </div>
          )}

              </>
            )}
            report={advancedMeasurementReport}
            reportState={advancedMeasurementReportState}
            onOpenSetup={!isEmbed() ? () => {
              void navigate({ to: '/projects/$projectName/portfolio', params: { projectName } })
            } : undefined}
            onRetryReport={() => {
              if (activeMeasurementPlanSchemaVersion === 2) {
                void Promise.all([advancedMeasurementOverviewQuery.refetch(), advancedMeasurementReportQuery.refetch()])
              }
              else void advancedMeasurementReportQuery.refetch()
            }}
            onViewChange={(view) => {
              setAdvancedMeasurementView({
                scope: view.scope,
                ...(view.groupKey ? { groupKey: view.groupKey } : {}),
                queryClass: view.queryClass,
                ...(view.search?.trim() ? { search: view.search.trim() } : {}),
              })
            }}
            onLoadMore={(cursor) => {
              if (cursor === mergedAdvancedMeasurementOverview?.properties.nextCursor) {
                void advancedMeasurementOverviewQuery.fetchNextPage()
              }
            }}
            onPropertyExpand={() => {
              if (hasExpandedAdvancedProperty && advancedMeasurementReportQuery.isError) {
                void advancedMeasurementReportQuery.refetch()
              }
              setHasExpandedAdvancedProperty(true)
            }}
            onRetryEvidence={() => { void advancedMeasurementReportQuery.refetch() }}
            isViewLoading={advancedMeasurementOverviewQuery.isPlaceholderData}
            isLoadingMore={advancedMeasurementOverviewQuery.isFetchingNextPage}
            isLoadMoreError={advancedMeasurementOverviewQuery.isFetchNextPageError}
            viewSearch={advancedMeasurementView.search ?? ''}
          />)}
          {!isSimpleOverview && visibilitySelection.measurementScope === 'project' ? <details key={projectName} className="visibility-disclosure" onToggle={event => {
            if (event.currentTarget.open) onRequestOverview()
          }}>
            <summary className="visibility-disclosure-summary"><span className="visibility-disclosure-label">Project signals</span></summary>
            {!overviewRequested || overviewLoading ? (
              <p role="status" className="text-copy-14 text-secondary">Loading project signals…</p>
            ) : overviewError ? (
              <div role="alert" className="text-label-14 text-secondary">
                <p>Could not load project signals.</p>
                <Button type="button" variant="outline" onClick={() => { void refetch() }}>Retry</Button>
              </div>
            ) : (
              <OverviewSignals
                insights={model.insights}
                suggestedQueries={model.suggestedQueries}
                siteDomain={model.project.canonicalDomain || undefined}
                onManageQueries={!isEmbed() ? () => { void navigate({ to: '/projects/$projectName/queries', params: { projectName }, search: previous => ({ ...previous, queryWorkspace: 'tracked', trackingQueryId: undefined }) }) } : undefined}
              />
            )}
          </details> : null}
          {competitorLandscapeCard !== null ? (
            <details ref={competitorHistoryRef} className={`visibility-disclosure${isSimpleOverview ? ' page-section-divider' : ''}`} open={competitorHistoryOpen} onToggle={event => setCompetitorHistoryOpenForProject(event.currentTarget.open ? projectName : null)}>
              <summary className="visibility-disclosure-summary"><span className="visibility-disclosure-label">Competitor history</span></summary>
              <div className="visibility-disclosure-panel">{competitorLandscapeCard}</div>
            </details>
          ) : null}
        </>
        )}
        </>
      ) : tab === 'settings' ? !canViewProjectSettings ? (
        <Card className="surface-card empty-card">
          <h2>Project settings unavailable</h2>
          <p>Your account has view-only access to this project.</p>
          <Button asChild>
            <Link to="/projects/$projectName" params={{ projectName }}>Return to overview</Link>
          </Button>
        </Card>
      ) : (
        <>
          <ProjectSettingsSection project={{ ...model.project, displayName: model.project.displayName ?? model.project.name, defaultLocation: model.project.defaultLocation ?? null }} onUpdateProject={async (name, updates) => { await handleUpdateProject(name, updates) }} />
          <ProjectEngineSettingsSection project={model.project} onSave={async next => { await handleUpdateProject(model.project.name, next) }} />
          <SiteHealthScanSettingsSection key={model.project.id} project={model.project} onSave={async settings => { await handleUpdateProject(model.project.name, settings) }} />
          {canWrite && !isEmbed() ? (
            <section className="page-section-divider">
              <h2 className="text-heading-20 text-heading">Advanced measurement</h2>
              <p className="supporting-copy mt-1 mb-3">
                Measure individual properties, locations, or site sections with separate query sets.
              </p>
              {measurementSetupDisplayState === 'pending' ? (
                <p role="status" className="text-copy-14 text-secondary">Loading setup…</p>
              ) : measurementSetupDisplayState === 'error' ? (
                <div role="alert" className="flex flex-wrap items-center gap-3 text-label-14 text-negative">
                  <span>Could not load advanced measurement setup.</span>
                  <Button type="button" size="sm" variant="outline" onClick={() => { void measurementSetupQuery.refetch() }}>
                    Retry
                  </Button>
                </div>
              ) : (
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => { void navigate({ to: '/projects/$projectName/portfolio', params: { projectName } }) }}
                >
                  {advancedMeasurementSetupActionLabel(advancedMeasurementMode.setupAction)}
                </Button>
              )}
            </section>
          ) : null}
          <ScheduleSection projectName={model.project.name} />
          <NotificationsSection projectName={model.project.name} />
          {/* Deleting the project lives here, at the far end of Settings, rather
              than as an icon in the page header where it sat one misclick from
              "Run AI Visibility check". It destroys every query, run and snapshot, and a
              confirm dialog was the only thing standing between the two. */}
          {canWrite && !isEmbed() ? (
            <section className="page-section-divider">
              <h2 className="text-heading-20 text-negative-400">Delete project</h2>
              <p className="supporting-copy mt-1 mb-3">
                Permanently deletes this project and all its queries, competitors, runs, and snapshots.
              </p>
              {showDeleteConfirm ? (
                <Card className="surface-card p-6 bg-negative-soft">
                  <h3 className="text-heading-16 text-negative-400 mb-2">Delete project?</h3>
                  <p className="text-copy-14 text-secondary mb-4">
                    This will permanently delete <strong className="text-strong">{model.project.displayName || model.project.name}</strong> and
                    all its queries, competitors, runs, and snapshots. This cannot be undone.
                  </p>
                  <div className="flex items-center gap-3">
                    <Button
                      type="button"
                      variant="destructive"
                      disabled={deleting}
                      onClick={asyncHandler(handleDeleteProject)}
                    >
                      {deleting ? 'Deleting...' : 'Yes, delete project'}
                    </Button>
                    <Button type="button" variant="outline" disabled={deleting} onClick={() => setShowDeleteConfirm(false)}>
                      Cancel
                    </Button>
                  </div>
                </Card>
              ) : (
                <WriteButton type="button" variant="outline" onClick={() => setShowDeleteConfirm(true)}>
                  <Trash2 className="h-4 w-4 text-secondary" />
                  Delete project
                </WriteButton>
              )}
            </section>
          ) : null}
        </>
      ) : tab === 'client-queries' && queryLimit !== undefined ? (
        <EmbedQueriesSection projectName={projectName} limit={queryLimit} />
      ) : tab === 'queries' || tab === 'discovery' ? (
        <QueriesSection
          projectName={projectName}
          queryWorkspace={requestedQueryWorkspace}
          onQueryWorkspaceChange={value => updateVisibilitySearch({ queryWorkspace: value, trackingQueryId: undefined })}
          researchMode={projectSearchParams.researchMode === 'test' ? 'test' : 'find'}
          onResearchModeChange={value => updateVisibilitySearch({ researchMode: value })}
          selection={visibilitySelection}
          onSelectionChange={updateVisibilitySearch}
          trackingQueryId={typeof projectSearchParams.trackingQueryId === 'string' ? projectSearchParams.trackingQueryId : undefined}
          onTrackingQueryIdChange={value => updateVisibilitySearch({ trackingQueryId: value })}
          publishGuard={{ sweepActive: hasActiveVisibilitySweep }}
        />
      ) : tab === 'agent-readiness' ? (
        <SiteHealthSection
          projectName={model.project.name}
          projectId={model.project.id}
          initialRunId={projectSearchParams.siteHealthRunId}
          onReleaseInitialRun={releaseInitialSiteHealthRun}
        />
      ) : tab === 'conversions' ? (
        <>
          {/* Delivery first, plumbing second: spend and conversions are what an
              operator opens this tab for, and Conversion Integrity below is how
              the numbers earn their trust. */}
          <GoogleAdsPerformanceSection key={`${model.project.id}:performance`} projectName={model.project.name} />
          <ConversionIntegrityWorkspace
            key={model.project.id}
            projectId={model.project.id}
            projectName={model.project.name}
          />
        </>
      ) : tab === 'history' ? (
        <ProjectHistorySection projectName={model.project.name} />
      ) : tab === 'activity' ? (
        <ActivitySection projectName={model.project.name} />
      ) : tab === 'traffic' ? (
        <ServerTrafficSection
          key={JSON.stringify([model.project.id, projectSearchParams.connectCloudRun])}
          view="project"
          projectName={projectName}
          initialCloudRunTarget={projectSearchParams.connectCloudRun}
          sourceId={typeof projectSearchParams.trafficSource === 'string' ? projectSearchParams.trafficSource : undefined}
          onSelectSource={trafficSource => updateVisibilitySearch({ trafficSource, connectCloudRun: undefined })}
        />
      ) : tab === 'backlinks' ? (
        <BacklinksSection projectName={model.project.name} />
      ) : tab === 'seo-data' ? (
        <SeoDataSection key={model.project.id} projectName={model.project.name} />
      ) : tab === 'journeys' ? (
        <JourneysSection key={model.project.id} projectName={model.project.name} />
      ) : tab === 'local' ? (
        // Local presence (Google Business Profile + Places). GbpSection
        // self-gates on the connection and renders its own empty state.
        <GbpSection projectName={model.project.name} projectId={model.project.id} />
      ) : tab === 'search-console' ? (
        <SearchConsoleSection projectName={model.project.name} />
      ) : null}
    </div>
  )
}
