@canonry/canonry 7.21.0 → 7.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +0,0 @@
1
- import{j as e,r as o,t as Cd,u as Le,L as Ss,h as xs,o as Gt,B as Ai,C as Ql,D as kd,k as Ad,l as Rd}from"./vendor-tanstack-ZXXkndVj.js";import{T as fe,t as Pd,a as Id,s as Ri,M as ya,I as Oe,f as Xe,R as ea,m as Td,B as R,b as Hl,c as Ld,d as $d,e as qd,S as Wl,g as Yl,u as Pi,h as Md,n as Wn,C as Ed,i as Jl,j as Xl,k as Ii,l as Dd,o as Od,p as Fd,q as sn,r as Zl,v as ec,w as Ne,x as rr,y as ne,z as re,A as is,D as Dt,E as Je,F as Gd,G as _d,H as Kd,J as tc,K as Ud,L as Bd,N as Vd,O as wr,P as lo,Q as zd,U as Qd,V as Hd,W as Wd,X as Hs,Y as An,Z as Yd,_ as Jd,$ as Dn,a0 as Xt,a1 as Xd,a2 as Zd,a3 as co,a4 as sc,a5 as Jt,a6 as Ti,a7 as eu,a8 as tu,a9 as su,aa as nu,ab as uo,ac as Ee,ad as au,ae as ru,af as Sr,ag as iu,ah as ou,ai as lu,aj as cu,ak as du,al as uu,am as mu,an as hu,ao as xu,ap as pu,aq as gu,ar as fu,as as yu,at as vu,au as bu,av as nc,aw as Qs,ax as ju,ay as ac,az as cr,aA as Nu,aB as Ye,aC as wu,aD as Su,aE as Cu,aF as dr,aG as ku,aH as Au,aI as Ru,aJ as ni,aK as Pu,aL as Iu,aM as Tu,aN as rc,aO as ai,aP as Lu,aQ as Li,aR as $u,aS as Yn,aT as Yt,aU as ka,aV as Es,aW as ic,aX as ir,aY as ri,aZ as qu,a_ as mo,a$ as oc,b0 as va,b1 as Mu,b2 as lc,b3 as cc,b4 as Eu,b5 as dc,b6 as bn,b7 as $i,b8 as Cr,b9 as Du,ba as Ou,bb as Fu,bc as Gu,bd as _u,be as xa,bf as ho,bg as Oa,bh as kr,bi as Ku,bj as Uu,bk as xo,bl as Ar,bm as Rn,bn as uc,bo as qi,bp as mc,bq as Bu,br as Vu,bs as po,bt as zu,bu as Qu,bv as Hu,bw as Wu,bx as Yu,by as Ju,bz as Xu,bA as Zu,bB as em,bC as tm,bD as sm,bE as nm,bF as am,bG as rm,bH as im,bI as om,bJ as lm,bK as cm,bL as dm,bM as um,bN as mm,bO as hm,bP as xm,bQ as pm,bR as gm,bS as fm,bT as ym,bU as vm,bV as Ps,bW as bm,bX as go,bY as jm,bZ as Nm,b_ as wm,b$ as Sm,c0 as Cm,c1 as hc,c2 as km,c3 as Am,c4 as fo,c5 as Rm,c6 as $s,c7 as Pm,c8 as xc,c9 as Rr,ca as Im,cb as Tm,cc as yo,cd as Lm,ce as $m,cf as qm,cg as Mm,ch as Em,ci as Dm,cj as Om,ck as pc,cl as Fm,cm as gc,cn as fc,co as yc,cp as vc,cq as Gm,cr as _m,cs as Km,ct as Um,cu as Bm,cv as Vm,cw as zm,cx as vo,cy as Qm,cz as Hm,cA as Wm,cB as Ym,cC as Jm,cD as Xm,cE as Zm,cF as eh,cG as bo,cH as th,cI as sh,cJ as nh,cK as ah,cL as rh,cM as ih,cN as oh,cO as lh,cP as ch,cQ as dh,cR as uh,cS as mh,cT as Pr,cU as hh,cV as xh,cW as ph,cX as gh,cY as fh,cZ as yh,c_ as vh,c$ as bh,d0 as jh,d1 as Nh,d2 as wh,d3 as Sh,d4 as Ch,d5 as bc,d6 as kh,d7 as Ah,d8 as Rh,d9 as Ph,da as Ih,db as Th,dc as Fa,dd as Lh,de as $h,df as qh,dg as jo,dh as Mh}from"./index-Bhgc-ydO.js";import{u as rn,D as Vs,a as Ds,b as Mi,M as or,c as Ks,F as Eh,P as jc,s as Dh,p as Oh,S as Fh}from"./SiteHealthSection-DxsZelde.js";import{A as Ei,a as Gh,b as _h,c as Kh,s as ls,i as jn,d as Uh,e as Bh,V as No}from"./v2-overview-adapter-BgCyNPPW.js";import{o as Ot,C as ba,f as Pn,a as ms,b as Vt,c as Tt,d as rs,e as ct,g as hs,h as ta,M as Nc,i as Vh,j as Aa,p as zh,k as ii,l as Qh,m as wo}from"./ChartPrimitives-CZ4wVBJL.js";import{g as wc,y as ja,U as Hh,z as Wh,L as Yh,D as Jh,l as Xh,j as ur,I as Zh,C as Jn,X as ex,e as tx,J as sx,P as nx,K as ax,N as Sc}from"./vendor-lucide-Y6jANGfG.js";import{u as rx,a as ix,b as ox,t as lx,e as cx,c as Ct}from"./extract-error-message-W9-nsUzb.js";import{R as on,C as ln,a as Na,X as cn,Y as dn,T as un,b as oi,L as mr,A as nn,d as Bs,e as dx}from"./vendor-recharts-D-cUuLZo.js";import{H as Ir}from"./Hint-DICI5Jq9.js";import{A as ux}from"./AuditHistoryPanel-BYZCeO6t.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const mx=1e6;function hx(t,s="USD",n={}){const a=new Intl.NumberFormat("en-US",{style:"currency",currency:s,...n.fractionDigits===void 0?{}:{minimumFractionDigits:n.fractionDigits,maximumFractionDigits:n.fractionDigits}}),r=a.format(t/mx);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Ga={projectWide:"Project-wide",projectWideHelp:"This tab covers the whole project. Your measurement scope stays selected for AI Visibility and Queries.",savedScopeUnavailable:"Saved scope unavailable"};function Cc(t,s){return t!=="viewer"||s!==null}function kc(t,s){return t==="research"&&!s?"tracked":t}function Ac(t,s){return s.measurementScope==="project"?!1:s.measurementScopeKey?!(s.measurementScope==="group"?t.groups:s.measurementScope==="property"?t.targets:t.markets).some(a=>a.stableKey===s.measurementScopeKey):!0}function li(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function xx(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function px(t){if(t.embedded)return{kind:"none"};const{tab:s}=t;switch(s){case"overview":return t.surface==="advanced-overview"?{kind:"report-picker"}:{kind:"none"};case"queries":case"discovery":{const{tracking:n}=t;return t.queryWorkspace!=="tracked"||n.state!=="ready"||n.mode!=="advanced"?{kind:"none"}:n.scopeUnavailable?{kind:"scope-unavailable"}:{kind:"tracking-picker"}}case"search-console":case"activity":case"technical-aeo":case"conversions":case"local":case"backlinks":case"history":return t.scoped&&t.surface==="advanced-overview"?{kind:"project-wide"}:{kind:"none"};case"settings":case"portfolio":return{kind:"none"};default:return s}}function ci({state:t,label:s,className:n}){return e.jsx(fe,{tone:Id(t),className:n,children:s??Pd(t)})}const Nn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],So={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},gx={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},fx="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function yx(t,s){return s.unavailable?{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1}:s.noRun?{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1}:t.snapshotsTotal===0?s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1}:t.snapshotsWithAnswerText===0?{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1}:s.hasCompetitors?t.combinedMentionSnapshots===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:Xe(t.score,ea.percent),numeric:!0,detail:`${t.projectMentionSnapshots} of ${t.combinedMentionSnapshots} brand mentions`,showRows:!0}:{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1}}function vx({breakdown:t,projectLabel:s}){if(t.ranking.length===0)return null;const n=t.ranking.map(a=>({label:a.kind==="project"?`${s} (you)`:a.domain??"",mentions:a.mentionSnapshots,share:a.share,isYou:a.kind==="project"}));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Oe,{text:fx})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:n.map(a=>e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${a.isYou?"text-heading font-medium":"text-secondary"}`,children:a.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${a.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${a.share>0?Math.max(a.share*100,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:a.mentions}),e.jsx("td",{className:"mention-share-share",children:Xe(a.share)})]},a.label))})]})}function bx({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",m=i?"pooled":d,u=d==="branded"?t.branded:t.breakdown,x=d==="branded"?t.breakdown:t.branded,f=yx(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:x.snapshotsTotal>0}),p=Ri(f.headline),g=m==="non-brand"?ya[t.tone]:"text-secondary";function y(v){const C=Nn.findIndex(L=>L.value===d);let b=null;v.key==="ArrowRight"||v.key==="ArrowDown"?b=(C+1)%Nn.length:v.key==="ArrowLeft"||v.key==="ArrowUp"?b=(C-1+Nn.length)%Nn.length:v.key==="Home"?b=0:v.key==="End"&&(b=Nn.length-1),b!==null&&(v.preventDefault(),r(Nn[b].value),v.currentTarget.querySelectorAll('[role="radio"]')[b]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:l,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Oe,{text:gx[m]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:y,children:Nn.map(v=>{const C=v.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":C,tabIndex:C?0:-1,onClick:()=>r(v.value),className:`segmented-option min-h-11 ${C?"segmented-option-active":""}`,children:v.label},v.value)})}):e.jsx("span",{className:"mention-share-class",children:So[m]})]}),f.numeric?e.jsxs("p",{className:`mention-share-value ${g}`,children:[p.figure,p.sign?e.jsx("span",{className:"text-faint",children:p.sign}):null]}):e.jsx("p",{className:"mention-share-value-text",children:f.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:So[m]}),` · ${f.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),f.showRows&&e.jsx(vx,{breakdown:u,projectLabel:s})]})}function Ra({items:t,label:s="Details"}){return t.length===0?null:e.jsxs("details",{className:"av-details",children:[e.jsx("summary",{children:s}),e.jsx("ul",{className:"av-details-list",children:t.map((n,a)=>e.jsx("li",{children:n},a))})]})}function pa({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(c){const d=t.findIndex(u=>u.value===s);let m=null;c.key==="ArrowRight"||c.key==="ArrowDown"?m=(d+1)%t.length:c.key==="ArrowLeft"||c.key==="ArrowUp"?m=(d-1+t.length)%t.length:c.key==="Home"?m=0:c.key==="End"&&(m=t.length-1),m!==null&&(c.preventDefault(),n(t[m].value),c.currentTarget.querySelectorAll('[role="radio"]')[m].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(c=>{const d=c.value===s,m=c.description?`${l}-${c.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":m,tabIndex:d?0:-1,onClick:()=>n(c.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:c.label}),c.description?e.jsx("span",{id:m,className:"sr-only",children:c.description}):null]},c.value)})})}const jx=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Nx={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},wx={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},Sx={"non-brand":"Counts queries that do not name your brand.",branded:"Counts queries that name your brand.",all:"Counts every tracked query, so mention share is not shown."},Cx={"select-query-class":"no query type selected","answer-selection":"answers selected by the brands they named","no-competitors":"no competitors configured","insufficient-observed":"needs 3 observed competitors, each named in 3 or more answers","no-answers":"no answer text","no-mentions":"no brands named",unavailable:"competitor data unavailable"},Co="Mention share: your share of the brand mentions in these answers, each brand counted at most once per answer. Named: answers that name the brand. Cited: answers whose sources link to its site. Company names in answers are observations. Only competitor sites count toward mention share.",di=100;function kx(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function Rc(t){return t==="unavailable"?"Unavailable":"Not measured"}function ui(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function Is(t,s,n){return t===1?s:n}function Pc(t){const s=t.label.trim(),n=Ld(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function Ic({row:t,aliases:s=[],autoAliases:n=[]}){const a=Pc(t),r=[...s.map(i=>({alias:i,auto:!1})),...n.map(i=>({alias:i,auto:!0}))],l=r.length>0?e.jsxs("span",{className:"av-of block",children:["Also named"," ",r.map(({alias:i,auto:c},d)=>e.jsxs("span",{children:[d>0?", ":"",i,c?e.jsx("span",{className:"av-alias-auto",title:"Detected automatically from this project's stored answers",children:" (auto)"}):null]},`${c?"auto":"curated"}:${i}`))]}):null;return a?e.jsxs(e.Fragment,{children:[a," ",e.jsx("span",{className:"av-of",children:t.domain}),l]}):e.jsxs(e.Fragment,{children:[t.domain,l]})}function Ax(t){const s=Pc(t);return s?`${s} (${t.domain})`:t.domain}function ko(t,s){return s&&t>=di?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function mi({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function c(){if(!a){r(!0),i(null);try{await n(s)===!1&&i(`Could not ${t} competitor. Try again.`)}catch{i(`Could not ${t} competitor. Try again.`)}finally{r(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs(R,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{c()},children:[t==="pin"?"Pin":"Unpin"," ",e.jsx("span",{className:"sr-only",children:s})]}),l?e.jsx("span",{role:"alert",className:"sr-only",children:l}):null]})}function Rx({urls:t}){return e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.map(s=>e.jsx("li",{className:"break-all",children:s},s))})]})}function Un({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:Rc(n)}):e.jsxs("span",{className:"whitespace-nowrap",children:[e.jsx("span",{className:`av-n-sm ${a}`,children:t})," ",e.jsxs("span",{className:"av-of",children:["of ",s]})]})}function Ao({percent:t,state:s,toneClass:n}){if(s!=="measured"||t===null)return e.jsx("span",{className:"text-[13px] text-secondary",children:s==="measured"?"Not measured":Rc(s)});const{figure:a,sign:r}=Ri(Xe(t,ea.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Px({rows:t,state:s,named:n,cited:a,onPin:r}){return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":"Other competitors seen",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(Ic,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:ui(l.surfaceClass)}),e.jsx("td",{children:e.jsx(Un,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Un,{count:l.citationCount,of:a,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex min-w-max items-start gap-2",children:[s==="measured"&&l.sampleUrls.length>0?e.jsx(Rx,{urls:l.sampleUrls}):null,r?e.jsx(mi,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function Ix({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,c]=o.useState(null);async function d(){const m=n.trim();if(!(!m||r)){l(!0),c(null);try{if(await t(m)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:m=>{m.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:m=>a(m.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(R,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Tx({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},competitorAutoAliases:r={},canWrite:l,isEmbed:i,onWindowChange:c,onPin:d,onUnpin:m,onAddCompetitor:u,error:x,onRetry:f,isLoading:p=!1,scopeLabel:g,advancedPortfolio:y=!1}){const v=o.useId(),C=l&&!i,b=s?.pinned??n,L=s?.observed??[],k=s?.otherSources??[],h=s?.evidence,j=kx(s),w=s?.basis==="observed",P=w?L.filter(_=>_.shareOfVoice!==null):b,q=w?L.filter(_=>_.shareOfVoice===null):L,S=s?.filters.queryClass,V=s?.marketState?.draft?.pendingCompetitorDomains.length??0,F=s?.truncated===!0,D=h?.answeredResults??0,K=h?h.answeredResults+h.missingAnswerTextResults:0,H=S==="non-brand"&&s?.project.shareOfVoice!=null?ya[Td(s.project.shareOfVoice)]:"text-primary",se=_=>C?_.pinned?m?e.jsx(mi,{action:"unpin",domain:_.domain,mutation:m}):null:d?e.jsx(mi,{action:"pin",domain:_.domain,mutation:d}):null:null,Q=P.some(_=>se(_)!==null),M=[g,S?wx[S]:null,Nx[t],s?.basis?w?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),J=[];if(s&&!w&&P.length===0&&J.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&J.push({key:"reason",text:`Mention share: ${Cx[s.reason]}`}),s&&q.length>0){const _=q.length;J.push({key:"others",text:F&&_>=di?`${di} or more other competitors seen`:`${_} other ${Is(_,"competitor","competitors")} seen`})}V>0&&J.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${V} ${Is(V,"competitor","competitors")}`});const E=[h&&h.missingAnswerTextResults>0?"Answer data incomplete":null,h&&h.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);E.length>0&&J.push({key:"incomplete",text:E.join(" · "),className:ya.caution});const W=[];if(s&&h){W.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",Is(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:h.answeredResults})," ",Is(h.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:h.answeredResults})," ",Is(h.answeredResults,"answer","answers")]})),!s.reason&&j==="measured"&&s.project.shareOfVoice!==null&&W.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),P.map(ae=>e.jsxs(Cd.Fragment,{children:[", ",ae.domain," ",e.jsx("strong",{children:ae.mentionCount})]},ae.domain))," ","of ",e.jsx("strong",{children:h.mentionCredits})," ",w?"brand mentions":"tracked-brand mentions"]})),W.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:h.sourceResults})]})),q.length===0&&W.push("Other competitors seen: none"),h.missingAnswerTextResults>0&&W.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:h.missingAnswerTextResults})," ",Is(h.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),h.incompleteSourceResults>0&&W.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:h.incompleteSourceResults})," ",Is(h.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const _=h.excludedProbeResults+h.excludedNonCompletedResults;_>0&&W.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:_})," ",Is(_,"answer","answers")," from spot checks or unfinished sweeps"]}))}const T=[...s?[{name:"You",row:s.project}]:[],...P.map(_=>({name:_.domain,row:_}))].filter(_=>_.row.sampleUrls.length>0);j==="measured"&&T.length>0&&W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsx("summary",{children:"Sample pages cited"}),e.jsx("div",{className:"av-subdetails-body",children:T.map(({name:_,row:ae})=>e.jsxs("div",{children:[e.jsx("p",{children:_}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:ae.sampleUrls.map(ie=>e.jsx("li",{className:"break-all",children:ie},ie))})]},ae.domain))})]})),s&&q.length>0&&W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",ko(q.length,F)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Px,{rows:q,state:j,named:D,cited:K,onPin:C?d:void 0})})]}));const ee=s?.observedNames??[];if(ee.length>0){const _=s?.observedNamesTotal??ee.length;W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",_>ee.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:ee.length})," of ",e.jsx("strong",{children:_})]}):e.jsx("strong",{children:ee.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:ee.map(ae=>e.jsxs("li",{children:[ae.name," · ",ae.answerCount," ",Is(ae.answerCount,"answer","answers")]},ae.name))})]}))}return k.length>0&&W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",ko(k.length,F)]}),e.jsx("ul",{className:"av-subdetails-body",children:k.map(_=>e.jsxs("li",{children:[e.jsxs("span",{children:[Ax(_)," · ",ui(_.surfaceClass)," · ",_.citationCount," ",Is(_.citationCount,"citation","citations")]}),_.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:_.sampleUrls.map(ae=>e.jsx("li",{className:"break-all",children:ae},ae))}):null]},_.domain))})]})),e.jsxs("section",{"aria-labelledby":v,"aria-busy":p,className:"overview-brief",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:v,className:"av-card-title",children:"Competitors over time"}),e.jsx(Oe,{text:S?`${Sx[S]} ${Co}`:Co})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:M}),e.jsx(pa,{label:"Competitors over time window",className:"flex-wrap",options:jx,value:t,onChange:c})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[x?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:x}),f?e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:f,children:"Retry competitors over time"}):null]}):null,p&&!s&&b.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-24 animate-pulse rounded-md bg-surface",children:e.jsx("span",{className:"sr-only",children:"Loading competitors over time"})}):s||P.length>0?e.jsxs("table",{className:"av-grid av-grid-brands","aria-label":"Competitors over time",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Brand"})}),e.jsx("th",{scope:"col",className:"av-brand-type",children:"Type"}),e.jsx("th",{scope:"col",children:"Mention share"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),Q?e.jsx("th",{scope:"col",className:"av-brand-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})}):null]})}),e.jsxs("tbody",{children:[s?e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:s.project.label.trim()?e.jsxs(e.Fragment,{children:[s.project.label.trim()," ",e.jsx("span",{className:"av-of",children:"(you)"})]}):"You"}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:"Your brand"}),e.jsx("td",{children:e.jsx(Ao,{percent:s.project.shareOfVoice,state:j,toneClass:H})}),e.jsx("td",{children:e.jsx(Un,{count:s.project.mentionCount,of:D,state:j,toneClass:H})}),e.jsxs("td",{children:[e.jsx(Un,{count:s.project.citationCount,of:K,state:j,toneClass:H}),y&&j==="measured"?e.jsx("span",{className:"block text-[13px] text-secondary",children:Hl(s.project.domain,"cited")}):null]}),Q?e.jsx("td",{className:"av-brand-actions"}):null]}):null,P.map(_=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(Ic,{row:_,aliases:_.pinned?a[_.domain]:void 0,autoAliases:_.pinned?r[_.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:ui(_.surfaceClass)}),e.jsx("td",{children:e.jsx(Ao,{percent:_.shareOfVoice,state:j,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Un,{count:_.mentionCount,of:D,state:j,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Un,{count:_.citationCount,of:K,state:j,toneClass:"text-primary"})}),Q?e.jsx("td",{className:"av-brand-actions",children:se(_)}):null]},_.domain))]})]}):null,J.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:J.map(_=>e.jsx("p",{className:_.className,children:_.text},_.key))}):null]}),e.jsx(Ra,{items:W}),C&&u?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(Ix,{onAddCompetitor:u})}):null]})}function Ro({history:t,maxDots:s=12,signal:n="citations"}){const a=t.slice(-s);if(a.length===0)return e.jsx("span",{className:"text-[13px] text-secondary",children:"No data"});const r=n==="mentions"?"Mention":"Citation",l=n==="mentions"?{cited:"mentioned","not-cited":"not mentioned",lost:"mention lost",emerging:"new mention",pending:"mention pending"}:{cited:"cited","not-cited":"not cited",lost:"citation lost",emerging:"new citation",pending:"citation pending"},i={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},c={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,m=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),x=`${a.length} ${a.length===1?"run":"runs"}`,f=a.map((p,g)=>{const y=new Date(p.createdAt).toLocaleDateString();return`${g===d?"Latest run, ":""}${y}: ${l[p.citationState]??p.citationState}${p.model?`, model ${p.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${x}. ${f}`,children:[a.length>1?e.jsx("span",{className:"text-[11px] text-secondary shrink-0","aria-hidden":"true",children:m}):null,e.jsx("div",{className:"flex shrink-0 items-center gap-[3px]",title:x,"aria-hidden":"true",children:a.map((p,g)=>{const y=!!(p.model&&g>0&&a[g-1]?.model&&a[g-1].model!==p.model),v=g===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${c[p.citationState]??"rounded-sm"} ${i[p.citationState]??"bg-mono-700"} ${y?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${v?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[p.citationState]??p.citationState,new Date(p.createdAt).toLocaleDateString(),p.model?`model ${p.model}`:null,y?"model changed":null,v?"latest run":null].filter(Boolean).join(" · ")},`${p.runId}:${p.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function hi(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const l=s.get(r.createdAt);l?l.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:l}])=>({runId:l,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const Pa="__cited__",Ia="__mentioned__",zs="__mentionShare__";function Os(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Ot(n),end:Ot(a),sweepCount:s.sweepCount??1}}function wa(t,s=new Date){return qd(t,s)}function Ta(t,s=new Date){const n=Os(t);if(!n)return null;const a=wa(n.start,s),r=wa(n.end,s);return a===r?a:`${a} to ${r}`}function Di(t,s=new Date){const n=Os(t),a=Ta(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Lx(t){const s=Os(t);return s?$d(s.start):""}function Sa(t){return t.trim().toLowerCase()}function $x(t,s={}){return t.map(n=>{const a=n.trim().toLowerCase(),r=(s[n]??[]).map(l=>l.trim().toLowerCase()).filter(Boolean).sort();return a&&r.length>0?`${a}=${r.join("|")}`:a}).filter(Boolean).sort().join(`
2
- `)}const qx={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function at(t){const s=Sa(t);return qx[s]??t.charAt(0).toUpperCase()+t.slice(1)}function xi(t){return Math.round(t*1e3)/10}function pi(t){return t.byProvider??{}}function Mx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?Pa:Ia,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(x=>({date:x.startDate,[d]:xi(x[m])})),series:[d],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(pi(d))))].sort();return{rows:t.buckets.map(d=>{const m={date:d.startDate},u=pi(d);for(const x of i){const f=u[x];m[x]=f?xi(f[l]):null}return m}),series:i,hasData:a,singleBucket:r}}function Tc(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Ex(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Dx(t){return t.servedModelAttribution??{}}function Ox(t){return t.modelServiceMismatch??{}}function Fx(t){return t.modelPointerChanges??{}}function ga(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Ca(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return t.models.length===0?"Unknown model":`${t.models.join(", ")}${t.includesUnknown?" and an unknown model":""}`}}function Gx(t){return ga([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function _x(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const l=s.get(r.bucketStartDate)??[];l.push({provider:n,event:r}),s.set(r.bucketStartDate,l)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,l)=>r.provider.localeCompare(l.provider)||r.event.observedAt.localeCompare(l.event.observedAt))}))}function Kx(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const l=r.events.filter(i=>!i.fromPreWindowAnchor);for(const i of r.events)i.fromPreWindowAnchor&&n.push({provider:a,event:i});l.length>0&&(s[a]={...r,events:l})}return{buckets:_x(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Ux(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Bx(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[zs]:r?.rate==null?null:xi(r.rate)}}),n=s.map(a=>a[zs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[zs],hasData:n.length>0,singleBucket:n.length===1}}function Vx(t,s,n){return s==="mentionShare"?Bx(t):Mx(t,s,n)}function zx(t,s){if(s==="mentionShare")return t.buckets.flatMap(a=>{const r=a.mentionShare?.rate;return typeof r=="number"&&Number.isFinite(r)?[r]:[]});const n=s==="cited"?"citationRate":"mentionRate";return t.buckets.map(a=>a[n])}function Qx(t,s){const n=t.windowChange;if(!n)return null;switch(s){case"cited":return n.citationRate;case"mentioned":return n.mentionRate;case"mentionShare":return n.mentionShare}}function Hx(t,s,n){const a=n==="mentioned"?"mentionRate":"citationRate";for(let r=t.buckets.length-1;r>=0;r--){const l=pi(t.buckets[r])[s];if(l)return l[a]}return null}function We(t){return Date.parse(t)}function Lc(t,s){const n=Os(t);if(!n)return!1;const a=We(s);return a>=We(n.start)&&a<=We(n.end)}function $c(t){return t.basketChanges??[]}function qc(t,s){return s.filter(n=>Lc(t,n.at)).sort((n,a)=>We(n.at)-We(a.at))}function hr(t,s){return Sa(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function Wx(t){return Object.entries(t).filter(([s,n])=>!hr(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function Yx(t){return[...$c(t)].sort((s,n)=>We(n.at)-We(s.at)).map(s=>({at:Ot(s.at),added:s.added,removed:s.removed}))}function Jx(t,s){const n=[...t.events].sort((r,l)=>We(r.observedAt)-We(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)We(r.observedAt)<=We(s)&&(a=r.to);return a}function Po(t,s,n,a){return{provider:t,at:Ot(s.observedAt),onOrBefore:s.fromPreWindowAnchor===!0,anchorAt:s.anchorObservedAt?Ot(s.anchorObservedAt):null,from:s.from,to:s.to,served:n,reroute:a}}function Xx(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],c=new Set(r.events.map(d=>d.observedAt));for(const d of r.events){const m=hr(a,d.to)?i.find(u=>u.observedAt===d.observedAt):void 0;n.push(Po(a,d,m?{from:m.from,to:m.to}:null,!1))}for(const d of i)c.has(d.observedAt)||hr(a,Jx(r,d.observedAt))&&n.push(Po(a,d,null,!0))}return n.sort((a,r)=>We(r.at)-We(a.at)||a.provider.localeCompare(r.provider))}function Zx({latest:t,queryChanges:s,modelRows:n,now:a=new Date}){const r=[...s.map(f=>f.at),...n.map(f=>f.at)];if(r.length===0)return null;const l=f=>t!==void 0&&Lc(t,f),i=s.filter(f=>l(f.at)),c=i.reduce((f,p)=>f+p.added.length,0),d=i.reduce((f,p)=>f+p.removed.length,0),m=n.filter(f=>l(f.at)).length,u=t?Ta(t,a):null;if(u===null||c+d+m===0){const f=r.reduce((p,g)=>We(g)>We(p)?g:p);return`No changes since ${wa(f,a)}`}const x=[u];return c>0&&x.push(`${c} ${c===1?"query":"queries"} added`),d>0&&x.push(`${d} ${d===1?"query":"queries"} removed`),m>0&&x.push(`${m} new ${m===1?"model":"models"}`),x.join(" · ")}function ep(t,s,n,a=null){const r=We(t);if(!Number.isFinite(r))return null;const l=s.filter(m=>We(m)<r);if(l.length>0)return Ot(l.reduce((m,u)=>We(u)>We(m)?u:m));const i=n.map(m=>Os(m)).filter(m=>m!==null).sort((m,u)=>We(m.start)-We(u.start)),c=i.findIndex(m=>We(m.start)<=r&&r<=We(m.end));if(c===-1)return null;const d=i[c];return We(d.start)===r?c>0?i[c-1].end:a&&We(a)<r?Ot(a):null:d.sweepCount===2&&We(d.end)===r?d.start:null}function tp(t){const s=new Map,n=(a,r)=>{const l=s.get(a);l?l.push(r):s.set(a,[r])};for(const a of[...t].sort((r,l)=>r.revision-l.revision)){const r=We(a.at);for(const l of a.removed)n(l,{at:r,member:!1});for(const l of a.added)n(l,{at:r,member:!0})}return new Map([...s].filter(([,a])=>a.at(-1).member))}function Xn(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function sp(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function gi(t,s){const n=We(s.start),a=We(s.end);return s.sweepCount>2?sp(t,n,a):Xn(t,n)!==Xn(t,a)}function Mc(t,s,n,a){const r=We(s),l=We(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},c=new Set;for(const[x,f]of tp(t)){if(!a(f))continue;c.add(x);const p=Xn(f,r),g=Xn(f,l);p!==g?(g?i.added:i.removed).push(x):(p?i.removedAndAddedBack:i.addedAndRemovedAgain).push(x)}if(c.size===0)return null;const d=x=>[...x.added,...x.removed].some(f=>c.has(f)),m=t.filter(x=>We(x.at)>r&&We(x.at)<=l&&d(x)).sort((x,f)=>We(x.at)-We(f.at)),u=[...new Set(m.flatMap(x=>[...x.added,...x.removed]))].filter(x=>c.has(x));return{changes:m,keys:u,moves:i}}function np(t,s){if(t.length<2)return null;const n=t[0],a=t.at(-1),r=Os(n),l=Os(a),i=r?.start??n.startDate,c=l?.end??a.endDate,d=Mc(s,i,c,m=>Xn(m,We(i))!==Xn(m,We(c))||r!==null&&gi(m,r)||l!==null&&gi(m,l));return!d&&n.queryCount===a.queryCount?null:{...d??{changes:[],keys:[],moves:{added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]}},firstCount:n.queryCount,latestCount:a.queryCount}}function Ec(t,s){const n=Os(t);if(!n)return null;const a=Mc(s,n.start,n.end,r=>gi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function Tr(t){return`${t} ${t===1?"query":"queries"}`}function ap(t){const s=[],n=a=>s.length===0?Tr(a):String(a);return t.added.length>0&&s.push(`${n(t.added.length)} added`),t.removed.length>0&&s.push(`${n(t.removed.length)} removed`),t.removedAndAddedBack.length>0&&s.push(`${Tr(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${Tr(t.addedAndRemovedAgain.length)} added and removed again`),ga(s)}function Io(t,s,n,a){return t?s!=="mentionShare"||n!=="non-brand"||!a?!1:t.keys.length>0&&t.keys.every(r=>a(r)==="branded"):!0}const To=320;function Lo(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function $o(t){return t==="non-brand"?0:t==="branded"?1:2}function rp(t){const s=[];for(const n of t){const a=s.at(-1);a&&a.queryClass===n.queryClass?a.rows.push(n):s.push({queryClass:n.queryClass,rows:[n]})}return s}function ip(t){return t.phrase}function qo(t,s){return s==="citations"?t.citationState:t.visibilityState==="pending"||t.answerMentioned==null&&t.visibilityState==null?"pending":t.visibilityState==="visible"||t.answerMentioned===!0?"cited":"not-cited"}function Mo(t,s){if(s==="mentions")switch(t){case"cited":return"Mentioned";case"not-cited":return"Not Mentioned";case"pending":return"Pending";case"emerging":return"Newly Mentioned";case"lost":return"No Longer Mentioned"}switch(t){case"cited":return"Cited";case"not-cited":return"Not Cited";case"lost":return"Lost";case"emerging":return"Emerging";case"pending":return"Pending"}}function op(t,s){return t.map(n=>Dc(n,s))}function Dc(t,s){return s==="citations"?t:{...t,citationState:qo(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:qo(n,s)}))}}function Eo(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,l=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=l==="cited"||l==="emerging";return r==="lost"||l!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:l===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function lp(t){const s=hi(op(t,"mentions")),n=hi(t);return[Eo(s,"mentions"),Eo(n,"citations")]}function cp({signal:t}){const s=t.tone==="positive"?"text-positive":t.tone==="negative"?"text-negative":t.tone==="pending"?"text-caution":"text-secondary";return e.jsx("span",{className:s,children:t.label})}function Do({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:lp(t).map(s=>e.jsx(cp,{signal:s},s.key))})}function Oc({queryClass:t,actions:s}){return e.jsxs(e.Fragment,{children:[s?e.jsx("div",{className:"query-evidence-toolbar",children:e.jsxs("div",{className:"query-evidence-actions",children:[!t&&e.jsx(Wl,{}),s]})}):null,t?e.jsx(Yl,{queryClass:t,manage:!!s}):null]})}function dp({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[],actions:i,actionPanel:c}){const{openEvidence:d}=Pi(),m=o.useId(),[u,x]=o.useState(new Set),f=Md(),[p,g]=o.useState("mentions"),[y,v]=o.useState(n),[C,b]=o.useState("all"),[L,k]=o.useState(""),h=a??L,j=E=>{k(E),r?.(E)},w=o.useMemo(()=>[...new Set([...t.map(E=>E.provider).filter(Boolean),...h?[h]:[]])].sort(),[t,h]),P=o.useMemo(()=>{const E=new Map;for(const W of t){if(h&&W.provider!==h)continue;const T=W.query,ee=W.queryClass??null,_=s?W.location??null:null,ae=JSON.stringify([T,ee,_]),ie=E.get(ae)??{key:ae,phrase:T,queryClass:ee,location:_,items:[],rawItems:[]};ie.items.push(Dc(W,p)),ie.rawItems.push(W),E.set(ae,ie)}return[...E.values()].sort((W,T)=>$o(W.queryClass)-$o(T.queryClass))},[t,p,s,h]),q=o.useMemo(()=>P.filter(E=>C==="all"||(C==="unclassified"?E.queryClass===null:E.queryClass===C)),[P,C]),S=rn({rows:q,getSearchText:ip}),V=o.useMemo(()=>{const E=new Map;for(const W of S.filteredRows){const T=E.get(W.queryClass)??new Set;T.add(W.phrase),E.set(W.queryClass,T)}return E},[S.filteredRows]),F=o.useMemo(()=>new Set(l.map(Wn)),[l]),D=f?6:5,K=S.rows.map(E=>E.key),H=K.length>0&&K.every(E=>u.has(E)),se=E=>{x(W=>{const T=new Set(W);return T.has(E)?T.delete(E):T.add(E),T})},Q=p==="mentions"?"mentioned":"cited",M=p==="mentions"?"Mention History":"Citation History",J=p==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(Oc,{queryClass:C,actions:i}),c,e.jsxs("div",{className:"query-evidence-view-row",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"query-evidence-tabs",role:"tablist","aria-label":"Citation tracking view",children:["mentions","citations"].map(E=>e.jsx("button",{id:`${m}-${E}`,type:"button",role:"tab","aria-controls":m,"aria-selected":p===E,tabIndex:p===E?0:-1,onClick:()=>g(E),onKeyDown:W=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(W.key))return;W.preventDefault();const T=W.key==="Home"?"mentions":W.key==="End"||E==="mentions"?"citations":"mentions";g(T),document.getElementById(`${m}-${T}`)?.focus()},children:E==="mentions"?"Mentions":"Citations"},E))}),e.jsx(Oe,{text:"Mentions track your brand or domain in answer text. Citations track your domain in source links. Each signal is measured independently."})]}),e.jsxs("div",{className:"query-evidence-display-controls",children:[e.jsxs("label",{className:"query-evidence-preview-toggle",children:[e.jsx("input",{type:"checkbox",checked:y==="detailed",onChange:E=>v(E.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(R,{type:"button",variant:"ghost",className:"min-h-11",disabled:K.length===0,onClick:()=>{x(E=>{const W=new Set(E);for(const T of K)H?W.delete(T):W.add(T);return W})},children:H?"Collapse page":"Expand page"})]})]}),t.length>0||h?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(Vs,{value:S.query,onChange:S.setQuery,label:"Find a query",placeholder:"Find a query",className:"query-evidence-search"}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Answer engine"}),e.jsxs("select",{value:h,onChange:E=>{j(E.target.value),S.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),w.map(E=>e.jsx("option",{value:E,children:at(E)},E))]})]}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Query class"}),e.jsxs("select",{value:C,onChange:E=>{b(E.target.value),S.setPage(1)},children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsxs("div",{id:m,role:"tabpanel","aria-labelledby":`${m}-${p}`,children:[e.jsx("div",{className:"query-evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table query-evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),f&&e.jsx("th",{scope:"col","aria-label":"Sentiment",children:e.jsxs("span",{className:"inline-flex items-center",children:["Sentiment",e.jsx(Oe,{text:"Branded query rows show the favorable share of judged answers. Non-brand rows show only their unfavorable and mixed answers. Expanded engine rows show each stored answer’s sentiment; factual and unmentioned answers are not judgments."})]})}),e.jsx("th",{scope:"col",children:M}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),rp(S.rows).map(E=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:D,children:[Lo(E.queryClass)," (",V.get(E.queryClass)?.size??0,")"]})}),E.rows.map(({key:W,phrase:T,queryClass:ee,location:_,items:ae,rawItems:ie})=>{const Re=u.has(W),X=K.indexOf(W),ue=`${m}-query-${X}`,ve=F.has(Wn(T)),Z=ae.map(oe=>oe.citationState),he=Z.includes("cited")?"cited":Z.includes("emerging")?"emerging":Z.includes("lost")?"lost":Z.every(oe=>oe==="pending")?"pending":"not-cited",G=[...new Set(ie.map(oe=>oe.queryId).filter(oe=>!!oe))],me=ie.map(oe=>oe.sourceSnapshotId).filter(oe=>!!oe),De=hi(ae),ke=ae.filter(oe=>oe.citationState===Ed.cited||oe.citationState==="emerging").length;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>se(W),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":T,"aria-describedby":ue,"aria-expanded":Re,onClick:oe=>{oe.stopPropagation(),se(W)},children:[e.jsx(wc,{size:16,"aria-hidden":"true",className:Re?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:T}),e.jsxs("span",{id:ue,className:"query-evidence-meta",children:[e.jsx("span",{children:Lo(ee)}),s&&e.jsx("span",{children:_??"No location"}),ae.filter(oe=>oe.provider).map(oe=>e.jsx("span",{children:at(oe.provider)},oe.id))]})]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ci,{state:he,label:Mo(he,p),className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal"}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums","aria-label":`${ke} of ${ae.length} engines ${J}`,title:`${ke} of ${ae.length} engines ${J}`,children:[ke,"/",ae.length]})]})}),f&&e.jsx("td",{children:e.jsx(Jl,{queryId:G.length===1?G[0]:null,sourceSnapshotIds:G.length>1?[]:me,queryClass:ee,location:s?_:void 0})}),e.jsx("td",{children:e.jsx(Ro,{history:De,signal:p})}),e.jsx("td",{className:"evidence-change-cell",children:ve?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(Do,{items:ie})}),e.jsx("td",{})]}),Re&&ae.map((oe,pe)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-engine-row",children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"text-sm text-secondary",children:oe.provider?at(oe.provider):"Awaiting engine"})}),e.jsx("td",{children:e.jsx(ci,{state:oe.citationState,className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal",label:Mo(oe.citationState,p)})}),f&&e.jsx("td",{children:e.jsx(Xl,{queryId:oe.queryId,sourceSnapshotIds:oe.sourceSnapshotId?[oe.sourceSnapshotId]:[],queryClass:oe.queryClass,provider:oe.provider,location:oe.location??null})}),e.jsx("td",{children:e.jsx(Ro,{history:oe.runHistory,signal:p})}),e.jsx("td",{className:"evidence-change-cell",children:ve?null:e.jsx(Do,{items:[ie[pe]??oe]})}),e.jsx("td",{children:e.jsx(R,{variant:"ghost",className:"min-h-11",type:"button",title:`View ${oe.provider?at(oe.provider):"saved"} answer for ${oe.query}`,onClick:we=>{we.stopPropagation(),d(oe.id)},children:"View"})})]}),y==="detailed"&&e.jsx("tr",{className:"query-evidence-preview-row",children:e.jsx("td",{colSpan:D,children:e.jsx(mp,{item:oe,mode:p,onViewFull:()=>d(oe.id)},p)})})]},oe.id))]},W)})]},E.queryClass??"unclassified"))]})}),S.totalRows===0&&(S.hasQuery||C!=="all"||h)?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ds,{page:S.page,pageSize:S.pageSize,visibleRows:S.rows.length,totalRows:S.totalRows,onPageChange:S.setPage,itemLabel:S.hasQuery||C!=="all"||h?"matches":"queries"})]}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",Q==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function up(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=Od(t),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function fi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function mp({item:t,mode:s,onViewFull:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1);if(s==="mentions")return e.jsx(Oo,{item:t,onViewFull:n});const c=t.evidenceUrls.length>0?t.evidenceUrls.map(d=>({uri:d,title:t.groundingSources.find(m=>m.uri===d)?.title})):t.groundingSources;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:t.evidenceUrls.length>0?"Cited sources":c.length>0?"Grounding sources":"Cited domains"}),c.length>0?e.jsx("ul",{className:"space-y-4",children:c.slice(0,l?void 0:6).map((d,m)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(Ii,{url:d.uri,title:d.title}),fi(t,Dd(d.uri)??"")&&e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:"Competitor source"})]},`${m}-${d.uri}`))}):t.citedDomains.length>0?e.jsx("ul",{className:"space-y-1 text-sm text-secondary",children:t.citedDomains.slice(0,l?void 0:6).map(d=>e.jsxs("li",{className:"[overflow-wrap:anywhere]",children:[d,fi(t,d)?" · competitor source":""]},d))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(c.length>6||c.length===0&&t.citedDomains.length>6)&&e.jsx(R,{type:"button",variant:"ghost",className:"min-h-11","aria-expanded":l,onClick:()=>i(d=>!d),children:l?"Show fewer sources":"View all sources"}),t.answerSnippet.trim()?e.jsxs("details",{open:a,className:"border-t border-subtle pt-1",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:d=>{d.preventDefault(),r(m=>!m)},children:"Answer text"}),a&&e.jsx(Oo,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function Oo({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}=t,c=o.useMemo(()=>up({matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}),[a,r,l,i]);if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."});const m=t.answerSnippet.length>To;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[!n&&e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:"Answer text"}),e.jsx(Ei,{headingLevel:4,highlightGroups:c,previewLength:To,children:t.answerSnippet}),(!n&&t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("dl",{className:"space-y-2 text-[13px] leading-6 text-secondary",children:[!n&&t.citedDomains.length>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Cited domains"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.citedDomains.slice(0,6).map(u=>e.jsxs("span",{className:"[overflow-wrap:anywhere]",children:[u,fi(t,u)?" · competitor source":""]},`c-${u}`)),t.citedDomains.length>6&&e.jsxs("span",{children:["+",t.citedDomains.length-6," more"]})]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Competitors in answer"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.mentionedCompetitorDomains.slice(0,4).map(u=>e.jsx("span",{className:"[overflow-wrap:anywhere]",children:u},`co-${u}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]})]}),m&&e.jsx(R,{type:"button",variant:"ghost",className:"min-h-11",onClick:u=>{u.stopPropagation(),s()},children:"View full answer"})]})}function _a({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}function La({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:l=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:l,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>{i!==s&&Fd("window"),n(i)},children:r?r(i):i},i))})}const Lr=ct[0],$r=ct[1],Fo=ct[2],Go=ct[3],hp=["both","server","ga4"],_o={fontSize:11,paddingTop:6},Ko=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Uo=t=>typeof t=="number"?rr(Math.round(t)):String(t),cs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function qr(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,l)=>l<t.startIndex||l>t.endIndex?null:t.start+(l-t.startIndex)*a)}function Mr({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Oe,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function xp(t,s){return n=>{const{cx:a,cy:r,index:l,key:i}=n,c=l??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function pp({projectName:t,sinceMinutes:s}){const[n,a]=o.useState(!0),[r,l]=o.useState(!0),[i,c]=o.useState("both"),d=rx(t,{sinceMinutes:s,granularity:"day",limit:1}),m=ix(t),x=Le({...Zl({client:ne,path:{name:t}}),enabled:!!t,staleTime:sn}).data?.connected===!0,f=Le({...ec({client:ne,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&x,staleTime:sn}),p=o.useMemo(()=>d.data?.series?.points??[],[d.data]),g=o.useMemo(()=>{const P=f.data;return new Map((P?.days??[]).map(q=>[q.date,q.sessions]))},[f.data]),y=o.useMemo(()=>{const P=S=>S.measured!==!1;if(p.length===0||P(p[0]))return null;const q=p.findIndex(P)-1;return q<0?{from:p[0].bucket,to:p[p.length-1].bucket}:{from:p[0].bucket,to:p[q].bucket}},[p]),v=d.data?.series?.coverageStart??null,C=d.data?.series?.trends,b=o.useMemo(()=>{const P=qr(C?.crawlerContentHits,p.length),q=qr(C?.aiUserFetchHits,p.length),S=qr(C?.aiReferralLandedHits,p.length);return p.map((V,F)=>({...V,crawlerContentHits:V.measured!==!1?cs(V.crawlerContentHits):null,aiUserFetchHits:V.measured!==!1?cs(V.aiUserFetchHits):null,aiReferralLandedHits:V.measured!==!1?cs(V.aiReferralLandedHits):null,ga4Visits:g.get(V.bucket)??null,crawlTrend:P[F],fetchTrend:q[F],visitTrend:S[F]}))},[p,g,C]),L=d.data?.totals,k=L&&{crawlers:cs(L.crawlerContentHits),fetches:cs(L.aiUserFetchHits),visits:cs(L.aiReferralLandedHits)},h=o.useMemo(()=>p.reduce((P,q)=>({crawlers:P.crawlers+cs(q.crawlerContentHits),fetches:P.fetches+cs(q.aiUserFetchHits),visits:P.visits+cs(q.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[p]),j=k??h,w=j.crawlers>0||j.fetches>0||j.visits>0;if(d.isLoading)return e.jsx(Ne,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(Ne,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!w){const P=m.data?.sources,q=P!==void 0&&P.length===0,S=!q&&v===null;return e.jsxs(Ne,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:q?"No server-side traffic source connected yet.":S?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:q?"Connect a traffic source to see how AI engines read this site over time.":S?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(Ne,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Mr,{label:"AI crawlers",value:rr(j.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Mr,{label:"AI page fetches",value:rr(j.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Mr,{label:"AI visitors",value:rr(j.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),p.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:cs(p[p.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:cs(p[p.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:cs(p[p.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:g.get(p[p.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Oe,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:P=>a(P.target.checked),className:"accent-current"}),"Page fetches"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:P=>l(P.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(on,{width:"100%",height:206,children:e.jsxs(ln,{data:b,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Na,{stroke:ba,vertical:!1}),e.jsx(cn,{dataKey:"bucket",tick:Vt,stroke:ms,tickFormatter:Pn,minTickGap:28}),e.jsx(dn,{tick:Vt,stroke:ms,width:48,allowDecimals:!1}),e.jsx(un,{contentStyle:rs.contentStyle,labelStyle:rs.labelStyle,itemStyle:rs.itemStyle,labelFormatter:Tt,formatter:Uo}),y&&e.jsx(oi,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(mr,{wrapperStyle:_o,iconType:"plainline",iconSize:14,formatter:P=>Ko.has(P)?"":P}),e.jsx(nn,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Lr,fill:Lr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(nn,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:$r,fill:$r,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Bs,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Lr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Bs,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:$r,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Oe,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(La,{windows:hp,value:i,onChange:c,label:"Visit measurement source",formatOption:P=>P==="ga4"?"GA4":P==="both"?"Both":"Server"})]}),e.jsx(on,{width:"100%",height:176,children:e.jsxs(ln,{data:b,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Na,{stroke:ba,vertical:!1}),e.jsx(cn,{dataKey:"bucket",tick:Vt,stroke:ms,tickFormatter:Pn,minTickGap:28}),e.jsx(dn,{tick:Vt,stroke:ms,width:48,allowDecimals:!1}),e.jsx(un,{contentStyle:rs.contentStyle,labelStyle:rs.labelStyle,itemStyle:rs.itemStyle,labelFormatter:Tt,formatter:Uo}),y&&e.jsx(oi,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(mr,{wrapperStyle:_o,iconType:"plainline",iconSize:14,formatter:P=>Ko.has(P)?"":P}),i!=="ga4"&&e.jsx(Bs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Fo,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Bs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Go,strokeWidth:1.8,strokeDasharray:"5 3",dot:xp(b.map(P=>P.ga4Visits),Go)}),r&&i!=="ga4"&&e.jsx(Bs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Fo,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const gp=6,Zn="__other__",Qn="_socialTotal";function fp(t,s=gp){const n=new Map;for(const u of t)n.set(u.source,(n.get(u.source)??0)+u.sessions);const a=[...n.entries()].sort((u,x)=>x[1]!==u[1]?x[1]-u[1]:u[0].localeCompare(x[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),c=new Map;for(const u of t){let x=c.get(u.date);x||(x={date:u.date,[Qn]:0},c.set(u.date,x));const f=l.has(u.source)?u.source:Zn;x[f]=(x[f]??0)+u.sessions,x[Qn]=(x[Qn]??0)+u.sessions}const d=[...c.values()].sort((u,x)=>String(u.date).localeCompare(String(x.date))),m=r.map(([u])=>u);return i>0&&m.push(Zn),{data:d,sources:m,otherCount:i}}function Hn(t){return t.replace(/\+/g," ")}function Fc(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Bo="_totalSessions",Vo="_organicSessions";function yp(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Bo]:i.sessions,[Vo]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[Bo]:0,[Vo]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),l=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:l}}const vp=["7d","30d","90d"],bp={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},tn=ct,yi=hs.textDim,Gc=hs.textFaint,ra=25;function jp(t){return Mi(t.landingPage)}const Np=25,wp=10,Er={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Ka(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function xr(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Sp({projectName:t}){const{data:s,isLoading:n,isError:a}=ox(t);if(n)return e.jsx(Ne,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(Ne,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!re()&&e.jsx(Ss,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(Ne,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!re()&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(Ne,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(l=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(fe,{tone:lx(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:l.lastSyncedAt?xr(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:re()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ss,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function Cp({projectName:t}){const[s,n]=o.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Sp,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(La,{windows:vp,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(kp,{projectName:t,window:s}),e.jsx(pp,{projectName:t,sinceMinutes:bp[s]})]})}function kp({projectName:t,window:s}){const n=xs(),a=s??"30d",[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!0),[u,x]=o.useState(!1),[f,p]=o.useState(!1),[g,y]=o.useState(null),[v,C]=o.useState(null),[b,L]=o.useState("sessions"),[k,h]=o.useState("desc"),[j,w]=o.useState("sessions"),[P,q]=o.useState("desc"),[S,V]=o.useState("sessions"),[F,D]=o.useState("desc"),[K,H]=o.useState("sessions"),[se,Q]=o.useState("desc"),[M,J]=o.useState(Er),[E,W]=o.useState([]),[T,ee]=o.useState([]),[_,ae]=o.useState(!1);async function ie(te){m(!0),y(null);try{const Ue=await n.fetchQuery({...Zl({client:ne,path:{name:t}}),staleTime:sn});if(te.current)return;if(l(Ue),!Ue.connected){c(null),J(Er),W([]),ee([]),m(!1);return}const qe=a==="all"?void 0:a,Ce=await n.fetchQuery({...Gd({client:ne,path:{name:t},query:qe?{window:qe}:void 0}),staleTime:sn}),gt=Ce.windowStart||Ce.windowEnd?{...Ce.windowStart?{startDate:Ce.windowStart}:{},...Ce.windowEnd?{endDate:Ce.windowEnd}:{}}:void 0,[Qt,Kt,Zt]=await Promise.all([n.fetchQuery({...ec({client:ne,path:{name:t},query:qe?{window:qe}:void 0}),staleTime:sn}).catch(()=>Er),n.fetchQuery({..._d({client:ne,path:{name:t},query:qe?{window:qe}:void 0}),staleTime:sn}).catch(()=>[]),n.fetchQuery({...Kd({client:ne,path:{name:t},query:gt}),staleTime:sn}).catch(()=>[])]);if(te.current)return;c(Ce),J(Qt),W(Kt),ee(Zt),m(!1)}catch(Ue){if(te.current)return;y(Ue instanceof Error?Ue.message:"Failed to load GA4 data"),m(!1)}}o.useEffect(()=>{const te={current:!1};return ie(te),()=>{te.current=!0}},[t,a,n]);async function Re(){x(!0),y(null),C(null);try{const te=await tc(t);C(`Synced ${te.rowCount.toLocaleString()} page rows, ${te.aiReferralCount.toLocaleString()} AI and ${te.socialReferralCount.toLocaleString()} social referral rows (${te.days} days)`),await Dt(n,"ga"),await ie({current:!1})}catch(te){y(te instanceof Error?te.message:"Sync failed")}finally{x(!1)}}async function X(){p(!0),y(null),C(null);try{await Ud(t),await Dt(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),C("GA4 disconnected")}catch(te){y(te instanceof Error?te.message:"Disconnect failed")}finally{p(!1)}}function ue(te){G.setPage(1),b===te?h(Ue=>Ue==="desc"?"asc":"desc"):(L(te),h("desc"))}function ve(te){j===te?q(Ue=>Ue==="desc"?"asc":"desc"):(w(te),q("desc"))}function Z(te){S===te?D(Ue=>Ue==="desc"?"asc":"desc"):(V(te),D("desc"))}const he=o.useMemo(()=>i?.topPages?[...i.topPages].sort((te,Ue)=>{const qe=te[b],Ce=Ue[b];return typeof qe=="string"&&typeof Ce=="string"?k==="asc"?qe.localeCompare(Ce):Ce.localeCompare(qe):k==="asc"?qe-Ce:Ce-qe}):[],[i?.topPages,b,k]),G=rn({rows:he,getSearchText:te=>Mi(te.landingPage),pageSize:wp}),me=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((te,Ue)=>{const qe=te[j],Ce=Ue[j];return typeof qe=="string"&&typeof Ce=="string"?P==="asc"?qe.localeCompare(Ce):Ce.localeCompare(qe):P==="asc"?qe-Ce:Ce-qe}):[],[i?.aiReferrals,j,P]),De=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((te,Ue)=>{const qe=te[K],Ce=Ue[K];return typeof qe=="string"&&typeof Ce=="string"?se==="asc"?qe.localeCompare(Ce):Ce.localeCompare(qe):se==="asc"?qe-Ce:Ce-qe}):[],[i?.aiReferralLandingPages,K,se]),ke=rn({rows:De,getSearchText:jp,pageSize:Np}),oe=ke.totalRows>0?`${ke.totalRows.toLocaleString()} ${ke.hasQuery?ke.totalRows===1?"match":"matches":ke.totalRows===1?"row":"rows"}`:ke.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function pe(te){ke.setPage(1),K===te?Q(Ue=>Ue==="desc"?"asc":"desc"):(H(te),Q("desc"))}const we=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((te,Ue)=>{const qe=te[S],Ce=Ue[S];return typeof qe=="string"&&typeof Ce=="string"?F==="asc"?qe.localeCompare(Ce):Ce.localeCompare(qe):F==="asc"?qe-Ce:Ce-qe}):[],[i?.socialReferrals,S,F]),{socialChartData:Ke,socialChartSources:Me,socialOtherCount:O}=o.useMemo(()=>{const te=fp(T);return{socialChartData:te.data,socialChartSources:te.sources,socialOtherCount:te.otherCount}},[T]),{chartData:U,chartSources:B,dateRange:Te}=o.useMemo(()=>{const te=yp(M,E);return{chartData:te.data,chartSources:te.sources,dateRange:te.dateRange}},[M,E]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return re()||is()?e.jsx(Ne,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Pp,{projectName:t,onConnected:()=>{(async()=>(await Dt(n,"ga"),await ie({current:!1})))()}});const He=i?.organicSharePctDisplay??"0%",Be=i?.channelBreakdown?.organic.sharePctDisplay??He,Ze=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,xe=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,jt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",_e=i?.paidAiSessionsBySession??0,et=i?.paidAiSharePctBySessionDisplay??"0%",zt=i?new Set(i.aiReferrals.map(te=>te.source.toLowerCase())).size:0,rt=me[0]??null,tt=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",Nt=i?.channelBreakdown?.direct.sessions??tt,_t=i?.channelBreakdown?.direct.sharePctDisplay??pt,Ve=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,A=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",$e=i?.socialSessions??0,Pe=i?.socialSharePctDisplay??"0%",ze=i?.channelBreakdown?.social.sessions??$e,wt=i?.channelBreakdown?.social.sharePctDisplay??Pe,it=i?new Set(i.socialReferrals.map(te=>te.source.toLowerCase())).size:0,Fe=we[0]??null;return e.jsxs(e.Fragment,{children:[g&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:g}),v&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:v}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!re()&&!is()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",disabled:u,onClick:Je(Re),children:[e.jsx(ja,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(R,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:f,onClick:Je(X),children:[e.jsx(Hh,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Oe,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Dr,{value:Ka(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Dr,{value:Ka(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${He} of total`,tone:"positive"}),e.jsx(Dr,{value:i.totalUsers===null?"—":Ka(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!re()&&!is()&&e.jsxs(R,{variant:"outline",size:"sm",disabled:u,onClick:Je(Re),children:[e.jsx(ja,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Oe,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),Te&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Te.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Te.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),U.length>0&&e.jsxs(Ne,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:B.length>0?"AI vs. total sessions":"All sessions (baseline)"}),B.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),B.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(on,{width:"100%",height:"100%",children:e.jsxs(ln,{data:U,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(cn,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Pn}),e.jsx(dn,{tick:Vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(un,{...rs,labelFormatter:Tt,formatter:(te,Ue)=>{const qe=typeof te=="number"?te.toLocaleString():String(te??0),Ce=String(Ue??"");return Ce==="_totalSessions"?[qe,"Total Sessions"]:Ce==="_organicSessions"?[qe,"Organic Sessions"]:[qe,Ce]}}),e.jsx(mr,{wrapperStyle:{fontSize:11,color:hs.text},formatter:te=>te==="_totalSessions"?"Total Sessions":te==="_organicSessions"?"Organic Sessions":te}),e.jsx(nn,{type:"monotone",dataKey:"_totalSessions",stroke:hs.textFaint,fill:hs.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),B.map((te,Ue)=>e.jsx(nn,{type:"monotone",dataKey:te,stackId:"ai",stroke:tn[Ue%tn.length],fill:tn[Ue%tn.length],fillOpacity:.4,strokeWidth:1.5},te))]})})})]}),e.jsxs(Ne,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(ws,{label:"Organic",value:Be,hint:`${Ze.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(ws,{label:"Social",value:wt,hint:`${ze.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(ws,{label:"Direct",value:_t,hint:`${Nt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(ws,{label:"Visitors from AI (at least)",value:jt,hint:_e>0?`${xe.toLocaleString()} sessions · ${_e.toLocaleString()} paid`:`${xe.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(ws,{label:"Other channels",value:A,hint:`${Ve.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),rt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:rt.source})," via ",rt.medium,", accounting for ",rt.sessions.toLocaleString()," sessions.",_e>0&&e.jsxs("span",{children:[" Paid AI: ",_e.toLocaleString()," sessions (",et,")."]})]})]}),e.jsxs(Ne,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${zt} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Source",sortKey:"source",current:j,dir:P,onSort:ve,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:j,dir:P,onSort:ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:j,dir:P,onSort:ve,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:me.map(te=>e.jsx(Tp,{referral:te},`${te.source}:${te.medium}:${te.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(Ne,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:oe})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Vs,{value:ke.query,onChange:ke.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),ke.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Landing Page",sortKey:"landingPage",current:K,dir:se,onSort:pe,align:"left"}),e.jsx(Et,{label:"Source",sortKey:"source",current:K,dir:se,onSort:pe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:K,dir:se,onSort:pe,align:"right"})]})}),e.jsx("tbody",{children:ke.rows.map(te=>e.jsx(Lp,{row:te},`${te.landingPage}:${te.source}:${te.medium}:${te.sourceDimension}`))})]})}),e.jsx(Ds,{page:ke.page,pageSize:ke.pageSize,visibleRows:ke.rows.length,totalRows:ke.totalRows,onPageChange:ke.setPage,itemLabel:ke.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>ke.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Oe,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(Ne,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ws,{label:"Social Sessions",value:Ka($e),hint:`${$e.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(ws,{label:"Share of Traffic",value:Pe,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(ws,{label:"Platforms",value:String(it),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Fe&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${Fe.source} via ${Fe.medium}`,children:Fc(Hn(Fe.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Fe.medium,children:["via ",Hn(Fe.medium)," · ",Fe.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ws,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(ws,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(ws,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),Ke.length>0&&e.jsxs(Ne,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),O>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Me.length-1," sources · ",O," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(on,{width:"100%",height:"100%",children:e.jsxs(ln,{data:Ke,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(cn,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Pn}),e.jsx(dn,{tick:Vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(un,{...rs,labelFormatter:Tt,formatter:(te,Ue)=>{const qe=typeof te=="number"?te.toLocaleString():String(te??0),Ce=String(Ue??"");if(Ce===Qn)return[qe,"Total Social"];if(Ce===Zn){const gt=`Other (${O} source${O===1?"":"s"})`;return[qe,gt]}return[qe,Hn(Ce)]}}),e.jsx(nn,{type:"monotone",dataKey:Qn,stroke:Gc,fill:hs.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Me.map((te,Ue)=>{const Ce=te===Zn?yi:tn[Ue%tn.length];return e.jsx(nn,{type:"monotone",dataKey:te,stackId:"social",stroke:Ce,fill:Ce,fillOpacity:.4,strokeWidth:1.5},te)})]})})}),e.jsx(qp,{sources:Me,otherCount:O})]}),e.jsxs(Ne,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?we.length>ra&&!_?`Top ${ra} of ${we.length}`:`${we.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Source",sortKey:"source",current:S,dir:F,onSort:Z,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:S,dir:F,onSort:Z,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:S,dir:F,onSort:Z,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(_?we:we.slice(0,ra)).map(te=>e.jsx($p,{referral:te},`${te.source}:${te.medium}:${te.channelGroup}`))})]})}),we.length>ra&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ae(te=>!te),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:_?`Show top ${ra}`:`Show all ${we.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Oe,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Vs,{value:G.query,onChange:G.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Landing Page",sortKey:"landingPage",current:b,dir:k,onSort:ue,align:"left"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:b,dir:k,onSort:ue,align:"right"}),e.jsx(Et,{label:"Organic",sortKey:"organicSessions",current:b,dir:k,onSort:ue,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:G.rows.map(te=>e.jsx(Ip,{page:te},te.landingPage))})]})}),G.totalRows===0&&G.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Ds,{page:G.page,pageSize:G.pageSize,visibleRows:G.rows.length,totalRows:G.totalRows,onPageChange:G.setPage,itemLabel:G.hasQuery?"matches":"pages"})]})]}),e.jsx(Rp,{projectName:t}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${xr(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}const Ap=25,_c="n/a",bt={heading:"Google organic search traffic",tooltip:`GA4's "Google organic search traffic: Landing page + query string" report, from the property's Search Console link. Each window ends yesterday in the property time zone, as GA4's own date ranges do. The Total row is GA4's own total for all pages, not a sum of the rows, and it does not change with the filter. Search Console data arrives about two days late.`,windowLabel:"Google organic search time period",loading:"Loading Google organic search pages…",loadError:"Could not load Google organic search pages.",neverSynced:"No Google organic search data has been synced yet.",neverSyncedAction:"Sync GA4 to load the Search Console landing-page report.",unavailable:"GA4 did not return Search Console data for this property.",unavailableAction:"Link Search Console to this GA4 property (Admin, Product links, Search Console links), then sync GA4 again.",refreshFailed:"The last refresh failed.",noSearchTraffic:"No landing pages had Google organic search traffic in this window.",noSearchTrafficAction:"If this property should have some, check its Search Console link in GA4 (Admin, Product links, Search Console links).",thresholded:"GA4 applied thresholding to this report, so it may withhold some rows.",retry:"Retry",refreshFailedBadge:"Last refresh failed",unavailableBadge:"Search Console unavailable",thresholdedBadge:"Thresholded",previousSnapshot:"Showing the last good snapshot, synced",totalLabel:"Total",totalScope:"all pages",noFilterMatch:"No landing pages match this filter",noFilterMatchInLoaded:t=>`No landing pages in the top ${t.toLocaleString()} by clicks match this filter. The filter searches only the pages loaded here.`};function zo(t,s){switch(s){case"landingPage":return t.landingPage;case"clicks":return t.organicGoogleSearchClicks;case"impressions":return t.organicGoogleSearchImpressions;case"ctr":return t.organicGoogleSearchClickThroughRate;case"position":return t.organicGoogleSearchAveragePosition;case"activeUsers":return t.activeUsers}}function Qo(t){return t===null?_c:t.toFixed(1)}function Ho(t){return t===null?_c:Xe(t)}function Rp({projectName:t}){const[s,n]=o.useState(Bd),[a,r]=o.useState("clicks"),[l,i]=o.useState("desc"),c=Le({...Vd({client:ne,path:{name:t},query:{window:s,limit:Wd}}),staleTime:sn}),d=c.data,m=o.useMemo(()=>[...d?.rows??[]].sort((y,v)=>{const C=zo(y,a),b=zo(v,a);return C===null||b===null?C===b?0:C===null?1:-1:typeof C=="string"&&typeof b=="string"?l==="asc"?C.localeCompare(b):b.localeCompare(C):l==="asc"?C-b:b-C}),[d?.rows,a,l]),u=rn({rows:m,getSearchText:g=>Mi(wr(g.landingPage)),pageSize:Ap});function x(g){u.setPage(1),a===g?i(y=>y==="desc"?"asc":"desc"):(r(g),i(g==="landingPage"?"asc":"desc"))}const f=d?.total??null,p=!re()&&!is();return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{"aria-labelledby":"ga-search-landing-heading",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Search Console link"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"ga-search-landing-heading",className:"text-base font-semibold text-primary",children:bt.heading}),e.jsx(Oe,{text:bt.tooltip})]}),d?.windowStart&&d.windowEnd&&e.jsxs("p",{className:"text-sm text-secondary mt-1",children:[lo(d.windowStart)," to ",lo(d.windowEnd),d.timeZone?` (${d.timeZone})`:""]})]}),e.jsx(La,{windows:zd,value:s,onChange:g=>{u.setPage(1),n(g)},label:bt.windowLabel})]}),c.isPending?e.jsx("p",{className:"text-sm text-secondary py-6 text-center",children:bt.loading}):c.isError||!d?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:[e.jsx("span",{children:bt.loadError}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>{c.refetch()},children:bt.retry})]}):e.jsxs(e.Fragment,{children:[(d.status==="error"||d.status==="unavailable"||d.subjectToThresholding)&&e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2","data-testid":"ga-search-landing-status",children:[d.status==="error"&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(fe,{tone:"negative",children:bt.refreshFailedBadge}),d.error&&e.jsx(Oe,{text:d.error})]}),d.status==="unavailable"&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(fe,{tone:"caution",children:bt.unavailableBadge}),d.error&&e.jsx(Oe,{text:d.error})]}),d.subjectToThresholding&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(fe,{tone:"caution",children:bt.thresholdedBadge}),e.jsx(Oe,{text:bt.thresholded})]}),d.status!=="ready"&&f&&d.syncedAt&&e.jsxs("span",{className:"text-sm text-secondary",children:[bt.previousSnapshot," ",xr(d.syncedAt),"."]}),d.status==="unavailable"&&f&&e.jsx("p",{className:"w-full text-sm text-secondary",children:bt.unavailableAction})]}),f?e.jsxs(e.Fragment,{children:[e.jsx(Vs,{value:u.query,onChange:u.setQuery,label:"Filter Google organic search landing pages",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm","aria-labelledby":"ga-search-landing-heading",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Landing page",sortKey:"landingPage",current:a,dir:l,onSort:x,align:"left"}),e.jsx(Et,{label:"Clicks",sortKey:"clicks",current:a,dir:l,onSort:x,align:"right"}),e.jsx(Et,{label:"Impressions",sortKey:"impressions",current:a,dir:l,onSort:x,align:"right"}),e.jsx(Et,{label:"CTR",sortKey:"ctr",current:a,dir:l,onSort:x,align:"right"}),e.jsx(Et,{label:"Avg. position",sortKey:"position",current:a,dir:l,onSort:x,align:"right"}),e.jsx(Et,{label:"Active users",sortKey:"activeUsers",current:a,dir:l,onSort:x,align:"right"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-t border-subtle font-semibold","data-testid":"ga-search-landing-total",children:[e.jsxs("td",{className:"py-1.5 text-primary",children:[bt.totalLabel," ",e.jsx("span",{className:"font-normal text-secondary",children:bt.totalScope})]}),e.jsx("td",{className:"py-1.5 text-right text-primary tabular-nums",children:f.organicGoogleSearchClicks.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-primary tabular-nums",children:f.organicGoogleSearchImpressions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-primary tabular-nums",children:Ho(f.organicGoogleSearchClickThroughRate)}),e.jsx("td",{className:"py-1.5 text-right text-primary tabular-nums",children:Qo(f.organicGoogleSearchAveragePosition)}),e.jsx("td",{className:"py-1.5 text-right text-primary tabular-nums",children:f.activeUsers.toLocaleString()})]}),u.rows.map(g=>e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:wr(g.landingPage),children:wr(g.landingPage)}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:g.organicGoogleSearchClicks.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:g.organicGoogleSearchImpressions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:Ho(g.organicGoogleSearchClickThroughRate)}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:Qo(g.organicGoogleSearchAveragePosition)}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:g.activeUsers.toLocaleString()})]},g.landingPage))]})]})}),!Qd(f)&&e.jsxs("div",{className:"text-sm text-secondary mt-3 space-y-1",children:[e.jsx("p",{children:bt.noSearchTraffic}),e.jsx("p",{children:bt.noSearchTrafficAction})]}),u.totalRows===0&&u.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:d.totalRows>d.rows.length?bt.noFilterMatchInLoaded(d.rows.length):bt.noFilterMatch}),e.jsx(Ds,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?"matches":"pages"}),(d.totalRows>d.rows.length||d.rowsCapped)&&e.jsxs("p",{className:"text-sm text-secondary mt-3",children:[d.totalRows>d.rows.length?`Showing the top ${d.rows.length.toLocaleString()} of ${d.totalRows.toLocaleString()} stored pages by clicks.`:"",d.totalRows>d.rows.length&&d.rowsCapped?" ":"",d.rowsCapped&&d.reportRowCount!==null?`GA4 reported ${d.reportRowCount.toLocaleString()} pages; the ${d.totalRows.toLocaleString()} with the most clicks are stored.`:""]}),d.syncedAt&&e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Synced ",xr(d.syncedAt)]})]}):e.jsx(Ne,{className:"p-5",children:d.status==="unavailable"?e.jsxs("div",{className:"text-sm text-secondary space-y-1",children:[e.jsx("p",{className:"text-neutral",children:bt.unavailable}),e.jsx("p",{children:bt.unavailableAction})]}):d.status==="error"?e.jsxs("div",{className:"text-sm text-secondary space-y-1",children:[e.jsx("p",{className:"text-neutral",children:bt.refreshFailed}),d.error&&e.jsx("p",{children:d.error})]}):e.jsxs("div",{className:"text-sm text-secondary space-y-1",children:[e.jsx("p",{className:"text-neutral",children:bt.neverSynced}),p&&e.jsx("p",{children:bt.neverSyncedAction})]})})]})]})]})}function Pp({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!1),[u,x]=o.useState(null),f=o.useRef(null),p=o.useCallback(y=>{const v=y.target.files?.[0];if(!v)return;x(null),l(v.name);const C=new FileReader;C.onload=()=>{const b=C.result;try{const L=JSON.parse(b);if(!L.client_email||!L.private_key){x("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(b)}catch{x("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},C.onerror=()=>{x("Failed to read file."),c(null)},C.readAsText(v)},[]);async function g(){if(x(null),!n.trim()){x("Property ID is required.");return}if(!i){x("Please upload a service account key file.");return}m(!0);try{await Hd(t,{propertyId:n.trim(),keyJson:i});try{await tc(t)}catch{}s()}catch(y){x(y instanceof Error?y.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(Ne,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),u&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:u}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:y=>a(y.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:f,type:"file",accept:".json,application/json",onChange:p,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>f.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(Wh,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(R,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Je(g),children:d?"Connecting & syncing…":"Connect GA4"})]})}function Et({label:t,sortKey:s,current:n,dir:a,onSort:r,align:l}){const i=n===s;return e.jsx("th",{className:`py-1 ${l==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${i?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,i&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Kc={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Dr({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${Kc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function ws({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Oe,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Kc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Ip({page:t}){const s=Xe(t.organicShare);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}const Uc={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Bc={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function Tp({referral:t}){const s=Xe(t.share),n=Uc[t.sourceDimension]??t.sourceDimension,a=Bc[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",l=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:l,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:a,children:n})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}function Lp({row:t}){const s=Uc[t.sourceDimension]??t.sourceDimension,n=Bc[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(or,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function $p({referral:t}){const s=Xe(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Hn(t.source),r=Hn(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:n})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}function qp({sources:t,otherCount:s}){const n=[{key:Qn,color:Gc,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Zn)n.push({key:Zn,color:yi,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Hn(r);n.push({key:r,color:tn[a%tn.length]??yi,label:Fc(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Mp(t){const s=t.details;if(t.code!=="FORBIDDEN"||!s||s.reason!=="gsc-api-disabled")return null;const n=typeof s.projectNumber=="string"?s.projectNumber:void 0;return{title:"Enable the Search Console API",message:`Your Google Cloud project${n?` (${n})`:""} hasn't enabled the Search Console API. Enable the Search Console API and the Indexing API, wait ~2–5 minutes, then retry.`,enableUrl:typeof s.enableUrl=="string"?s.enableUrl:void 0,indexingApiUrl:typeof s.indexingApiUrl=="string"?s.indexingApiUrl:void 0,projectNumber:n}}const Ep="Search Console is not connected yet. Your Canonry team can set this up.",Dp=["7d","30d","90d","all"],Ua=500,Wo=[{key:"clicks",label:"Clicks",color:ct[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:ct[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:ta.caution,format:t=>Xe(t)},{key:"position",label:"Avg position",color:ct[2],inverted:!0,format:t=>t.toFixed(1)}],Zs=25,Op="canonry:google-oauth-complete";function Fp(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const i=t.prior[s],c=t.trailing[s];return i!==null&&c!==null&&i<=0&&c>0?`new in the last ${a}d`:i===null||i<=0?`no prior ${a}d to compare`:c===null?`no value in the last ${a}d`:"comparison unavailable"}return r===0?`→ no change vs prior ${a}d`:`${(n?r<0:r>0)?"↑":"↓"} ${Xe(Math.abs(r))} vs prior ${a}d`}function Gp(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,l=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${l} (${c}) with the ${s} ${l} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Yo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Jo(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function Xo(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function _p({projectName:t,refreshNonce:s}){const n=xs(),{isAdmin:a}=Hs(),r=is(),[l,i]=o.useState(!1),[c,d]=o.useState([]),[m,u]=o.useState([]),[x,f]=o.useState([]),[p,g]=o.useState(null),[y,v]=o.useState([]),[C,b]=o.useState([]),[L,k]=o.useState(null),[h,j]=o.useState(""),[w,P]=o.useState(""),[q,S]=o.useState("30"),[V,F]=o.useState(!1),[D,K]=o.useState("30d"),[H,se]=o.useState(["clicks","impressions"]),[Q,M]=o.useState(!0),[J,E]=o.useState(null),[W,T]=o.useState(0),[ee,_]=o.useState({startDate:"",endDate:"",query:"",page:""}),[ae,ie]=o.useState(0),[Re,X]=o.useState(!1),[ue,ve]=o.useState(0),[Z,he]=o.useState(!1),[G,me]=o.useState(""),[De,ke]=o.useState(!0),[oe,pe]=o.useState(!1),[we,Ke]=o.useState(!1),[Me,O]=o.useState(!1),[U,B]=o.useState(!1),[Te,He]=o.useState(!1),[Be,Ze]=o.useState(!1),[xe,jt]=o.useState(null),[_e,et]=o.useState(!1),[zt,rt]=o.useState(!1),[tt,pt]=o.useState(null),[Nt,_t]=o.useState(null),[Ve,A]=o.useState([]),[$e,Pe]=o.useState(new Set),[ze,wt]=o.useState({}),[it,Fe]=o.useState(new Set),[te,Ue]=o.useState(""),[qe,Ce]=o.useState(null),[gt,Qt]=o.useState(""),[Kt,Zt]=o.useState(!1),[It,vt]=o.useState(!1),[ps,dt]=o.useState(!1),[gs,Fs]=o.useState(!1),[St,Gs]=o.useState("indexed"),[Lt,fs]=o.useState(null),es=!!(ee.query.trim()||ee.page.trim()||Lt),ts=Lt!==null,xt=o.useMemo(()=>{if(!Lt)return x;const{key:N,dir:Y}=Lt;return[...x].sort((de,be)=>{const nt=N===An.CTR?Number.isFinite(de.ctr)?de.ctr:0:de[N],st=N===An.CTR?Number.isFinite(be.ctr)?be.ctr:0:be[N];return Y==="asc"?nt-st:st-nt})},[x,Lt]),Ht=rn({rows:xt,pageSize:Ks}),ss=Z?Ht.rows:xt,ns=rn({rows:(tt??[]).filter(N=>N.path.toLowerCase().includes(te.trim().toLowerCase())),pageSize:Ks}),[$t,ys]=o.useState([]),[ot,At]=o.useState(null),[vs,z]=o.useState(1),le=o.useMemo(()=>{if($t.length<2)return null;const N=$t[$t.length-1],Y=$t[$t.length-2];return{indexed:N.indexed-Y.indexed,notIndexed:N.notIndexed-Y.notIndexed}},[$t]);o.useEffect(()=>{z(1)},[xe,St,ot]);const Ae=o.useMemo(()=>ot?(xe?.reasonGroups??[]).find(N=>N.reason===ot):void 0,[xe,ot]),ce=o.useMemo(()=>xe?St==="indexed"?xe.indexed:St==="deindexed"?xe.deindexed:St==="notIndexed"?ot?Ae?.urls??[]:(xe.reasonGroups??[]).length===0?xe.notIndexed:[]:[]:[],[xe,St,ot,Ae]),ge=Math.max(1,Math.ceil(ce.length/Zs)),Ge=Math.min(Math.max(1,vs),ge),mt=(Ge-1)*Zs,Rt=o.useMemo(()=>xe?.indexed.slice(mt,mt+Zs)??[],[xe,mt]),bs=o.useMemo(()=>xe?.notIndexed.slice(mt,mt+Zs)??[],[xe,mt]),$=o.useMemo(()=>xe?.deindexed.slice(mt,mt+Zs)??[],[xe,mt]),Se=o.useMemo(()=>(Ae?.urls??[]).slice(mt,mt+Zs),[Ae,mt]),[lt,Pt]=o.useState(!1),[qt,Qe]=o.useState(null),[ft,Ws]=o.useState(null),[$a,os]=o.useState(null);function qa(N,Y){const de=cx(N),be=Mp(de);be?(Ws(be),Qe(null)):(Ws(null),Qe(de.message||Y))}const Ft=c.find(N=>N.connectionType==="gsc"),as=(Ft?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Tn=Ve.length>0?Ve:(tt??[]).map(N=>N.path),Ma=Tn.filter(N=>tt?.some(Y=>Y.path===N&&Y.isSitemapsIndex)).length,Ys=Ma===1?"Resubmit sitemap index":Ma>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",js=x.length>0||y.length>0||C.length>0,_s=Yd(),Ln=Jd();async function mn(N,Y=!1){if(r){u([]);return}if(!N){u([]),j("");return}Ke(!0);try{const{sites:de}=await n.fetchQuery({...mu({client:ne,path:{name:t}}),staleTime:Y?0:Jt});u(de),j(N.propertyId??de[0]?.siteUrl??""),Ws(null)}catch(de){u([]),qa(de,"Failed to load Search Console properties")}finally{Ke(!1)}}async function hn(N){B(!0);const Y=N??ae;try{const de=es?Ua:Ks,be=es?0:Y,nt={limit:String(de)};ee.startDate&&(nt.startDate=ee.startDate),ee.endDate&&(nt.endDate=ee.endDate),ee.query&&(nt.query=ee.query),ee.page&&(nt.page=ee.page),be>0&&(nt.offset=String(be)),D&&D!=="all"&&!ee.startDate&&(nt.window=D);const st=await n.fetchQuery({...tu({client:ne,path:{name:t},query:nt}),staleTime:Jt}),ht=st.rows;es?(X(!1),f(ht),ve(ht.length),he(!0)):(X(be+ht.length<st.totalMatching),f(ht),ve(0),he(!1))}catch(de){f([]),X(!1),ve(0),Qe(de instanceof Error?de.message:"Failed to load GSC performance data")}finally{B(!1)}}async function xn(){try{const N={};ee.startDate&&(N.startDate=ee.startDate),ee.endDate&&(N.endDate=ee.endDate),D&&D!=="all"&&!ee.startDate&&(N.window=D);const Y=await n.fetchQuery({...eu({client:ne,path:{name:t},query:N}),staleTime:Jt});g(Y)}catch{g(null)}}async function pn(N=!1){He(!0);try{const Y=G.trim()||void 0,de={limit:"20"};Y&&(de.url=Y);const[be,nt]=await Promise.all([n.fetchQuery({...du({client:ne,path:{name:t},query:de}),staleTime:N?0:Jt}),n.fetchQuery({...uu({client:ne,path:{name:t}}),staleTime:N?0:Jt})]);v(be),b(nt)}catch(Y){v([]),b([]),Qe(Y instanceof Error?Y.message:"Failed to load GSC inspection history")}finally{He(!1)}}async function $n(N=!1){et(!0);try{const[Y,de]=await Promise.all([n.fetchQuery({...au({client:ne,path:{name:t}}),staleTime:N?0:Jt}),n.fetchQuery({...ru({client:ne,path:{name:t}}),staleTime:N?0:Jt}).catch(()=>[])]);jt(Y),ys(de)}catch(Y){jt(null),ys([]),Qe(Y instanceof Error?Y.message:"Failed to load coverage data")}finally{et(!1)}}async function Ea(N){Pt(!0),Qe(null);try{const Y=await uo(t,{urls:N}),{succeeded:de,failed:be,total:nt}=Y.summary;Ee({title:"Indexing requested",detail:be===0?`${de} URL${de!==1?"s":""} submitted for indexing.`:`${de}/${nt} submitted successfully, ${be} failed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(Y){Qe(Y instanceof Error?Y.message:"Failed to request indexing")}finally{Pt(!1)}}async function sa(){Pt(!0),Qe(null);try{const N=await uo(t,{urls:[],allUnindexed:!0}),{succeeded:Y,failed:de,total:be}=N.summary;Ee({title:"Indexing requested",detail:de===0?`${Y} unindexed URL${Y!==1?"s":""} submitted for indexing.`:`${Y}/${be} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(N){Qe(N instanceof Error?N.message:"Failed to request indexing")}finally{Pt(!1)}}async function Da(){rt(!0),Qe(null);try{const N=await Sr(t);n.setQueryData(iu({client:ne,path:{name:t}}),N),pt(N.sitemaps),_t(N.summary),A(N.preferredSubmissionUrls),Pe(new Set),wt({}),N.sitemaps.length===0&&os("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(N){Qe(N instanceof Error?N.message:"Failed to list sitemaps")}finally{rt(!1)}}async function so(N){const Y=$e.has(N);if(Pe(de=>{const be=new Set(de);return Y?be.delete(N):be.add(N),be}),!(Y||ze[N])){Fe(de=>new Set(de).add(N));try{const de=await Sr(t,N);wt(be=>({...be,[N]:de.sitemaps}))}catch(de){Qe(de instanceof Error?de.message:"Failed to load sitemap files")}finally{Fe(de=>{const be=new Set(de);return be.delete(N),be})}}}async function Cs(N){if(!as||N.length===0)return;const Y=[...new Set(N)];vt(!0),Qe(null),Ce({completed:0,total:Y.length});let de=0,be=0,nt=0,st=null;try{for(let Mt=0;Mt<Y.length;Mt+=50){const ut=Y.slice(Mt,Mt+50);try{const Ie=await ou(t,ut);de+=Ie.summary.accepted,be+=Ie.summary.failed,nt+=ut.length,Ce({completed:nt,total:Y.length})}catch(Ie){nt+=ut.length;const ks=ut.length,Xs=Y.length-nt,En=Ie instanceof Error?Ie.message:"The batch request failed",Ns=`${de} accepted, ${be} failed, ${ks} unconfirmed, ${Xs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;st=`Sitemap submission stopped after a batch request failed. ${Ns} ${En}`,Qe(st),Ee({title:"Sitemap resubmission partially completed",detail:Ns,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const ht=Y.length;Ee({title:be===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:be===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${de}/${ht} sitemap submissions; ${be} failed. Indexing is not guaranteed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Qt("")}catch(ht){Qe(ht instanceof Error?ht.message:"Failed to submit sitemap to Google")}finally{vt(!1),Ce(null),await Da(),st&&Qe(st)}}async function vr(){vt(!0);const N=tt??[];try{const Y=N.filter(be=>be.isSitemapsIndex),de=[];for(let be=0;be<Y.length;be+=4)(await Promise.all(Y.slice(be,be+4).map(async st=>{const ht=ze[st.path];if(ht)return ht;const Mt=await Sr(t,st.path);return wt(ut=>({...ut,[st.path]:Mt.sitemaps})),Mt.sitemaps}))).forEach((st,ht)=>{de.push(...st.length>0?st.map(Mt=>Mt.path):[Y[be+ht].path])});await Cs([...N.filter(be=>!be.isSitemapsIndex).map(be=>be.path),...de])}catch(Y){Qe(Y instanceof Error?Y.message:"Failed to load sitemap files"),vt(!1)}}async function Js(N){Zt(!0),Qe(null);try{await lu(t,"gsc",N),await Dt(n,"google"),d(Y=>Y.map(de=>de.connectionType==="gsc"?{...de,sitemapUrl:N}:de)),Ee({title:"Default sitemap updated",detail:N,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(Y){Qe(Y instanceof Error?Y.message:"Failed to set the default sitemap")}finally{Zt(!1)}}async function gn(N){try{await Ln.mutateAsync({projectName:t,projectLabel:t,opts:N?{sitemapUrl:N}:void 0})}catch{}}async function qn(){ke(!0),Qe(null);try{const[N,Y]=await Promise.all([r||!a?Promise.resolve(null):sc().catch(()=>null),n.fetchQuery({...Ti({client:ne,path:{name:t}}),staleTime:Jt}).catch(()=>[])]);i(!!N?.google?.configured),d(Y);const de=Y.find(be=>be.connectionType==="gsc");await Promise.all([r?Promise.resolve():mn(de),hn(),xn(),pn(),$n(),!r&&de?.propertyId?Da():Promise.resolve()])}finally{ke(!1)}}o.useEffect(()=>{qn()},[t,s,a]),o.useEffect(()=>{ie(0),E(null),_(N=>N.startDate||N.endDate?{...N,startDate:"",endDate:""}:N),T(N=>N+1),xn()},[D]);const fn=o.useRef(!1);o.useEffect(()=>{if(!fn.current){fn.current=!0;return}ie(0),Ht.setPage(1),hn(0)},[W]);function yn(N){const Y=J===N?null:N;E(Y),_(de=>({...de,startDate:Y??"",endDate:Y??""})),T(de=>de+1)}const Mn=o.useRef(!1);o.useEffect(()=>{if(!Mn.current){Mn.current=!0;return}ie(0),hn(0)},[ts]);async function na(){if(!l){Qe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}pe(!0),Qe(null),os(null);try{let N=function(Ie){if(Ie.source!==be||Ie.origin!==nt||!Ie.data||typeof Ie.data!="object")return;const ks=Ie.data;ks.type!==Op||ks.connectionType!=="gsc"||ut(!0)};const{authUrl:Y,redirectUri:de}=await nu(t,"gsc");if(!Y.startsWith("https://accounts.google.com/")){Qe("Unexpected OAuth redirect URL. Please try again.");return}const be=window.open(Y,"_blank","width=600,height=700");if(!be){window.location.assign(Y);return}const nt=de?new URL(de).origin:window.location.origin;let st=!1,ht=null;const Mt=()=>{ht!==null&&window.clearInterval(ht),window.removeEventListener("message",N)},ut=async Ie=>{if(!st){st=!0,Mt(),os(Ie?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Dt(n,"google"),await qn()}finally{os(null)}}};window.addEventListener("message",N),os("Finish the Google consent flow in the popup. This page will refresh automatically."),ht=window.setInterval(()=>{be.closed&&ut(!1)},1e3)}catch(N){Qe(N instanceof Error?N.message:"Failed to start OAuth flow")}finally{pe(!1)}}async function br(){Qe(null),os(null);try{await su(t,"gsc"),await Dt(n,"google"),d(N=>N.filter(Y=>Y.connectionType!=="gsc")),u([]),j("")}catch(N){Qe(N instanceof Error?N.message:"Failed to disconnect")}}async function jr(){if(h){O(!0),Qe(null);try{await hu(t,"gsc",h),await Dt(n,"google"),d(N=>N.map(Y=>Y.connectionType==="gsc"?{...Y,propertyId:h}:Y)),Ee({title:"GSC property updated",detail:`${t} is now linked to ${h}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(N){Qe(N instanceof Error?N.message:"Failed to save GSC property")}finally{O(!1)}}}async function no(){Qe(null),os(null);try{await _s.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(q,10)||void 0,full:V||void 0}}),await Dt(n,"gsc")}catch{}}async function vn(){if(w.trim()){Ze(!0),Qe(null),os(null);try{const N=await cu(t,w.trim());await Dt(n,"gsc"),k(N),P(""),await pn()}catch(N){Qe(N instanceof Error?N.message:"Failed to inspect URL")}finally{Ze(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),ft&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:ft.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:ft.message}),(Dn(ft.enableUrl)||Dn(ft.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Dn(ft.enableUrl)&&e.jsx("a",{href:Dn(ft.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Dn(ft.indexingApiUrl)&&e.jsx("a",{href:Dn(ft.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>Ws(null),children:"×"})]})}),qt&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[qt,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Qe(null),children:"×"})]}),$a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-sm text-positive",children:[$a,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>os(null),children:"×"})]}),De?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ft?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:Ft.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",xe?.lastInspectedAt?Xt(xe.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Je(br),children:"Disconnect"})]}):a?e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(fe,{tone:l?"caution":"negative",children:l?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:l?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[l?e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:oe,onClick:Je(na),children:oe?"Opening…":"Connect Google Search Console"}):e.jsx(R,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ss,{to:"/settings",children:"Open Settings"})}),!l&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(Ne,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:Ep})}),(Ft||js)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Oe,{text:`${Gp(p?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${Ua.toLocaleString()} matching rows while the table shows ${Ks} per page.`})]}),p?.window?.startDate&&p.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[p.window.startDate," to ",p.window.endDate,(p.window.daysSinceLatestData??0)>0&&` · latest data ${p.window.daysSinceLatestData} day${p.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{windows:Dp,value:D,onChange:N=>{K(N),ie(0),Ht.setPage(1)},label:"Search Console time period",formatOption:N=>N==="all"?"All":N}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:U,onClick:()=>{ie(0),Ht.setPage(1),hn(0),xn()},children:U?"Loading…":"Apply filters"})]})]}),p&&p.daily.length>0&&(()=>{const{totals:N,daily:Y,trends:de,periodComparison:be}=p,st=Wo.filter(Ie=>H.includes(Ie.key)).map(Ie=>({dataKey:Ie.key,label:Ie.label,color:Ie.color,axisId:Ie.key,inverted:Ie.inverted,formatValue:Ie.format,trend:Q?de?.[Ie.key]??null:null})),ht=Ie=>N[Ie]??null,Mt=new Map(Y.map(Ie=>[Ie.date,Ie])),ut=Y.length===0?[]:Xd(Y[0].date,Y[Y.length-1].date).map(Ie=>Mt.get(Ie)??{date:Ie});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Wo.map(Ie=>{const ks=H.includes(Ie.key),Xs=ht(Ie.key),En=Xs===null;return e.jsxs("button",{type:"button","aria-pressed":ks,disabled:En,className:`rounded-md border px-3 py-2 text-left transition-colors ${ks?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${En?"cursor-not-allowed opacity-50":""}`,onClick:()=>{se(Ns=>Ns.includes(Ie.key)?Ns.length===1?Ns:Ns.filter(aa=>aa!==Ie.key):[...Ns,Ie.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:ks?Ie.color:"transparent",border:`1px solid ${Ie.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Ie.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Xs===null?"—":Ie.format(Xs)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Fp(be,Ie.key,Ie.inverted)})]},Ie.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:Q,onChange:Ie=>M(Ie.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Nc,{data:ut,xKey:"date",series:st,xTickFormatter:Pn,labelFormatter:Tt,onSelectX:yn,selectedX:J})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:Y.map(Ie=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":J===Ie.date,onClick:()=>yn(Ie.date),children:[Tt(Ie.date),": ",Ie.clicks," clicks, ",Ie.impressions," impressions"]},Ie.date))}),J&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Tt(J)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>yn(J),children:["Show all ",N.days," days"]})]}),N.position!==null&&(N.positionDays??N.days)<N.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",N.positionDays," of ",N.days," days. The rest have no property-level position recorded."]}),(N.position===null||N.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:ee.startDate,onChange:N=>_(Y=>({...Y,startDate:N.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:ee.endDate,onChange:N=>_(Y=>({...Y,endDate:N.target.value}))}),e.jsx(Vs,{value:ee.query,onChange:N=>_(Y=>({...Y,query:N})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Vs,{value:ee.page,onChange:N=>_(Y=>({...Y,page:N})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),x.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(An).map(N=>e.jsx("th",{className:"text-right","aria-sort":Lt?.key===N?Lt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{Ht.setPage(1),fs(Y=>Y?.key===N?Y.dir==="desc"?{key:N,dir:"asc"}:null:{key:N,dir:"desc"})},children:[Zd[N],Lt?.key===N?Lt.dir==="desc"?" ↓":" ↑":""]})},N))]})}),e.jsx("tbody",{children:ss.map((N,Y)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:N.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:N.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(or,{value:N.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:N.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.impressions.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Xe(N.ctr)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.position.toFixed(1)})]},`${N.date}:${N.query}:${N.page}:${Y}`))})]})}),e.jsx(Ds,{page:Z?Ht.page:Math.floor(ae/Ks)+1,pageSize:Ks,visibleRows:ss.length,totalRows:Z?ue:void 0,hasNextPage:Z?void 0:Re,disabled:U,itemLabel:Z?"matches":"rows",onPageChange:N=>{if(Z){Ht.setPage(N);return}const Y=(N-1)*Ks;ie(Y),hn(Y)}}),Z&&ue>=Ua?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Ua.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Oe,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[xe&&xe.notIndexed.length>0&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:()=>{sa()},children:lt?"Requesting…":`Request indexing (${xe.notIndexed.length})`}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:_e,onClick:()=>{$n(!0)},children:_e?"Loading…":"Reload saved coverage"})]})]}),xe&&xe.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const N=xe.summary.indexedShare??0,Y=xe.summary.notIndexedShare??0,de=54,be=2*Math.PI*de,nt=be*(1-N),st=be*Y,ht=be*N;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:hs.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:ta.positiveDeep,strokeWidth:"14",strokeDasharray:be,strokeDashoffset:nt,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),xe.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:hs.textFaint,strokeWidth:"14",strokeDasharray:`${st} ${be-st}`,strokeDashoffset:-ht,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-3xl font-bold tabular-nums text-primary",children:Xe(xe.summary.indexedShare)}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:xe.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:xe.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(xe.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(xe.reasonGroups??[]).length," ",(xe.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),xe.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:xe.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(N=>{const Y=N==="indexed"?xe.indexed.length:N==="notIndexed"?xe.notIndexed.length:xe.deindexed.length,de=N==="indexed"?"Indexed":N==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":St===N,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${St===N?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Gs(N),At(null)},children:[de," (",Y,")"]},N)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[St==="indexed"&&xe.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:Rt.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.crawlTime?N.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:N.isMobileFriendly===!0?"Yes":N.isMobileFriendly===!1?"No":"—"})]},N.id))})]}),St==="notIndexed"&&!ot&&(xe.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(xe.reasonGroups??[]).map(N=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>At(N.reason),onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),At(N.reason))},tabIndex:0,role:"button","aria-label":`View ${N.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:N.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.count})]},N.reason))})]}),St==="notIndexed"&&!ot&&(xe.reasonGroups??[]).length===0&&xe.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:bs.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.coverageState??"Unknown"})]},N.id))})]}),St==="notIndexed"&&ot&&(()=>{const N=(xe.reasonGroups??[]).find(Y=>Y.reason===ot);return N?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>At(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:N.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[N.count," affected page",N.count!==1?"s":""]})]}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:()=>{Ea(N.urls.map(Y=>Y.url))},children:lt?"Requesting…":`Request indexing (${N.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Se.map(Y=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:Y.url}),e.jsx("td",{className:"text-secondary",children:Y.crawlTime?Y.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:lt,onClick:()=>{Ea([Y.url])},title:"Request indexing",children:"Index"})})]},Y.id))})]})]}):null})(),St==="deindexed"&&xe.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:$.map((N,Y)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.previousState}),e.jsx("td",{className:"text-secondary",children:N.currentState}),e.jsx("td",{className:"text-secondary",children:N.transitionDate.split("T")[0]})]},`${N.url}-${Y}`))})]}),(St==="indexed"&&xe.indexed.length===0||St==="notIndexed"&&!ot&&xe.notIndexed.length===0||St==="deindexed"&&xe.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ds,{page:Ge,pageSize:Zs,visibleRows:Math.min(Zs,ce.length-mt),totalRows:ce.length,onPageChange:z,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":gs,onClick:()=>Fs(N=>!N),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:gs?"Hide snapshots":$t.length>0?`View ${$t.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",xe.summary.indexed.toLocaleString()," indexed, ",xe.summary.notIndexed.toLocaleString()," not indexed.",le&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",le.indexed>=0?"+":"",le.indexed.toLocaleString()," indexed, ",le.notIndexed>=0?"+":"",le.notIndexed.toLocaleString()," not indexed."]})]}),gs&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:$t.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:$t.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:N.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:N.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.notIndexed.toLocaleString()})]},N.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:_e?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Oe,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:zt||!Ft?.propertyId,onClick:()=>{Da()},children:zt?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:gt,onChange:N=>Qt(N.target.value),onKeyDown:N=>N.key==="Enter"&&void Cs([gt.trim()])}),e.jsx(R,{type:"button",size:"sm",disabled:!as||It||!gt.trim(),onClick:()=>{Cs([gt.trim()])},children:It?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:!as||It||Tn.length===0,onClick:()=>{Cs(Tn)},children:It?"Resubmitting…":Ys}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:!as||It||!tt?.length,onClick:()=>{vr()},children:"Resubmit all files"}),Nt&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Nt.indexes," index",Nt.indexes===1?"":"es",", ",Nt.files," file",Nt.files===1?"":"s"]}),qe&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",qe.completed,"/",qe.total]})]}),!as&&Ft&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Je(na),children:"Reconnect"})]}),tt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:tt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Vs,{value:te,onChange:N=>{Ue(N),ns.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:ns.rows.flatMap(N=>{const Y=Yo(N),de=Jo(N),be=Xo(N),nt=ze[N.path]??[],st=$e.has(N.path),ht=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(or,{value:N.path})}),e.jsx("td",{className:"text-secondary",children:N.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":st,"aria-label":`${st?"Collapse":"Expand"} files in ${N.path}`,onClick:()=>{so(N.path)},children:it.has(N.path)?"Loading…":`${st?"▾":"▸"} Index${ze[N.path]?` (${nt.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:be}),e.jsx("td",{className:"text-secondary",children:N.lastSubmitted?N.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:N.lastDownloaded?N.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Y.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:de||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!as||It,onClick:()=>{Cs([N.path])},children:N.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Ft?.sitemapUrl===N.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Js(N.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Ln.isPending,onClick:()=>{gn(N.path)},children:"Inspect URLs"})]})})]},N.path),Mt=N.isSitemapsIndex&&st?nt.map(ut=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(or,{value:ut.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Xo(ut)}),e.jsx("td",{className:"text-secondary",children:ut.lastSubmitted?ut.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ut.lastDownloaded?ut.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Yo(ut).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Jo(ut)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!as||It,onClick:()=>{Cs([ut.path])},children:"Resubmit"}),Ft?.sitemapUrl===ut.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Js(ut.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Ln.isPending,onClick:()=>{gn(ut.path)},children:"Inspect URLs"})]})})]},`${N.path}:${ut.path}`)):[];return[ht,...Mt]})})]}),e.jsx(Ds,{page:ns.page,pageSize:Ks,visibleRows:ns.rows.length,totalRows:ns.totalRows,onPageChange:ns.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:w,onChange:N=>P(N.target.value),onKeyDown:N=>N.key==="Enter"&&void vn()}),e.jsx(R,{type:"button",size:"sm",disabled:Be||!Ft?.propertyId||!w.trim(),onClick:Je(vn),children:Be?"Inspecting…":"Inspect URL"})]}),L&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:L.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:L.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:co(L.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Xt(L.crawlTime)})]})]})]})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{pn(!0)},children:Te?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:G,onChange:N=>me(N.target.value)}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:Te,onClick:()=>{pn(!0)},children:"Apply filter"})]}),y.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:y.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-neutral",children:N.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:co(N.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Xt(N.inspectedAt)})]},N.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),C.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:C.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:N.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Xt(N.transitionDate)})]},`${N.url}:${N.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ft&&!r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>dt(N=>!N),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${ps?"rotate-90":""}`,"aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted",children:"Setup & Configuration"})]})}),ps&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(Ne,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Oe,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:h,disabled:we||m.length===0,onChange:N=>j(N.target.value),children:m.length===0?e.jsx("option",{value:"",children:we?"Loading properties…":"No properties available"}):m.map(N=>e.jsxs("option",{value:N.siteUrl,children:[N.siteUrl," · ",N.permissionLevel]},N.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:we,onClick:()=>{mn(Ft,!0)},children:we?"Refreshing…":"Refresh properties"}),e.jsx(R,{type:"button",size:"sm",disabled:!h||Me,onClick:Je(jr),children:Me?"Saving…":"Save property"})]})]})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:q,onChange:N=>S(N.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:V,onChange:N=>F(N.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(R,{type:"button",size:"sm",disabled:_s.isPending||!Ft.propertyId,onClick:Je(no),children:_s.isPending?"Queueing…":"Queue sync"}),!Ft.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Kp=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Up({projectName:t,projectId:s}){const n=xs(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),m=Le(Ti({client:ne,path:{name:t}})),u=m.data?.find(X=>X.connectionType==="gbp"),x=!!u,f=a?{locationName:a}:void 0,p=Le({...xu({client:ne,path:{name:t}}),enabled:x}),g=Le({...pu({client:ne,path:{name:t},query:f}),enabled:x}),y=Le({...gu({client:ne,path:{name:t},query:f}),enabled:x}),v=Le({...fu({client:ne,path:{name:t},query:f}),enabled:x}),C=Le({...yu({client:ne,path:{name:t},query:f}),enabled:x}),b=Le({...vu({client:ne,path:{name:t},query:f}),enabled:x}),L=Le({queryKey:["gbp-section-insights",t],queryFn:()=>bu(t),enabled:x});function k(){Dt(n,"gbp")}const h=Gt({...ju(),onSuccess:X=>{nc({id:X.runId,projectId:s,kind:Qs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Ee({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),j=o.useSyncExternalStore(ac,cr,cr),w=Object.values(j.runs).some(X=>X.kind===Qs["gbp-sync"]&&X.projectId===s),P=h.isPending||w,q=Gt({...Nu(),onSuccess:()=>k()});if(o.useEffect(()=>{if(!a||!p.data)return;const X=p.data.locations.filter(ue=>ue.selected);(X.length<=1||!X.some(ue=>ue.locationName===a))&&r(null)},[a,p.data]),o.useEffect(()=>{if(!l||!p.data)return;(a?[a]:p.data.locations.filter(ue=>ue.selected).map(ue=>ue.locationName)).includes(l)||i(null)},[l,p.data,a]),m.isLoading)return null;if(!u){const X=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(Ne,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:X.map((ue,ve)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:ve+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ue.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ue.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ue.note})]})]},ue.title))})]})})}const S=g.data,V=p.data?.locations??[],F=V.filter(X=>X.selected),D=y.data?.keywords??[],K=v.data?.lodging??[],H=C.data?.placeActions??[],se=b.data?.places??[],Q=V.length>0?V[0].accountName:u.domain,M=a?V.find(X=>X.locationName===a)?.displayName??null:null,J=a?V.filter(X=>X.locationName===a):F,E=new Set(J.map(X=>X.locationName)),W=K.filter(X=>E.has(X.locationName)),T=H.filter(X=>E.has(X.locationName)),ee=se.filter(X=>E.has(X.locationName)),_=new Set(F.map(X=>X.locationName)),ae=a?D:D.filter(X=>_.has(X.locationName)),ie=!a&&F.length>1,Re=(L.data??[]).filter(X=>!X.dismissed&&Kp.has(X.type)&&(!M||X.query===M||X.query===a||X.title.startsWith(M)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Oe,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{tone:"positive",children:"Connected"}),!re()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:P,onClick:()=>h.mutate({client:ne,path:{name:t},body:{}}),children:P?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[Q?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:Q})," · "]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:X=>r(X.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),F.map(X=>e.jsx("option",{value:X.locationName,children:X.displayName},X.id))]})]}),F.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[Re.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Re.map(X=>e.jsx("div",{className:["insight-card",sg(X.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[X.title,X.recommendation?.reason&&e.jsx(Oe,{text:X.recommendation.reason})]})},X.id))]}),S&&e.jsx(ig,{performance:S.performance,freshness:S.freshness,timeseries:S.timeseries}),S?.profileCompleteness&&e.jsx(Bp,{summary:S.profileCompleteness}),J.length>0&&e.jsx(Vp,{locations:J,lodging:W,places:ee,placeActions:T,expandedLocation:l,onToggleExpanded:X=>{i(ue=>ue===X?null:X)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),y.data&&y.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[Xe(y.data.thresholdedPct,ea.percent)," privacy-thresholded"]})]}),ae.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),ie&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:ae.slice(0,25).map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:X.keyword}),ie&&e.jsx("td",{className:"text-muted",children:V.find(ue=>ue.locationName===X.locationName)?.displayName??X.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:X.valueCount!==null?X.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",X.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[X.periodStart,"–",X.periodEnd]})]},`${X.locationName}:${X.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(X=>!X),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",V.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:V.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!re()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:V.map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:X.displayName}),e.jsx("td",{className:"text-muted",children:X.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(fe,{tone:X.selected?"positive":"neutral",children:X.selected?"Tracked":"Not tracked"})}),!re()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:q.isPending,onClick:()=>q.mutate({client:ne,path:{name:t,locationName:X.locationName},body:{selected:!X.selected}}),children:X.selected?"Untrack":"Track"})})]},X.id))})]})})]})]})})}function Bp({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:ia(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:ia(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:ia(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:ia(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:ia(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Oe,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${tg(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Vp({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(m=>[m.locationName,m])),c=new Map(n.map(m=>[m.locationName,m])),d=new Map;for(const m of a){const u=d.get(m.locationName)??[];u.push(m),d.set(m.locationName,u)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Oe,{text:re()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(m=>{const u=i.get(m.locationName)??null,x=c.get(m.locationName)??null,f=d.get(m.locationName)??[],p=r===m.locationName;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(fe,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(fe,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Vc(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Qp,{location:m})}),e.jsx("td",{children:e.jsx(Hp,{lodging:u})}),e.jsx("td",{children:e.jsx(Yp,{place:x,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(Xp,{actions:f})}),e.jsx("td",{className:"text-right",children:e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>l(m.locationName),children:p?"Hide":"Details"})})]}),p&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(eg,{location:m,lodging:u,place:x,placeActions:f})})})]},m.id)})})]})})]})}function zp(t){return[{label:"Description",tone:kn(t.description)?"positive":"neutral",value:kn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:kn(t.primaryPhone)?"positive":"neutral",value:kn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:kn(t.websiteUri)?"positive":"neutral",value:kn(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function Qp({location:t}){const s=zp(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(fe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Hp({lodging:t}){return e.jsx(Oi,{...Wp(t)})}function Wp(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function Yp({place:t,mapsUri:s}){return e.jsx(Oi,{...Jp(t,s)})}function Jp(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function Xp({actions:t}){return e.jsx(Oi,{...Zp(t)})}function Zp(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function Oi({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(fe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function eg({location:t,lodging:s,place:n,placeActions:a}){const r=s?ag(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Or,{title:"Owner profile · Business Information",children:[e.jsx(Wt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Wt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Wt,{label:"Description",value:kn(t.description)?t.description:"Not returned"}),e.jsx(Wt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Wt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Wt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Wt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Wt,{label:"Open status",value:Vc(t.openStatus)}),e.jsx(Wt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Or,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{label:"Last checked",value:Zo(s.syncedAt)}),e.jsx(Wt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Wt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(Or,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{label:"Places tier",value:n.tier}),e.jsx(Wt,{label:"Last checked",value:Zo(n.syncedAt)}),e.jsx(Wt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(l=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[pr(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[pr(l.providerType),l.uri?` · ${ng(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function Or({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Wt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function ia(t,s,n){return t===s?"positive":t===0?n:"caution"}function tg(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function sg(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function kn(t){return typeof t=="string"&&t.trim().length>0}function Vc(t){return t?pr(t):"Not returned"}function pr(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function ng(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Zo(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ag(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&rg(n)).map(([s])=>pr(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function rg(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function ig({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=wu.filter(g=>(a[g]??0)>0),l=Su.filter(g=>(a[g]??0)>0),i=Object.keys(a).filter(g=>(a[g]??0)>0&&Cu(g)==="other").sort((g,y)=>(a[y]??0)-(a[g]??0)),c=Object.keys(a).filter(g=>(a[g]??0)===0).sort(),d=n.map(g=>{const y={date:g.date};for(const[v,C]of Object.entries(g.metrics))y[v]=C;return y}),m=n.find(g=>g.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,x=d.length>0,f=s.dataThroughDate?`Data through ${Tt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,p=[...r,...i];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),f&&e.jsx("span",{className:"text-[11px] text-muted",children:f})]}),!x||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(el,{data:d,metrics:r,kind:"line",firstPending:m,lastDate:u}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:p.map(g=>e.jsxs("span",{className:"text-sm text-secondary",children:[dr(g)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[g]??0).toLocaleString()})]},g))})]})]}),x&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(el,{data:d,metrics:l,kind:"area",firstPending:m,lastDate:u})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(g=>dr(g)).join(", ")]})]})}function el({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(on,{width:"100%",height:"100%",children:e.jsxs(ln,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Na,{stroke:ba,vertical:!1}),e.jsx(cn,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Pn,minTickGap:24}),e.jsx(dn,{tick:Vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(un,{...rs,labelFormatter:Tt,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),dr(String(i??""))]}),e.jsx(mr,{wrapperStyle:{fontSize:11,color:hs.text},formatter:l=>dr(l)}),a&&r&&e.jsx(oi,{x1:a,x2:r,fill:hs.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:hs.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Bs,{type:"monotone",dataKey:l,stroke:ct[i%ct.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(nn,{type:"monotone",dataKey:l,stackId:"reach",stroke:ct[i%ct.length],fill:ct[i%ct.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function og(t){return Vh(Ot(String(t)))}function lg(t){return Aa(Ot(String(t)))}const Ba=Ks;function On(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Fr(t){return t.toLocaleString()}function cg(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function dg(t){const s=t.filter(n=>n.kind===Qs["backlink-extract"]&&!rc(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function ug(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),l=a%60;return l===0?`${r}m`:`${r}m ${l}s`}function mg({projectName:t}){const s=is(),[n,a]=o.useState(null),[r,l]=o.useState(null),[i,c]=o.useState([]),[d,m]=o.useState(null),[u,x]=o.useState(null),[f,p]=o.useState(null),[g,y]=o.useState(Date.now()),[v,C]=o.useState(0),[b,L]=o.useState(!0),[k,h]=o.useState(!1),[j,w]=o.useState(null),P=o.useCallback(async()=>{L(!0),w(null);try{const[M,J,E,W,T]=await Promise.all([ku().catch(()=>null),Au(t,{excludeCrawlers:!0}).catch(()=>null),Ru(t,{limit:Ba,offset:v,excludeCrawlers:!0}).catch(_=>{if(_ instanceof ni&&_.code==="NOT_FOUND")return null;throw _}),Pu(t).catch(()=>[]),Iu(t).catch(()=>[])]);m(M),a(J),l(E),c(W);const ee=dg(T);x(ee)}catch(M){w(M instanceof Error?M.message:"Failed to load backlinks")}finally{L(!1)}},[t,v]);o.useEffect(()=>{P()},[P]),o.useEffect(()=>{if(!u)return;const M=u.id;let J=!1;const E=async()=>{try{const T=await ai(M);if(J)return;rc(T.status)?(x(null),p(T),await P()):x(ee=>ee?.id===T.id?{...ee,...T}:ee)}catch{}},W=window.setInterval(()=>{E()},3e3);return()=>{J=!0,window.clearInterval(W)}},[u,P]),o.useEffect(()=>{if(!u)return;const M=window.setInterval(()=>y(Date.now()),1e3);return()=>window.clearInterval(M)},[u]),o.useEffect(()=>{if(!f||f.status==="failed")return;const M=window.setTimeout(()=>p(null),1e4);return()=>window.clearTimeout(M)},[f]);async function q(){h(!0),w(null);try{const M=await Lu(t);x(M)}catch(M){M instanceof ni&&M.code==="MISSING_DEPENDENCY"?w("DuckDB is not installed. Visit the Backlinks admin page to install it."):w(M instanceof Error?M.message:"Failed to trigger extract")}finally{h(!1)}}const S=o.useMemo(()=>i.slice().sort((M,J)=>M.queriedAt.localeCompare(J.queriedAt)).map(M=>({date:M.queriedAt,linkingDomains:M.totalLinkingDomains})),[i]),V=r?.rows??[],F=r?.total??0,D=n?.excludedLinkingDomains??0,K=Math.floor(v/Ba)+1;return o.useEffect(()=>{v>0&&v>=F&&C(0)},[v,F]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),j&&e.jsx(Ne,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:j})}),u&&e.jsx(Ne,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Yh,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(fe,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[ug(u.startedAt??null,u.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",g]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),f&&!u&&e.jsx(Ne,{className:`surface-card p-4 mb-4 ${f.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[f.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Jh,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${f.status==="failed"?"text-negative":"text-positive"}`,children:f.status==="failed"?"Extract failed":"Extract complete"}),f.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Tu(f.error)}):f.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return b?e.jsx(Ne,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):se()}function se(){const M=n!==null&&n.totalLinkingDomains>0,J=f?.status==="failed",E=n!==null&&n.totalLinkingDomains===0&&!J,W=d?.status==="ready",T=d?.status==="failed",ee=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return M?Q(e.jsxs(e.Fragment,{children:[!re()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:k||u!==null,onClick:Je(q),children:[e.jsx(Zh,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsx(Ir,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!re()&&!s&&e.jsx(R,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:On("/backlinks"),children:"Open admin"})})]})):e.jsx(Ne,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Xh,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!re()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:On("/backlinks"),children:"Set up backlinks"})})})]}),ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!re()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:On("/backlinks"),children:"View sync status"})})})]}),T&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!re()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:On("/backlinks"),children:"Go to Backlinks admin"})})})]}),W&&!ee&&!E&&!J&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:d.release})," is ready. Run an extract for this project."]}),!re()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(R,{type:"button",size:"sm",disabled:k||u!==null,onClick:Je(q),children:[e.jsx(ur,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Run extract"]}),e.jsx(Ir,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),J&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!re()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:On("/backlinks"),children:"Go to Backlinks admin"})})})]}),E&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",n.targetDomain,". Try a newer release or re-run this extract."]}),!re()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:On("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:k||u!==null,onClick:Je(q),children:[e.jsx(ur,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsxs(Ir,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:n.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function Q(M){if(!n)return null;const J="Linking hosts",E="linking hosts",W="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Fr(n.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",n.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",E]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Fr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",E," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Xe(Number(n.top10HostsShare))})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",E," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",W," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",cg(n.queriedAt),D>0&&e.jsxs(e.Fragment,{children:[" · ",D," excluded domain",D===1?"":"s"]})]}),S.length>=2&&e.jsxs(Ne,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(on,{width:"100%",height:"100%",children:e.jsxs(ln,{data:S,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:ct[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:ct[0],stopOpacity:0})]})}),e.jsx(cn,{dataKey:"date",tick:Vt,stroke:ms,tickFormatter:og}),e.jsx(dn,{tick:Vt,stroke:ms,allowDecimals:!1}),e.jsx(un,{contentStyle:rs.contentStyle,labelStyle:rs.labelStyle,itemStyle:rs.itemStyle,labelFormatter:lg}),e.jsx(nn,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:ct[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(Ne,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:J})]})}),e.jsxs("tbody",{children:[V.map(T=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:T.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Fr(T.numHosts)})]},T.linkingDomain)),V.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:D>0&&F===0?`Every referring domain in this ${W} was a crawler/proxy host (${D} hidden).`:`No referring domains in this ${W}.`})})]})]})}),e.jsx(Ds,{page:K,pageSize:Ba,visibleRows:V.length,totalRows:F,onPageChange:T=>C((T-1)*Ba)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:M})]})}}const hg=["non-brand","branded","unclassified"],tl={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function xg(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function pg(t,s){const n=[...new Set(t.byQuery.flatMap(i=>i.providers.map(c=>c.provider)))].sort(),a=new Map,r=i=>{const c=s(i)??"unclassified";let d=a.get(c);return d||(d={key:c,queries:0,unanswered:0,engines:n.map(m=>({provider:m,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},a.set(c,d)),d},l=new Map;for(const i of t.byQuery){const c=r(i.query);if(i.providers.length===0){c.unanswered++;continue}c.queries++;for(const u of i.providers){l.set(`${i.queryId}::${u.provider}`,i.query);const x=c.engines.find(f=>f.provider===u.provider);x.answered++,u.mentioned&&x.mentioned++,u.cited&&x.cited++,c.answers++}const d=i.providers.some(u=>u.cited),m=i.providers.some(u=>u.mentioned);d&&m?c.citedAndNamed++:d?c.citedNotNamed++:m?c.namedNotCited++:c.neither++}for(const i of t.competitorGaps){const c=l.get(`${i.queryId}::${i.provider}`);if(c===void 0)continue;const d=r(c);d.competitorCited++,d.competitorGaps.push({query:c,provider:i.provider,competitors:i.citingCompetitors})}return hg.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function gg(t){const s=new Map(t.byQuery.map(n=>[n.queryId,n]));return t.competitorGaps.flatMap(n=>{const a=s.get(n.queryId);return a?.providers.some(r=>r.provider===n.provider)?[]:[{query:n.query,provider:n.provider,competitors:n.citingCompetitors,reason:a?"engine":"query"}]})}const fg={engine:"engine no longer configured",query:"query no longer tracked"},sl={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},yg="Each engine's latest answer to each query, spot checks left out. Mentioned: the answer names you. Cited: its sources link to your site. Competitor cited instead of you: answers that cite a tracked competitor's site and not yours.";function Fn(t,s,n){return t===1?s:n}function vg({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=o.useId(),[l,i]=o.useState("non-brand"),c=Le({...$u({client:ne,path:{name:t}}),staleTime:Li}),d=c.data??null,m=d?.status==="ready"?pg(d,s):[],u=m.find(y=>y.key===l)??m.at(0);let x;c.isError?x=e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Could not load engine results: ",Ct(c.error)]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:()=>{c.refetch()},children:"Retry"})]}):d?d.status==="no-data"?x=e.jsx("p",{className:"text-sm text-secondary",children:d.reason==="no-queries"?"Add queries to start tracking AI citations.":Yt()?Yn:"Engine results appear after the first AI Visibility sweep."}):u||(x=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):x=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const f=[];if(u&&d?.status==="ready"){const y=Fn(u.queries,"query","queries");f.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",y]})),f.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",y]})),f.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",y]})),f.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",y]}));for(const L of u.engines)L.answered<u.queries&&f.push(e.jsxs(e.Fragment,{children:[at(L.provider),": answered ",e.jsxs("strong",{children:[L.answered," of ",u.queries]})," ",y]}));u.unanswered>0&&f.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",Fn(u.unanswered,"query","queries")]}));const{providersCiting:v,providersMentioning:C,providersConfigured:b}=d.summary;f.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[v," of ",b]})," ",Fn(b,"engine","engines"),", named by ",e.jsxs("strong",{children:[C," of ",b]})]}));for(const L of a)f.push(e.jsxs(e.Fragment,{children:[at(L.provider),L.model?` (${L.model})`:""," citation rate:"," ",e.jsx("strong",{children:Xe(L.score,ea.percent)}),", ",e.jsxs("strong",{children:[L.cited," of ",L.total]})," ",Fn(L.total,"answer","answers"),", all queries"]}));for(const L of u.competitorGaps)f.push(`"${L.query}" (${at(L.provider)}): ${L.competitors.join(", ")} cited instead of you`);for(const L of gg(d))f.push(`"${L.query}" (${at(L.provider)}): ${L.competitors.join(", ")} cited instead of you, not counted (${fg[L.reason]})`)}const p=d?.status==="ready"?d.summary.latestRunAt:null,g=(y,v)=>u?.key==="non-brand"?ya[xg(y,v)]:"text-primary";return e.jsxs("section",{className:"overview-brief","aria-labelledby":r,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:r,className:"av-card-title",children:"By engine"}),u&&e.jsx(Oe,{text:yg})]}),p||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[p?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",ka(p)]}):null,m.length>1?e.jsx(pa,{label:"Query type",className:"flex-wrap",options:m.map(y=>({value:y.key,label:tl[y.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:tl[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:x??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${sl[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",Fn(u.queries,"query","queries")]}),u.engines.map(y=>e.jsx("th",{scope:"col",children:at(y.provider)},y.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(y=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${g(y.mentioned,y.answered)}`,children:y.mentioned})},y.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(y=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${g(y.cited,y.answered)}`,children:y.cited})},y.provider))]})]})]}),e.jsxs("p",{className:"av-card-line",children:[e.jsx("span",{className:"av-card-line-label",children:"Competitor cited instead of you"}),n?e.jsxs("span",{children:[e.jsx("span",{className:"av-n-sm text-primary",children:u.competitorCited})," ",e.jsxs("span",{className:"av-of",children:["of ",u.answers," ",Fn(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",sl[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(Ra,{items:f})]})}const bg={[Es.queued]:{word:"queued",tone:"text-secondary"},[Es.running]:{word:"running",tone:"text-info-300"},[Es.completed]:{word:"completed",tone:"text-secondary"},[Es.partial]:{word:"partial",tone:"text-caution-400"},[Es.failed]:{word:"failed",tone:"text-negative-400"},[Es.cancelled]:{word:"cancelled",tone:"text-secondary"}};function jg({runs:t,collapsed:s=!1}){const n=o.useId(),{openRun:a}=Pi(),r=new Set(t.map(c=>c.location??"")).size>1,l=t.some(c=>c.kind!==Qs["answer-visibility"]),i=t.map(c=>`${c.startedAt}: ${c.summary}.${c.statusDetail?` ${c.statusDetail}`:""}`);return e.jsx("section",{className:"overview-brief","aria-labelledby":n,children:e.jsxs("details",{className:"av-history",open:!s||void 0,children:[e.jsxs("summary",{className:"av-card-head",children:[e.jsx("h2",{id:n,className:"av-card-title",children:"Past sweeps"}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t.length>0?e.jsxs("span",{className:"av-card-meta",children:[t.length," recent"]}):null,e.jsx(Jn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"av-card-body",children:t.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No sweeps yet."}):e.jsxs("table",{className:"av-grid av-grid-dense av-grid-sweeps","aria-labelledby":n,children:[e.jsx("thead",{className:"sr-only",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Started"}),l?e.jsx("th",{scope:"col",children:"Type"}):null,e.jsx("th",{scope:"col",children:"Trigger"}),r?e.jsx("th",{scope:"col",children:"Location"}):null,e.jsx("th",{scope:"col",children:"Duration"}),e.jsx("th",{scope:"col",children:"Status"})]})}),e.jsx("tbody",{children:t.map(c=>{const d=bg[c.status],m=c.status===Es.partial||c.status===Es.failed;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label tabular-nums",children:e.jsx("button",{type:"button",className:"av-link",onClick:()=>a(c.id),"aria-label":`View the ${c.startedAt} sweep`,children:c.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:c.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:c.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${d.tone}`,children:d.word}),m&&c.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:c.statusDetail}):null]})]},c.id)})})]})}),e.jsx(Ra,{items:i})]})})}const Ng=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],nl="Measured answers",wg="Close answers",qs={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},Sg={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},us={up:t=>`Up ${t} pts`,down:t=>`Down ${t} pts`,none:"No change",previousUnavailable:"No earlier value",comparedWith:t=>`vs ${t} sweep`,noPreviousRun:"No earlier sweep to compare",definitionChanged:t=>t===null?"Not compared: setup changed":`Not compared: setup changed since ${t}`,modelChanged:t=>t===null?"Not compared: engines or models changed":`Not compared: engines or models changed since ${t}`,legacyUnknown:"Not compared: older sweep lacks comparison details",partialRun:"Not compared: a sweep was incomplete",scopedRun:"Not compared: this sweep covered part of the project",explanation:"Change compares this sweep with the sweep before it when both completed and used the same setup, engines and models."},oa={simpleMention:"Mentioned counts answers naming your brand in the answer text, not in the source links.",simpleCitation:"Cited counts answers linking to your site in the sources behind the answer, not in the answer text.",advancedMention:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned. An answer that could not be tied to one property is left out of the rate, never counted as not mentioned.",advancedCitation:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited. An answer whose sources could not be checked is left out of the rate, as neither cited nor not cited, and counted on its own line.",propertyReach:"Selected properties named in at least one measured answer, out of the selected properties that have a name to match on. It counts properties, not answers, and shows no rate while any of those properties is unmeasured."},Cg="Counts properties, not answers. The buckets do not overlap and add up to the total. Cited only means the engine used the property's page as a source without naming it in the answer. Not measured covers a property with no eligible completed measurement, and one where only one of the two signals was measured: calling that mentioned but not cited would assert an absence nothing measured. Neither signal means both were measured and neither was found. One verified mention or citation stands, and a later uncertain answer cannot erase it.",gr="min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400";function kg(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function zc(t){return t.reason==="identity-ambiguous"?dc.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function In({value:t,signal:s}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:zc(t)});const n=$i(t,s);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Xe(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator]}),n?e.jsx("span",{className:"text-sm tabular-nums text-secondary",children:n}):null]})}function al({value:t}){return t.rate===null?null:e.jsx("span",{className:"report-rate-bar","aria-hidden":"true",children:e.jsx("span",{className:"report-rate-bar-fill progress-fill-neutral",style:{width:`${t.rate*100}%`}})})}function Gr(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case Cr["previous-unavailable"]:return{text:us.previousUnavailable,tone:"text-secondary"};case Cr["current-unavailable"]:case Cr["not-applicable"]:return null}const{direction:a,magnitude:r}=oc(n.delta);switch(a){case"up":return{text:us.up(r),tone:"text-positive"};case"down":return{text:us.down(r),tone:"text-negative"};case"none":return{text:us.none,tone:"text-secondary"}}}function rl(t,s){const n=Ot(t);return s!==null&&wo(n)===wo(Ot(s))?ii(n):Aa(n)}function Ag(t,s){return(t.run.id===null?void 0:s.trend.find(a=>a.runId===t.run.id))?.createdAt??t.measurement.completedAt??s.trend.at(-1)?.createdAt??null}function Rg(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?rl(t.previousRun.createdAt,s):null;switch(t.reason){case bn["no-selected-run"]:return null;case bn["no-previous-run"]:return us.noPreviousRun;case bn["definition-changed"]:return us.definitionChanged(n);case bn["model-changed"]:return us.modelChanged(n);case bn["legacy-unknown"]:return us.legacyUnknown;case bn["partial-run"]:return us.partialRun;case bn["scoped-run"]:return us.scopedRun}}return us.comparedWith(rl(t.previousRun.createdAt,s))}function Pg(t,s){const n=`${t.queryCount} ${t.queryCount===1?"query":"queries"} · ${t.answerCount} ${t.answerCount===1?"answer":"answers"}`;return s===null?n:`${n} · ${s}`}function _r({label:t,help:s,value:n,signal:a,unit:r,classNoun:l,change:i}){const c=e.jsx("span",{className:"sr-only",children:` · ${l}`}),d=$i(n,a);return e.jsxs("div",{className:"report-headline-tile",children:[e.jsxs("dt",{className:"flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:t}),e.jsx(Oe,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[zc(n),c]}):e.jsxs(e.Fragment,{children:[e.jsxs("dd",{className:"report-headline-value",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums text-heading",children:Xe(n.rate)}),c,i?e.jsx("span",{className:`text-sm ${i.tone}`,children:i.text}):null]}),e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:`${n.numerator} of ${n.denominator} ${r}`}),d?e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:d}):null]})]})}const Ig={otherQueries:"Other queries"},Va={retiredScope:"This saved scope is unavailable for this measurement. Show the whole site to choose another.",retiredMarket:"This saved market is unavailable for this measurement. Show all markets to choose another.",showWholeSite:"Show whole site",showAllMarkets:"Show all markets"};function Tg(t,s){const n=new Map;for(const r of t){const l=n.get(r.queryKey);l?l.rows.push(r):n.set(r.queryKey,{queryKey:r.queryKey,query:r.query,rows:[r]})}const a=[...n.values()];if(!s||!t.some(r=>r.marketKeys?.length))return a;for(const r of a){const l=[...new Set(r.rows.flatMap(i=>i.marketKeys??[]))].sort();r.marketLabel=l.map(i=>s.get(i)??i).join(" · ")||Ig.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}const fa={help:"Only part of the source list for this answer was saved, so its sources could not all be checked. It is left out of Cited, counted neither as cited nor as not cited. The links that were saved still show what it cited. A property that no fully checked answer cites shows as Not measured.",partlySaved:t=>t===1?"Sources partly saved":`${t} answers with sources partly saved`,savedCite:(t,s,n)=>s===1?`Saved links cite ${n}`:`Saved links in ${t} of ${s} answers cite ${n}`,savedCiteNone:t=>t===null?"No saved link cites an assigned property":`No saved link cites ${t}`,outcomes:t=>`${t} not measured only because an answer's sources were partly saved. Query results shows which answer.`};function Lg({row:t,targetLabels:s,showCount:n}){const a=t.uncheckedSources;if(!a)return null;const r=i=>s.get(i)??i,l=a.citedAnswers>0?fa.savedCite(a.citedAnswers,a.answers,a.citedTargetKeys.map(r).join(", ")):fa.savedCiteNone(t.targetKeys.length===1?r(t.targetKeys[0]):null);return e.jsxs(e.Fragment,{children:[n?e.jsx("span",{className:"text-sm text-secondary",children:fa.partlySaved(a.answers)}):null,e.jsx("span",{className:"text-sm text-secondary",children:l})]})}function il({value:t,signal:s,singleAnswer:n,row:a,targetLabels:r}){if(n&&t.denominator===1&&t.unattributed===void 0&&t.unchecked===void 0&&(t.rate===0||t.rate===1)){const i=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${i?"text-positive":"text-secondary"}`,children:[i?e.jsx(tx,{size:16,"aria-hidden":"true"}):e.jsx(sx,{size:16,"aria-hidden":"true"}),i?"Yes":"No"]})}const l=s==="cited"&&a?.uncheckedSources?a:void 0;return e.jsxs("span",{className:"inline-flex items-start gap-1",children:[e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx(In,{value:t,signal:s}),l?e.jsx(Lg,{row:l,targetLabels:r??new Map,showCount:t.rate===null}):null]}),l?e.jsx(Oe,{text:fa.help}):t.reason==="evidence-incomplete"?e.jsx(Oe,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function ol({targetKeys:t,labels:s}){return t.length===0?e.jsx("span",{children:"No assigned properties"}):t.length===1?e.jsx("span",{children:s.get(t[0])??t[0]}):e.jsxs("details",{children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[t.length," properties"]}),e.jsx("ul",{className:"max-h-48 space-y-2 overflow-y-auto pb-3",children:t.map(n=>e.jsx("li",{children:s.get(n)??n},n))})]})}function $g({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],c=x=>JSON.stringify([...x.targetKeys].sort()),d=t.rows.every(x=>c(x)===c(i)),m=t.rows.every(x=>x.location===i.location),u=x=>x===null?"No location requested":`Requested search location: ${x}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[r?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:r})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsx("div",{className:"text-sm font-normal",children:e.jsx(Jl,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(x=>x.sourceSnapshotIds??[]),queryClass:s==="unknown"?null:s,location:m?i.location:void 0})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[n&&d?e.jsx(ol,{targetKeys:i.targetKeys,labels:a}):null,m?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(x=>e.jsxs("tr",{className:"measurement-engine-result",children:[e.jsxs("td",{className:"measurement-result-engine",children:[e.jsx("span",{className:"font-medium text-heading",children:at(x.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:x.model??"Model not recorded"}),n&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(ol,{targetKeys:x.targetKeys,labels:a})}):null,m?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(x.location)}),e.jsx(Xl,{showLabel:!0,showSubjects:n,queryId:x.queryId,sourceSnapshotIds:x.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:x.provider,model:x.model,location:x.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(il,{value:x.mentionCoverage,signal:"mentioned",singleAnswer:x.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(il,{value:x.citationCoverage,signal:"cited",singleAnswer:x.answerCount===1,row:x,targetLabels:a})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(R,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${x.query} · ${x.provider}`,onClick:f=>l(x,f.currentTarget),children:[x.answerCount===1?"View answer":"View answers",e.jsx(wc,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([x.provider,x.model,x.location])))]})}const qg="Cited counts only answers whose sources could be checked.",ll=[{key:"mentioned",label:"Mentioned",color:ct[1],dashed:!1},{key:"cited",label:"Cited",color:ta.positive,dashed:!0}],cl="var(--chart-tooltip-bg)";function Mg({population:t}){const s=o.useId(),[n,a]=o.useState({mentioned:!0,cited:!0}),r=ll.filter(f=>n[f.key]).map(f=>f.key),l=f=>a(p=>{const g={...p,[f]:!p[f]};return g.mentioned||g.cited?g:p});let i=0;const c=t.trend.map((f,p)=>(p>0&&f.continuity.state!=="comparable"&&(i+=1),{createdAt:Date.parse(f.createdAt),[`mentioned-${i}`]:f.mentionCoverage.rate,[`cited-${i}`]:f.citationCoverage.rate})),d=Array.from({length:i+1},(f,p)=>p),m=new Set(t.trend.slice(1).map(f=>f.continuity.state)),u=[...c.length===1?["First measurement. A trend appears after another comparable run."]:[],...m.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...m.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...m.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(f=>f.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[],...t.trend.some(f=>f.citationCoverage.unchecked!==void 0)?[qg]:[]];if(c.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const x=t.trend.some(f=>f.mentionCoverage.rate!==null||f.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[x?e.jsxs(e.Fragment,{children:[e.jsxs("fieldset",{className:"flex flex-wrap gap-x-5 py-1 text-sm text-secondary",children:[e.jsx("legend",{className:"sr-only",children:"Trend legend"}),ll.map(f=>e.jsxs("label",{className:"flex min-h-11 items-center gap-2",children:[e.jsx("input",{type:"checkbox",className:"size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",checked:n[f.key],disabled:n[f.key]&&r.length===1,onChange:()=>l(f.key)}),e.jsxs("svg",{"aria-hidden":"true",className:"shrink-0",width:"24",height:"10",viewBox:"0 0 24 10",children:[e.jsx("line",{x1:"0",y1:"5",x2:"24",y2:"5",stroke:f.color,strokeWidth:"2",strokeDasharray:f.dashed?"6 4":void 0}),e.jsx("circle",{cx:"12",cy:"5",r:"3",fill:f.dashed?cl:f.color,stroke:f.color,strokeWidth:"2"})]}),f.label]},f.key))]}),u.length>0&&e.jsx("p",{id:s,className:"pb-3 text-sm text-secondary",children:u.join(" ")}),e.jsx("div",{className:"visibility-trend-chart",role:"img","data-visible-series":r.join(" "),"aria-describedby":u.length>0?s:void 0,"aria-label":`${qs[t.queryClass]} mention and citation trend`,children:e.jsx(on,{width:"100%",height:"100%",children:e.jsxs(ln,{data:c,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Na,{stroke:ba,vertical:!1}),e.jsx(cn,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Vt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:f=>new Date(Number(f)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(dn,{domain:[0,1],tick:Vt,tickLine:!1,axisLine:!1,width:48,tickFormatter:f=>Xe(Number(f))}),e.jsx(un,{...rs,formatter:f=>typeof f=="number"?Xe(f):"Not measured",labelFormatter:f=>new Date(Number(f)).toLocaleDateString()}),d.map(f=>e.jsxs(o.Fragment,{children:[n.mentioned?e.jsx(Bs,{type:"linear",dataKey:`mentioned-${f}`,name:"Mentioned",stroke:ct[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:ct[1]}}):null,n.cited?e.jsx(Bs,{type:"linear",dataKey:`cited-${f}`,name:"Cited",stroke:ta.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:cl,strokeDasharray:"none"}}):null]},f))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:x?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${qs[t.queryClass]} trend data`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(f=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(f.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(In,{value:f.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(In,{value:f.citationCoverage,signal:"cited"})}),e.jsx("td",{children:f.continuity.state.replaceAll("-"," ")})]},f.runId))})]})})]})}function vi(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function Fi(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,l=t.populations.find(m=>m.queryClass===r);if(l)return l;const i=vi(a,s)??vi(t,s),c=t.populations.find(m=>m.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(m=>t.populations.find(u=>u.queryClass===m));return d.find(m=>m&&(m.summary.queryCount>0||m.trend.some(u=>u.queryCount>0)))??d.find(m=>m!==void 0)??t.populations[0]}const kt={queryType:"Query type",filters:t=>t===0?"Filters":`Filters · ${t}`,panel:"Visibility filters",clearFilters:"Clear filters",manageQueries:"Manage queries",removeFilter:t=>`Remove filter ${t}`,engine:t=>`Engine: ${t}`,model:t=>`Model: ${t}`,location:t=>`Requested search location: ${t}`,noLocation:"No location requested",dateRange:(t,s)=>`${t} to ${s} (UTC)`,dateFrom:t=>`From ${t} (UTC)`,dateThrough:t=>`Through ${t} (UTC)`,resultsFrom:t=>`Results from: ${t}`,resultsFromSelectedSweep:"Results from: selected sweep",trackingChanged:(t,s,n)=>[t?`Tracking changed ${t}.`:"Tracking changed.",`Showing the ${s??"last"} results, from before the change.`,`New numbers after the ${n??"next"} sweep.`].join(" ")},Eg={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Dg="min-h-11 rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400";function Og(t,s){return t&&s?kt.dateRange(t.slice(0,4)===s.slice(0,4)?Qh(t):Tt(t),Tt(s)):t?kt.dateFrom(Tt(t)):s?kt.dateThrough(Tt(s)):null}function Fg(t,s){const n=[];t.provider&&n.push({key:"engine",label:kt.engine(t.provider),patch:{measurementProvider:void 0}}),t.model&&n.push({key:"model",label:kt.model(t.model),patch:{measurementModel:void 0}}),t.location&&n.push({key:"location",label:t.location==="none"?kt.noLocation:kt.location(t.location),patch:{measurementLocation:void 0}});const a=Og(t.from,t.to);if(a&&n.push({key:"dates",label:a,patch:{measurementFrom:void 0,measurementTo:void 0}}),t.measurementRunId){const r=s.populations.flatMap(l=>l.trend).find(l=>l.runId===t.measurementRunId);n.push({key:"run",label:r?kt.resultsFrom(Aa(Ot(r.createdAt))):kt.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function za(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function Gg({report:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,trackingChangedAt:l,nextSweepDate:i,reportIsPlaceholder:c=!1}){const[d,m]=o.useState(!1),u=o.useRef(null),x=o.useId(),f=`${x}-filters`,{filterOptions:p,selection:g}=t,y=g.measurement,v=Fi(t,s.queryKey,s.answer),C=s.queryClass==="all"?v.queryClass:s.queryClass,b=Fg(s,t),L=s.measurementScope==="property"?s.measurementScopeKey:void 0,k=L?r?.({id:L,label:li(t.scopeOptions,s)?.label??L}):null,h=s.provider??"",j=s.model??"",w=s.location??"",P=s.measurementRunId??"",q=!c&&y.awaitingSweep&&y.measuredRevision!==null&&!g.run.explicit&&s.measurementRunId===void 0&&s.revision===void 0&&s.to===void 0,S=()=>u.current?.focus(),V=(D,K,H,se,Q)=>e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${x}-${K}`,className:"text-sm font-medium text-heading",children:D}),Q?e.jsx(Oe,{text:Q}):null]}),e.jsx("select",{id:`${x}-${K}`,className:gr,value:H,onChange:M=>n({[K]:M.target.value||void 0,measurementQueryKey:void 0}),children:se.map(M=>e.jsx("option",{value:M.value,children:M.label},M.value))})]}),F=(D,K,H,se)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${x}-${K}`,className:"mb-1 block text-sm font-medium text-heading",children:D}),e.jsx("input",{id:`${x}-${K}`,type:"date",className:gr,value:H?.slice(0,10)??"",onChange:Q=>n({[K]:Q.target.value?`${Q.target.value}${se}`:void 0})})]});return e.jsxs("div",{className:"visibility-filter-container",children:[e.jsxs("div",{className:"visibility-results-toolbar",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:kt.queryType}),e.jsxs("select",{"aria-label":kt.queryType,className:Dg,value:C,onChange:D=>n({queryClass:D.target.value,measurementQueryKey:void 0}),children:[e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"unknown",children:"Unclassified"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{tone:y.state==="measured"?"positive":"neutral",children:y.state==="measured"?"Complete":y.state==="partial"?"Partial":"Not measured"}),y.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:Aa(Ot(y.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(R,{ref:u,type:"button",variant:"outline",className:"min-h-11","aria-expanded":d,"aria-controls":f,onClick:()=>m(D=>!D),children:kt.filters(b.length)}),b.map(D=>e.jsxs(R,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":kt.removeFilter(D.label),onClick:()=>{n(D.patch),S()},children:[e.jsx("span",{className:"min-w-0 truncate",children:D.label}),e.jsx(ex,{size:16,className:"shrink-0","aria-hidden":"true"})]},D.key)),k,a?e.jsx(R,{type:"button",variant:"outline",className:"min-h-11",onClick:a,children:kt.manageQueries}):null]})]}),e.jsxs("div",{id:f,role:"group","aria-label":kt.panel,hidden:!d,className:"border-b border-default",onKeyDown:D=>{D.key==="Escape"&&(D.target instanceof HTMLElement&&D.target.getAttribute("aria-expanded")==="true"||(m(!1),S()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[V("Answer engine","measurementProvider",h,za([{value:"",label:"All engines"},...p.providers.map(D=>({value:D,label:D}))],h,h)),V("Requested search location","measurementLocation",w,za([{value:"",label:"All requested locations"},...p.locations.flatMap(D=>D.kind==="exact"?[{value:D.value,label:D.value}]:D.kind==="none"?[{value:"none",label:kt.noLocation}]:[])],w,w==="none"?kt.noLocation:w)),V("AI model","measurementModel",j,za([{value:"",label:"All models"},...Array.from(new Set(p.models.filter(D=>!s.provider||D.provider===s.provider).map(D=>D.model))).map(D=>({value:D,label:D}))],j,j),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),F("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),F("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),V("Results from","measurementRunId",P,za([{value:"",label:"Latest saved sweep"},...[...v.trend].reverse().map(D=>({value:D.runId,label:new Date(D.createdAt).toLocaleString()}))],P,"Selected sweep"),"Choose a saved AI sweep to view its results. No new sweep starts.")]}),e.jsx("div",{className:"flex justify-end pb-3",children:e.jsx(R,{type:"button",variant:"ghost",className:"min-h-11",disabled:b.length===0,onClick:()=>{n({...Eg}),S()},children:kt.clearFilters})})]}),q?e.jsx("p",{role:"status",className:"border-b border-default py-3 text-sm text-secondary",children:kt.trackingChanged(l?ii(Ot(l)):null,y.completedAt?ii(Ot(y.completedAt)):null,i??null)}):null]})}function _g({report:t,isRefreshing:s=!1,onSelectionChange:n,onPage:a,onSearch:r,search:l="",queryKey:i,answerSelection:c,evidenceReport:d,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:x,onEvidencePage:f}){const p=o.useRef(null),g=o.useRef(void 0),y=o.useRef(null),v=Fi(t,i,c,d),C=d??t,b=C.populations.filter(S=>[...S.queries.items,...S.evidence.items].some(V=>V.queryKey===i)),L=c?[c.queryClass]:(b.length?b:m?[]:[v]).map(S=>S.queryClass),k=i?JSON.stringify([c??i,L]):void 0;o.useEffect(()=>{if(!k){s||(g.current=void 0);return}if(g.current===k)return;const S=p.current?.querySelectorAll(`[aria-label="${nl}"]`);if(S?.length){for(const V of S){const F=V.closest("details[data-query-results]");F&&(F.open=!0)}S[0].focus({preventScroll:!0}),S[0].scrollIntoView?.({block:"start"}),g.current=k}},[k,s]);const{selection:h}=t,j=kg(h.scope),w=new Map(t.scopeOptions.filter(S=>S.kind==="property").map(S=>[S.id,S.label])),P=S=>{const V=C.populations.find(F=>F.queryClass===S.queryClass)?.evidence;return{items:V?.items.filter(F=>F.queryKey===i&&(!c||F.provider===c.provider&&F.model===c.model&&F.location===c.location&&(c.runId===null||F.runId===c.runId)))??[],nextCursor:V?.nextCursor}},q=()=>{g.current=void 0;const S=y.current;S!==null&&S.row.queryKey===i&&(!c||S.row.provider===c.provider&&S.row.model===c.model&&S.row.location===c.location)&&S?.element.isConnected?S.element.focus():p.current?.querySelector(`details[data-query-results="${v.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:p,className:"visibility-report","aria-label":"AI visibility results",children:[h.provenance.kind==="legacy-simple"&&h.queryClass!=="unknown"&&h.queryClass!=="all"?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default py-3 text-sm text-secondary",children:[e.jsx("p",{children:"These saved results aren't separated by query type."}),e.jsx(R,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[v].map(S=>{const V=Tg(S.queries.items,h.scope.kind==="property"&&!h.market&&S.queryClass==="non-brand"?new Map(t.scopeOptions.filter(Q=>Q.kind==="market").map(Q=>[Q.id,Q.label])):void 0),F=P(S),D=F.items[0]?.query??S.queries.items.find(Q=>Q.queryKey===i)?.query,K=h.mode==="advanced"&&h.scope.kind!=="property",H=Sg[S.queryClass],se=Rg(S.comparison,Ag(h,S));return e.jsxs("section",{"aria-label":qs[S.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head flex-wrap items-center",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("h2",{children:qs[S.queryClass]}),e.jsx(Oe,{text:S.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":S.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates."})]}),e.jsxs("div",{className:"report-headline-caption",children:[e.jsx("span",{className:"tabular-nums",children:Pg(S.summary,se)}),e.jsx(Oe,{text:us.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":K?3:2,"aria-label":`${qs[S.queryClass]} headline results`,children:[e.jsx(_r,{label:K?"Answers mentioning a property":"Mentioned answers",help:h.mode==="advanced"?oa.advancedMention:oa.simpleMention,value:S.summary.mentionCoverage,signal:"mentioned",unit:"answers",classNoun:H,change:Gr(S.comparison,"mentionCoverage")}),e.jsx(_r,{label:K?"Answers citing a property":"Cited answers",help:h.mode==="advanced"?oa.advancedCitation:oa.simpleCitation,value:S.summary.citationCoverage,signal:"cited",unit:"answers",classNoun:H,change:Gr(S.comparison,"citationCoverage")}),K?e.jsx(_r,{label:"Properties mentioned",help:oa.propertyReach,value:S.summary.propertyReach,signal:"mentioned",unit:"properties",classNoun:H,change:Gr(S.comparison,"propertyReach")}):null]}),e.jsx(Yl,{queryClass:h.queryClass,manage:!0}),e.jsx(Mg,{population:S}),K&&(S.breakdown.groups.length>0||S.breakdown.properties.length>0)?e.jsx(Kg,{population:S,scope:h.scope,scopeOptions:t.scopeOptions,marketKey:h.market?.id,onSelectionChange:n},`${h.scope.kind}:${h.scope.id}`):null,h.mode==="advanced"?e.jsxs("details",{className:"visibility-disclosure","aria-label":`${qs[S.queryClass]} property outcomes`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Property outcomes"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[S.summary.outcomes.total," ",S.summary.outcomes.total===1?"property":"properties"]})]}),e.jsxs("div",{className:"visibility-disclosure-panel flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([Q,M])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:S.summary.outcomes[Q]}),e.jsx("span",{className:"text-sm text-secondary",children:M})]},Q))}),S.summary.notMeasuredUnchecked?e.jsx("p",{className:"text-sm text-secondary",children:fa.outcomes(S.summary.notMeasuredUnchecked)}):null]}),e.jsx(Oe,{text:Cg})]})]}):null,e.jsxs("details",{className:"visibility-disclosure","data-query-results":S.queryClass,"aria-label":`${qs[S.queryClass]} query results`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Query results"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[S.queries.total," ",S.queries.total===1?"result":"results"," · ",j]})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[r?e.jsx("input",{type:"search","aria-label":`Search ${qs[S.queryClass]}`,placeholder:"Search queries",className:`${gr} max-w-sm`,value:l,onChange:Q=>r(Q.target.value)}):null,e.jsx(Oe,{text:h.mode==="advanced"?"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, property scope, and answer counts. Mentioned and Cited count answers matching any assigned property, not the percentage of properties found.":"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, and answer counts. Mentioned counts answers naming your brand. Cited counts answers linking to your site."})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table measurement-results-table","aria-label":`${qs[S.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),V.map((Q,M)=>e.jsx($g,{group:Q,queryClass:S.queryClass,marketHeading:Q.marketLabel!==V[M-1]?.marketLabel?Q.marketLabel:void 0,advanced:h.mode==="advanced",targetLabels:w,onViewAnswers:(J,E)=>{y.current={row:J,element:E},n({measurementQueryKey:J.queryKey,measurementAnswer:JSON.stringify({queryKey:J.queryKey,queryClass:S.queryClass,provider:J.provider,model:J.model,location:J.location,runId:h.run.id,revision:h.revision})})}},Q.queryKey))]})}),S.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[V.length," ",V.length===1?"query":"queries"," · ",S.queries.items.length," ",S.queries.items.length===1?"engine result":"engine results"," shown of ",S.queries.total," results"]}),S.queries.nextCursor&&a?e.jsx(R,{variant:"outline",onClick:()=>a(S.queries.nextCursor),children:"Next queries"}):null,i&&L.includes(S.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":nl,"aria-busy":m,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("h3",{className:"min-w-0 flex-1 text-base font-semibold text-heading [overflow-wrap:anywhere]",children:D??"Answers"}),e.jsx(R,{variant:"ghost",className:"min-h-11",onClick:q,children:wg})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):u?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",u]}),x?e.jsx(R,{variant:"outline",onClick:x,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[F.items.map(Q=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("strong",{className:"text-sm text-heading",children:Q.provider}),Q.model?e.jsx("span",{className:"text-[13px] text-secondary",children:Q.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:Q.location===null?kt.noLocation:kt.location(Q.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(Q.createdAt).toLocaleDateString()}),e.jsx(fe,{tone:"neutral",children:Q.mentioned===null?Q.mentionUnavailableReason==="identity-ambiguous"?dc.ambiguous:"Mention not checked":Q.mentioned?"Mentioned":"Not mentioned"}),e.jsx(fe,{tone:"neutral",children:Q.cited===null?"Citation not checked":Q.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ei,{headingLevel:4,copyable:!!Q.answerText?.trim(),children:Q.answerText??"Answer text unavailable."})}),Q.sources.length>0?e.jsxs("details",{className:"mt-2","data-answer-sources":!0,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[Gh," (",Q.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:Q.sources.map(M=>e.jsx("li",{className:"min-w-0",children:e.jsx(Ii,{url:M})},M))})]}):null]},Q.answerId)),P(S).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:P(S).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,P(S).nextCursor&&f?e.jsx(R,{variant:"outline",onClick:()=>f(P(S).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"visibility-disclosure","aria-label":`${qs[S.queryClass]} competitors`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Competitors"}),e.jsx("span",{className:"visibility-disclosure-meta",children:S.competitorAvailability.state==="unavailable"?"Not available":`${S.competitors.length} measured`})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[S.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):S.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:S.competitors.map(Q=>e.jsxs("tr",{children:[e.jsx("td",{children:Q.domain}),e.jsx("td",{children:e.jsx(In,{value:Q.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(In,{value:Q.citationCoverage,signal:"cited"})})]},Q.domain))})]})}),S.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:S.observedCompetitors.map(Q=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:Q.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[Q.answerCount," ",Q.answerCount===1?"answer":"answers"]})]},Q.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},S.queryClass)})]})}function Kg({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(x=>x.kind==="group").map(x=>[x.id,x])),i=[...l.values()].some(x=>x.parentGroupIds?.length),c=t.breakdown.groups.filter(x=>{const f=l.get(x.id)?.parentGroupIds??[];return s.kind==="project"?f.length===0:s.kind==="group"&&i?f.includes(s.id):!0}),[d,m]=o.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),u=rn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:x=>x.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(x=>e.jsx(R,{variant:d===x?"secondary":"ghost",onClick:()=>{m(x),u.setPage(1)},children:x==="groups"?"Groups":"Properties"},x))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:x=>u.setQuery(x.target.value),className:`${gr} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:u.rows.map(x=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:x.id,measurementMarketKey:a}),children:x.label})}),e.jsx("td",{children:x.queryCount}),e.jsxs("td",{children:[e.jsx(In,{value:x.mentionCoverage,signal:"mentioned"}),e.jsx(al,{value:x.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(In,{value:x.citationCoverage,signal:"cited"}),e.jsx(al,{value:x.citationCoverage})]})]},x.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Ds,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:d,onPageChange:u.setPage})]})}function Qc(t,s,{enabled:n}){return Le({...ir({client:ne,path:{name:t},query:ri(s)}),enabled:n,staleTime:ic,retry:!1,placeholderData:Ai})}function Hc(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function Ug({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=o.useState(),[c,d]=o.useState(""),[m,u]=o.useState(),x=xs(),f=o.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),p=Le({...ir({client:ne,path:{name:t},query:{...ri(s),cursor:l,search:c||void 0}}),staleTime:ic,retry:!1,placeholderData:Ai}),g={...f,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??p.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??p.data?.selection.revision??s.revision,limit:50},y=JSON.stringify(g),v=Le({...ir({client:ne,path:{name:t},query:{...g,cursor:m?.selection===y?m.cursor:void 0}}),enabled:!!s.queryKey&&!!p.data&&!p.isPlaceholderData,retry:!1});if(o.useEffect(()=>{if(s.queryClass!=="all"||!p.data||p.isPlaceholderData||p.isFetching||p.isError||p.data.selection.availability.state==="unsupported"||p.data.populations.length===0||s.queryKey&&!s.answer&&!vi(p.data,s.queryKey)&&!v.data)return;const C=Fi(p.data,s.queryKey,s.answer,v.data);if(!l&&!c){const{queryKey:b}=ir({client:ne,path:{name:t},query:ri({...s,queryClass:C.queryClass})});x.setQueryData(b,{...p.data,selection:{...p.data.selection,queryClass:C.queryClass},populations:[C]},{updatedAt:p.dataUpdatedAt})}n({queryClass:C.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}},{replace:!0})},[s.queryClass,s.queryKey,s.answer,p.data,p.dataUpdatedAt,p.isPlaceholderData,p.isFetching,p.isError,v.data,n,x,t,f,l,c]),p.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:a});if(p.data&&Hc(p.data,r))return e.jsx(e.Fragment,{children:a});if(p.error){const C=lc(cc(p.error)),b=C?.reason===Eu["retired-market"];return e.jsxs("section",{className:"page-section-divider",role:"alert",children:[e.jsx("h2",{children:"AI visibility unavailable"}),e.jsx("p",{className:"my-3 text-sm text-secondary",children:b?Va.retiredMarket:C?Va.retiredScope:va(p.error)}),b?e.jsx(R,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:Va.showAllMarkets}):C?e.jsx(R,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:Va.showWholeSite}):e.jsx(R,{variant:"outline",onClick:()=>{i(void 0),p.refetch()},children:"Retry"})]})}return p.data?e.jsx("div",{"aria-busy":p.isFetching,children:e.jsx(_g,{report:p.data,isRefreshing:p.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:v.data,isEvidenceLoading:v.isFetching||!!s.queryKey&&v.isPending,evidenceError:v.error?va(v.error):void 0,onRetryEvidence:()=>{v.refetch()},onEvidencePage:v.isFetching?void 0:C=>u({selection:y,cursor:C}),search:c,onSearch:C=>{d(C),i(void 0)},onPage:p.isFetching?void 0:i,onSelectionChange:C=>{(!("measurementQueryKey"in C)||Object.keys(C).some(b=>b!=="measurementQueryKey"&&b!=="measurementAnswer"))&&i(void 0),u(void 0),n(C)}})}):e.jsx("section",{className:"page-section-divider",role:"status","aria-label":"Loading AI visibility",children:e.jsx("div",{className:"h-64 animate-pulse rounded-md bg-surface"})})}function Bg({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,trackingChangedAt:l,nextSweepDate:i,fallback:c,showUnmeasuredFallback:d=!1}){const m=Qc(t,s,{enabled:!0}),u=m.error?void 0:m.data,x=!m.isPlaceholderData&&u?.selection.availability.state==="available"?u.selection.run.id:null;Mu(x,null);const f=!!(u&&u.selection.availability.state==="available"&&!Hc(u,d));return e.jsxs(e.Fragment,{children:[f?e.jsx(Gg,{report:u,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,trackingChangedAt:l,nextSweepDate:i,reportIsPlaceholder:m.isPlaceholderData}):null,!f&&(u||m.error)?e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx(Wl,{})}):null,e.jsx(Ug,{projectName:t,selection:s,onSelectionChange:n,fallback:c,showUnmeasuredFallback:d},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Vg=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],zg=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"Your share of the answer-text brand mentions for you and tracked competitors, in non-brand answers, or in all answers when queries cannot be split by brand."}],Gi=ct[2],Qg=ct[4],Hg="var(--chart-tooltip-bg)",Wg={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function Wc({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function Yg(t){return t.direction==="none"?"no change over the period":`${Wc(t)} over the period`}function Jg(t){return t===Pa||t===Ia||t===zs}function Yc(t){return t===Pa?"Cited":t===Ia?"Mentioned":t===zs?"Mention share":at(t)}function da(t,s){return t===Pa?ta.positive:t===Ia?ct[1]:t===zs?Gi:zh(Sa(t),s)}function _i(t){return t==="non-brand"?"non-brand answers":"all answers"}function bi(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Ki(t,s){return t==="mentionShare"?`Mention share in ${_i(s)}`:bi(t)}function Xg(t){return`Mentioned = share of answers that name you. Cited = share that link to your site. Mention share = your share of tracked-brand mentions in ${t==="non-brand"?"non-brand answers":"all answers"}.`}function Jc(t){return t==="cited"?"citationRate":"mentionRate"}function Ui(t,s){return s==="cited"?t.cited:t.mentionedCount}function Xc(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function Zg(t,s){if(s==="mentionShare"){const{projectMentionSnapshots:n,competitorMentionSnapshots:a}=t.mentionShare;return`${n} of ${n+a} tracked-brand mentions`}return`${Ui(t,s)} of ${t.total} answers`}function ef(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Zc(t){const s=Tc(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>Sa(n).localeCompare(Sa(a))).map(([n,a])=>`${at(n)}: ${Ca(a)}`)}function ed(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function dl(t){return`${t} ${t===1?"query":"queries"}`}function Bi(t){const{added:s,removed:n}=t;return[...s.length>0?[`${dl(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:dl(n.length)} removed`]:[]].join(", ")}function td(t,s){const n=Os(t),a=Ta(t),r=Ec(t,s);if(!n||!a||!r)return null;const l=ap(r.moves),i=ed(n.start,n.end),c=d=>ka(d,i?n.start:null);return n.sweepCount===2?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes the ",e.jsx("strong",{children:c(n.start)})," sweep and the ",e.jsx("strong",{children:c(n.end)})," sweep, with ",l," between them"]}):r.moves.added.length+r.moves.removed.length>0?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes sweeps with ",l," between them"]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point pools ",e.jsx("strong",{children:n.sweepCount})," sweeps, with ",l," between the first and last"]})}function tf(t,s,n){const a=td(s,n);return a?e.jsxs(e.Fragment,{children:["Not the same queries: ",a]}):t.changes.length>0?e.jsxs(e.Fragment,{children:["Not the same queries: ",t.changes.map((r,l)=>e.jsxs(o.Fragment,{children:[l>0?", ":"",Bi(r)," ",e.jsx("strong",{children:wa(Ot(r.at))})]},r.at)),"; first and latest points cover different queries"]}):e.jsxs(e.Fragment,{children:["Not the same queries: first and latest points have answers for ",e.jsx("strong",{children:t.firstCount})," and ",e.jsx("strong",{children:t.latestCount})," queries"]})}function ul(t){return t.replace(/ /g," ")}function fr({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:Ca(t)})}function sf(t,s){return t.reroute?"Same preset, answered with a different model.":hr(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${Ca(t.served.to)} (was ${Ca(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function nf({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:c,sweepTimes:d}){const m=t.at(-1),u=h=>wa(h),x=new Map;for(const[h,j]of r){const w=n.find(P=>P.provider===h&&!P.reroute&&P.to.status==="known"&&j.modelIds.includes(P.to.model));w&&x.set(h,w)}const f=[];s.length>0&&f.push({key:"queries",label:"Queries",rows:s.map(h=>({key:`queries-${h.at}`,at:h.at,onOrBefore:!1,from:null,to:e.jsx("span",{className:"text-strong",children:Bi(h)}),toHelp:null}))});const p=[...new Set(n.map(h=>h.provider))].sort((h,j)=>at(h).localeCompare(at(j)));for(const h of p){const w=a[h]?.latestServedModelIds??null,P=n.filter(q=>q.provider===h);f.push({key:h,label:at(h),rows:P.map((q,S)=>{const V=x.get(h)===q?r.get(h).text:null,F=[sf(q,S===0?w:null),V].filter(Boolean).join(" ");return{key:`${h}-${q.at}-${q.reroute?"served":"set"}`,at:q.at,onOrBefore:q.onOrBefore,from:e.jsx(fr,{state:q.from,from:!0}),to:e.jsx(fr,{state:q.to}),toHelp:F||null}})})}const g=f.reduce((h,j)=>h+j.rows.length,0),y=[];for(const h of s)h.added.length>0&&y.push(e.jsxs(e.Fragment,{children:["Added ",e.jsx("strong",{children:u(h.at)}),": ",h.added.map(c).join(", ")]})),h.removed.length>0&&y.push(e.jsxs(e.Fragment,{children:["Removed ",e.jsx("strong",{children:u(h.at)}),": ",h.removed.map(c).join(", ")]}));const v=m?Ta(m):null;for(const[h,j]of Object.entries(m?Tc(m)??{}:{}).sort(([w],[P])=>w.localeCompare(P)))j.status==="mixed"&&v&&y.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:v})," point mixes ",at(h)," models: ",Gx(j)]}));const C=new Map;for(const h of n.filter(j=>j.onOrBefore)){const j=h.anchorAt?u(h.anchorAt):"";C.set(j,[...new Set([...C.get(j)??[],at(h.provider)])])}for(const[h,j]of C)y.push(h?e.jsxs(e.Fragment,{children:["Changed before this date range, after the ",e.jsx("strong",{children:h})," sweep: ",ga(j)]}):`Changed before this date range: ${ga(j)}`);for(const h of l)y.push(`${at(h.provider)}: most recent ${h.shown} of ${h.total} changes`);for(const h of i)y.push(`${at(h)}: may be missing older changes`);for(const[h,j]of r)x.has(h)||y.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[at(h),": no model updates on record",e.jsx(Oe,{text:j.text})]}));if(g===0&&y.length===0)return null;for(const[h,j]of Object.entries(a).sort(([w],[P])=>at(w).localeCompare(at(P)))){const w=j.latestServedModelIds??[],P=w.length>0?w.join(", "):Ca(j.latestObservation.state);y.push(e.jsxs(e.Fragment,{children:[at(h)," last answered with ",e.jsx("strong",{children:P})," on ",e.jsx("strong",{children:u(Ot(j.latestObservation.observedAt))})]}))}const b=f.flatMap(h=>h.rows.map(j=>j.at));let L="First sweep on the new model or query set.";if(b.length>0){const h=u(b.reduce((V,F)=>Date.parse(F)>Date.parse(V)?F:V)),j=[...new Set(b.filter(V=>u(V)===h))].sort(),w=j.map(V=>ka(V,V));L+=` ${h} = the ${ga(w)} ${w.length===1?"sweep":"sweeps"}.`;const P=n.flatMap(V=>V.anchorAt?[V.anchorAt]:[]),q=P.length>0?P.reduce((V,F)=>Date.parse(F)>Date.parse(V)?F:V):null,S=ep(j[0],d,t,q);S&&(L+=` Sweep before: ${u(S)}.`)}const k=Zx({latest:m,queryChanges:s,modelRows:n})??"No changes in this date range";return e.jsxs("details",{className:"av-wc",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"av-card-title",children:"What changed"}),e.jsx("span",{className:"av-wc-summary av-wc-when-closed",children:k}),e.jsxs("span",{className:"av-wc-toggle",children:[e.jsxs("span",{className:"av-wc-when-closed",children:[g>0?`Show all ${g}`:"Details"," ",e.jsx("span",{"aria-hidden":"true",children:"▸"})]}),e.jsxs("span",{className:"av-wc-when-open",children:["Hide ",e.jsx("span",{"aria-hidden":"true",children:"▴"})]})]})]}),e.jsx("div",{className:"av-wc-body",children:g>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-change-table",children:[e.jsx("caption",{className:"sr-only",children:"Query and model changes, newest first"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Changed"})}),e.jsx("th",{scope:"col","aria-label":"Date",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Date",e.jsx(Oe,{text:L})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),f.map(h=>e.jsx("tbody",{children:h.rows.map((j,w)=>e.jsxs("tr",{children:[w===0?e.jsx("th",{scope:"row",className:"av-engine",children:h.label}):e.jsx("td",{className:"av-engine",children:e.jsx("span",{className:"sr-only",children:h.label})}),e.jsx("td",{className:"av-date",children:j.onOrBefore?`on or before ${ul(u(j.at))}`:ul(u(j.at))}),j.from===null?null:e.jsx("td",{children:j.from}),e.jsx("td",{colSpan:j.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[j.to,j.toHelp?e.jsx(Oe,{text:j.toHelp}):null]})})]},j.key))},h.key))]})}),e.jsx(Ra,{items:y})]}):e.jsx("ul",{className:"av-details-list",children:y.map((h,j)=>e.jsx("li",{children:h},j))})})]})}function af({substitutions:t}){return t.length===0?null:e.jsx("ul",{className:"space-y-3","aria-label":"Model substitutions",children:t.map(({provider:s,mismatch:n})=>e.jsxs("li",{className:"av-amber-row border border-caution-800/60 bg-caution-950/20",children:[e.jsx("span",{className:"av-engine",children:at(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(fr,{state:n.configured})," · answered ",e.jsx(fr,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function rf({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const c=ef(l,s);if(!c)return null;const d=Os(c),m=d!==null&&ed(d.start,d.end)?d.start:null,u=qc(c,i),x=Zc(c),f=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:Di(c)}),u.map(y=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[Bi(y)," ",ka(y.at,m)]},y.at))]}),p=x.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:x.map((y,v)=>e.jsxs(o.Fragment,{children:[v>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:y})]},v))});if(a==="mentionShare"){const y=c.mentionShare.projectMentionSnapshots,v=c.mentionShare.competitorMentionSnapshots,C=y+v;return e.jsxs("div",{className:"trend-tooltip",children:[f,e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Gi},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ki("mentionShare",c.mentionShare.scope)}),e.jsx("span",{className:"trend-tooltip-value",children:Xe(c.mentionShare.rate)})]}),e.jsx("p",{className:"trend-tooltip-detail",children:C>0?`You ${y} of ${C} tracked-brand mentions. Competitors ${v}.`:"No tracked-brand mentions in this point"}),p]})}const g=r==="byProvider"?(n??[]).filter(y=>y.dataKey!==void 0):[{dataKey:a==="cited"?Pa:Ia}];return e.jsxs("div",{className:"trend-tooltip",children:[f,g.map((y,v)=>{const C=String(y.dataKey??y.name??""),b=r==="byProvider"?Xc(c,C,a):null,L=b?.count??Ui(c,a),k=b?.total??c.total,h=b?b.rate:c[Jc(a)],j=y.color??da(C,v);return e.jsx("div",{className:"trend-tooltip-block",children:e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:j},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Yc(C)}),e.jsx("span",{className:"trend-tooltip-value",children:Xe(h)}),e.jsxs("span",{className:"trend-tooltip-count",children:[L," of ",k]})]})},`${C}-${v}`)}),p]})}function of({buckets:t,metric:s,mode:n,series:a,mentionShareScope:r}){return e.jsx("div",{className:"sr-only",children:e.jsxs("table",{children:[e.jsxs("caption",{children:[Ki(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Point"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(l=>{let i;if(s==="mentionShare"){const d=l.mentionShare.projectMentionSnapshots,m=l.mentionShare.competitorMentionSnapshots,u=d+m,x=_i(l.mentionShare.scope);i=u>0?`${Xe(l.mentionShare.rate)} mention share in ${x}, ${d} of ${u} tracked-brand mentions were you`:`mention share undefined in ${x}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const m=Xc(l,d,s);return m?`${at(d)} ${Xe(m.rate)} ${bi(s).toLowerCase()}, ${m.count} of ${m.total} answers`:`${at(d)} no data`}).join("; "):i=`${Xe(l[Jc(s)])} ${bi(s).toLowerCase()}, ${Ui(l,s)} of ${l.total} answers`;const c=Zc(l);return c.length>0&&(i+=`; models: ${c.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Di(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function lf({projectName:t,competitorDomains:s=[],competitorAliases:n,analyticsRevision:a="none",queryTexts:r=[],classifyQuery:l,sweepTimes:i=[]}){const[c,d]=o.useState("all"),[m,u]=o.useState("mentioned"),[x,f]=o.useState("byProvider"),p=o.useId(),g=o.useMemo(()=>$x(s,n),[s,n]),y=Le({queryKey:["analytics-metrics",t,c,g,a],queryFn:()=>qu(t,c),staleTime:Li}),v=y.data??null,C=y.error,b=m==="mentionShare"?"overall":x,L=o.useMemo(()=>v?Vx(v,m,b):null,[v,m,b]),k=v?Ex(v):null,h=o.useMemo(()=>Kx(k??{}),[k]),j=o.useMemo(()=>Ux(k??{}),[k]),w=o.useMemo(()=>Object.entries(k??{}).filter(([,pe])=>pe.anchorUnavailable).map(([pe])=>pe).sort(),[k]),P=o.useMemo(()=>v?Dx(v):{},[v]),q=o.useMemo(()=>v?Wx(Ox(v)):[],[v]),S=o.useMemo(()=>v?$c(v):[],[v]),V=o.useMemo(()=>v?Yx(v):[],[v]),F=o.useMemo(()=>Xx(k??{},P),[k,P]),D=o.useMemo(()=>v?Fx(v):{},[v]),K=o.useMemo(()=>mo(D,{engineName:at}),[D]),H=o.useMemo(()=>{const pe=new Map;for(const[we,Ke]of Object.entries(D).sort(([Me],[O])=>Me.localeCompare(O))){const Me=mo({[we]:Ke},{engineName:at});Me?.kind==="no-known-change"&&pe.set(we,{text:`${Me.text} ${Me.detail}`,modelIds:Ke.modelIds??[]})}return pe},[D]),se=o.useMemo(()=>{const pe=new Map(r.map(we=>[Wn(we),we]));return we=>pe.get(Wn(we))??we},[r]),Q=m!=="mentionShare"&&b==="byProvider",M=v?.buckets??[],J=M[M.length-1]?.mentionShare.scope??v?.mentionShareScope??"pooled",E=Ki(m,J),W=Q?hs.textDim:m==="cited"?ta.positive:m==="mentionShare"?Gi:ct[1],T=o.useMemo(()=>{const pe=new Map(M.map(we=>[we.startDate,Lx(we)]));return we=>pe.get(String(we))??""},[M]),ee=m==="mentionShare"?M.filter(pe=>typeof pe.mentionShare.rate=="number"&&Number.isFinite(pe.mentionShare.rate)):M,_=ee.at(-1),ie=(v?zx(v,m):[]).at(-1)??null,Re=v?Qx(v,m):null,X=np(ee,S),ue=Io(X,m,J,l),ve=ie!==null&&Re!==null?oc(Re.delta):null,Z=ve!==null&&!ue,he=s.length,G=[];if(_&&Re!==null&&X&&!ue&&G.push(tf(X,_,S)),_&&ee.length===1){const pe=td(_,S);pe&&!Io(Ec(_,S),m,J,l)&&G.push(pe)}if(ve!==null&&ee[0]){const pe=Ta(ee[0]);pe&&G.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:pe})," point"]}))}Q&&ie!==null&&G.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:Xe(ie)})," pools all answers; not an average of engines"]}));const me=[...new Set([...h.buckets.map(pe=>pe.bucketStartDate),...M.filter(pe=>qc(pe,S).length>0).map(pe=>pe.startDate)])].sort(),De=ie!==null&&_&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:W},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:E}),e.jsx("span",{className:"visibility-trend-current-value",children:Xe(ie)}),ve!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${Z?"text-muted":Wg[ve.direction]}`,children:[Wc(ve),Z?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",Zg(_,m)]})]}),ke=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(pa,{options:zg,value:m,onChange:u,label:"Metric",className:"visibility-trend-metric-control"}),m!=="mentionShare"&&e.jsx(pa,{options:Vg,value:x,onChange:f,label:"Series"}),e.jsx(pa,{options:Ng,value:c,onChange:d,label:"Time window",className:"sm:ml-auto"})]});let oe;if(C)oe=e.jsx("p",{className:"text-sm text-negative-400",children:va(C)});else if(y.isLoading&&!v)oe=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(m==="mentionShare"&&he===0)oe=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!v||!L)oe=null;else{const{rows:pe,series:we,hasData:Ke}=L;if(!Ke)oe=e.jsx("p",{className:"text-sm text-secondary",children:m==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${_i(J)} in this window yet.`:Yt()?Yn:"Run a sweep to start tracking citations and mentions over time."});else if(Q&&we.length===0)oe=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const Me=`${E} rate across ${pe.length} ${pe.length===1?"sweep":"sweeps"}. Latest ${Xe(ie)}${ve!==null?`, ${Yg(ve)}${Z?", not the same queries":""}`:""}.`;oe=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:Me}),e.jsx(of,{buckets:M,metric:m,mode:b,series:we,mentionShareScope:J}),Q&&we.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:we.map((O,U)=>{const B=Hx(v,O,m);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:da(O,U)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:Yc(O)}),B!==null&&e.jsx("span",{className:"trend-legend-value",children:Xe(B)})]},O)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${E} trend chart over ${pe.length} ${pe.length===1?"point":"points"}`,children:e.jsx(on,{width:"100%",height:"100%",children:e.jsxs(ln,{data:pe,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(Na,{stroke:ba,vertical:!1}),e.jsx(cn,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:T,minTickGap:24}),e.jsx(dn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:O=>Xe(O,ea.percent),tick:Vt,tickLine:!1,axisLine:!1,width:40}),e.jsx(un,{cursor:{stroke:ms,strokeWidth:1},content:e.jsx(rf,{metric:m,mode:b,buckets:M,basketChanges:S})}),me.map(O=>e.jsx(dx,{x:O,stroke:Qg,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${O}`)),we.map((O,U)=>e.jsx(Bs,{type:"monotone",dataKey:O,name:O,stroke:da(O,U),strokeDasharray:O===zs?"5 4":void 0,strokeWidth:Jg(O)?2.5:2,dot:O===zs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:da(O,U),strokeWidth:1.5}:{r:2.5,fill:da(O,U),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Hg},connectNulls:O!==zs,isAnimationActive:!1},O))]})})}),me.length>0&&e.jsxs("p",{className:"visibility-trend-key",children:[e.jsx("span",{className:"visibility-trend-key-swatch","aria-hidden":"true"}),"Setup changed"]})]})}}return e.jsxs("div",{className:"visibility-trend-stack",children:[e.jsxs("section",{className:"visibility-trend","aria-labelledby":p,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:p,className:"av-card-title",children:"AI answers over time"}),e.jsx(Oe,{text:Xg(J)})]}),_?e.jsx("p",{className:"av-card-meta",children:Di(_)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[K?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:K.text}),De,ke,oe]}),e.jsx(Ra,{items:G})]}),v&&!C?e.jsxs(e.Fragment,{children:[e.jsx(nf,{buckets:M,queryChanges:V,modelRows:F,served:P,pointerNotices:H,truncated:j,incompleteHistory:w,queryName:se,sweepTimes:i}),e.jsx(af,{substitutions:q})]}):null]})}const ml=new Set([xa.queued,xa.running]),Bt={queryPlaceholder:"Write one research query per line",runAction:"Run queries",historyTitle:"Research history",historyMore:"Load older runs",historyLoading:"Loading older runs…",historyMoreError:"Could not load older research. Try again.",resultsTitle:"Research results",emptyHistory:"No saved research.",resultsEmpty:"Choose a saved run.",methodologySummary:"How matching works",methodology:"Brand-name matches use configured project names or domains in answer text. Project-domain citations use source links. Neither verifies property identity.",refreshPreview:"Regenerate preview",templateProvenance:"Query pattern details",brandedQuery:"Branded",discoveryQuery:"Discovery",unclassifiedQuery:"Unclassified"};function hl({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:m=null}){const u=xs(),{account:x,canWrite:f}=Hs(),p=x?.role==="viewer"&&m!==null,g=!f,y=is(),[v,C]=o.useState(""),[b,L]=o.useState(""),[k,h]=o.useState(null),[j,w]=o.useState([]),P=o.useRef(null),q=o.useRef(!1),[S,V]=o.useState(0),F=Le({...Du({client:ne,path:{name:t}}),staleTime:6e4}),D=Le({...Ou({client:ne}),enabled:!g&&!y,staleTime:6e4}),K={client:ne,path:{name:t},query:{limit:20}},H=Ql({...Fu(K),initialData:void 0,initialPageParam:K,getNextPageParam:G=>G.nextCursor?{path:K.path,query:{...K.query,cursor:G.nextCursor}}:void 0,refetchInterval:G=>G.state.data?.pages.some(me=>me.runs.some(De=>ml.has(De.status)))?3e3:!1}),se=H.isError&&!H.isFetchNextPageError,Q=H.data?.pages.at(-1),M=se?[]:[...new Map((H.data?.pages.flatMap(G=>G.runs)??[]).map(G=>[G.id,G])).values()],J=Q?.access?.canRun??(f||p),E=Q?.access?Q.access.dailyRunLimit:p?m.viewerDailyRunLimit:null;o.useEffect(()=>{!k&&M[0]&&h(M[0].id)},[M,k]);const W=M.find(G=>G.id===k)??null,T=Le({...Gu({client:ne,path:{name:t,runId:k??""}}),enabled:!se&&!!k,refetchInterval:W&&ml.has(W.status)?3e3:!1}),ee=se||T.isError?null:T.data??null,_=F.data?.locations??[],ae=o.useMemo(()=>{if(g)return(Q?.providers??[]).map(me=>({...me,catalog:me}));const G=new Map((D.data?.providerCatalog??[]).map(me=>[me.name,me]));return(D.data?.providers??[]).filter(me=>me.configured&&G.get(me.name)?.mode==="api").map(me=>({...me,catalog:{...G.get(me.name),defaultModel:me.model||G.get(me.name).defaultModel}}))},[g,Q?.providers,D.data]),ie=!(g?H.isPending:D.isPending)&&ae.length===0,Re=ae.find(G=>G.name===v)??null;o.useEffect(()=>{if(!v&&F.data&&!F.isError&&!D.isError){const G=F.data.providers.find(me=>ae.some(De=>De.name===me));C(G??ae[0]?.name??"")}},[v,ae,F.data,F.isError,D.isError]);const X=Re?.catalog.modelConfigurable??!1,ue=g?Re?.catalog.defaultModel:(Re?F.data?.providerModels[Re.name]:"")||Re?.catalog.defaultModel,ve=(X?b.trim():"")||ue,Z=Re?[...new Map([{id:Re.catalog.defaultModel,displayName:Re.catalog.defaultModel},...b.trim()?[{id:b.trim(),displayName:b.trim()}]:[],...Re.catalog.knownModels].map(G=>[G.id,G])).values()]:[],he=Gt({..._u(),onSuccess:async G=>{P.current=null,V(me=>me+1),w(G.runs),h(G.runs[0]?.id??null),await yf(u),Ee({title:"Research batch saved",detail:`${G.runs.length} ${G.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${G.runs.map(me=>me.id).join(":")}`,dedupeMode:"replace"})},onError:G=>{Ee({title:"Could not start research",detail:G instanceof Error?G.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{q.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[y?e.jsx(Ne,{className:"surface-card min-w-0",children:e.jsx("p",{className:"text-sm text-secondary",children:"This public demo shows saved research results. Running research is unavailable."})}):e.jsxs(e.Fragment,{children:[e.jsx(cf,{projectName:t,canWrite:f,researchAllowed:J&&!se,limitedAccess:g,isEmbed:re(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d,locations:_,defaultLocation:F.data?.defaultLocation??null,providerOptions:ae,provider:v,onProviderChange:G=>{C(G),L("")},resolvedModel:ve,visibilityModel:ue,configurableModel:X,model:b,onModelChange:L,modelOptions:Z,settingsReady:g?!H.isPending&&!se:!D.isPending&&!D.isError&&!D.isFetching,projectReady:!F.isPending&&!F.isError&&!F.isFetching,isPending:he.isPending,errorMessage:he.isError?"The request could not be confirmed.":void 0,onSubmit:(G,me)=>{!J||se||re()||q.current||(P.current?.fingerprint!==me&&(P.current={fingerprint:me,key:crypto.randomUUID()}),q.current=!0,he.mutate({client:ne,path:{name:t},body:{...G,idempotencyKey:P.current.key}}))}},`${t}:${S}`),E!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",E," destination runs per project per day."]}),!g&&D.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(R,{variant:"outline",onClick:()=>{D.refetch()},children:"Retry providers"})]}):null,F.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(R,{variant:"outline",onClick:()=>{F.refetch()},children:"Retry locations"})]}):null,!(g?se:D.isError)&&ie&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:g?"No research engines are available. Ask your Canonry team to configure one.":"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."}),j.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",j.map((G,me)=>e.jsxs("span",{children:[me>0?", ":"",e.jsxs("a",{href:`#research-run-${G.id}`,className:"text-link underline",onClick:()=>h(G.id),children:[G.scope?.label??"Whole site",G.location?`, ${G.location.label}`:", No location"]})]},G.id))]})]}),e.jsxs(Ne,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsx("div",{children:e.jsx("h3",{children:Bt.historyTitle})}),H.isFetching&&e.jsx(fe,{tone:"neutral",children:"Loading"})]}),se?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(R,{variant:"outline",onClick:()=>{H.refetch()},children:"Retry history"})]}):H.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):M.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Bt.emptyHistory}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Destination"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:M.map(G=>e.jsxs("tr",{className:k===G.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>h(G.id),children:pf(G.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:G.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:G.requestedModel??G.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:G.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:G.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[G.completedQueries+G.failedQueries,"/",G.totalQueries]}),e.jsx("td",{children:e.jsx(fe,{tone:sd(G.status),children:G.status})})]},G.id))})]})}),H.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Bt.historyMoreError}),H.hasNextPage&&e.jsx(R,{className:"mt-3",variant:"outline",disabled:H.isFetching,onClick:()=>{H.fetchNextPage()},children:H.isFetchingNextPage?Bt.historyLoading:Bt.historyMore})]})]}),!se&&T.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(R,{variant:"outline",onClick:()=>{T.refetch()},children:"Retry results"})]}):se?null:e.jsx(hf,{detail:ee,isLoading:T.isFetching,onReviewForTracking:y?void 0:s})]})}const Ms="mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50",Bn="__none__";function cf(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=xs(),[c,d]=o.useState("once"),[m,u]=o.useState(""),[x,f]=o.useState(""),[p,g]=o.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[y,v]=o.useState(null),[C,b]=o.useState([]),[L,k]=o.useState(""),[h,j]=o.useState({}),[w,P]=o.useState(null),[q,S]=o.useState([]),[V,F]=o.useState(null),[D,K]=o.useState(!1),[H,se]=o.useState(!1),[Q,M]=o.useState(""),[J,E]=o.useState(""),W=o.useRef(null),T=o.useRef(!1),ee=o.useRef(null),_=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";o.useEffect(()=>{g(_),P(null)},[_]);const ae=t.scopeOptions.filter(A=>A.kind==="market"||A.kind==="property"),ie=c==="markets"?"market":"property",Re=ae.filter(A=>A.kind===ie),X=A=>({kind:A.kind,key:A.id,label:A.label,planRevision:l??t.initialScope?.planRevision??0}),ue=A=>A===Bn?null:n.find($e=>$e.label===A),ve=y??t.defaultLocation??Bn,Z=ae.find(A=>`${A.kind}:${A.id}`===p),he=Z?X(Z):null,G=c==="once"?[{scope:he,location:ue(ve)}]:c==="locations"?C.map(A=>({scope:null,location:ue(A)})):C.map(A=>Re.find($e=>`${$e.kind}:${$e.id}`===A)).map(A=>A?{scope:X(A),location:ue(h[`${A.kind}:${A.id}`]??Bn)}:null),me=[...new Map([...q,...t.templates].map(A=>[A.id,A])).values()],De=w?me.find(A=>A.id===w.id):null,ke=w!==null&&De?.version!==w.version,oe=c==="once"?m:x,pe=oe.split(/\r?\n/).filter(A=>A.trim()),we=ho(pe),Ke=[...new Set([...x.matchAll(/\{([^{}]+)\}/g)].map(A=>A[1]))],Me=/[{}]/.test(x.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),O=[];pe.length||O.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),pe.some(A=>A.length>4e3)&&O.push("Keep each query under 4,001 characters."),c!=="once"&&Me&&O.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),G.length||O.push(c==="locations"?"Select at least one location.":"Select at least one destination."),G.some(A=>!A||A.location===void 0)&&O.push("A selected destination or location is no longer available. Update your selection.");const U=c==="once"&&p!=="project"||c==="markets"||c==="properties";U&&(t.scopePending||t.scopeError||!l||G.some(A=>!A?.scope))&&O.push("Load the current published markets and properties before running scoped research.");const B=(c==="once"?we.length:pe.length)*G.length;if(G.length>Oa&&O.push(`Select at most ${Oa} destinations.`),B>Ar&&O.push(`${B} queries selected. Reduce the selection to ${Ar} or fewer.`),ke&&O.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!Me){for(const A of G)if(!(!A||A.location===void 0))try{kr(w??{pattern:x,variables:Ke},A.scope,A.location)}catch{O.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const Te=JSON.stringify({mode:c,source:oe,contexts:G,provider:a,resolvedModel:r,template:w,...U?{planRevision:l}:{}}),He=V!==null&&V.signature!==Te,Be=c==="once"?we.map((A,$e)=>({id:String($e),query:A,scope:he,location:G[0]?.location??null})):V?.rows??[],Ze=mf(Be),xe=[];c!=="once"&&V&&(He&&xe.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Be.some(A=>!A.query.trim()||A.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(A.query))&&xe.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Be.some(A=>A.location&&!n.some($e=>JSON.stringify($e)===JSON.stringify(A.location)))&&xe.push("A preview location changed. Regenerate the preview."),Ze.some(A=>ho(A.queries).length!==A.queries.length)&&xe.push("Remove duplicate queries within each destination and location."),Ze.length>Oa&&xe.push(`The preview exceeds ${Oa} runs.`));const jt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!O.length&&!xe.length&&(c==="once"||V!==null),_e=()=>({runs:Ze.map(A=>({queries:A.queries,provider:a,model:r,location:A.location,...A.scope?{scope:{kind:A.scope.kind,key:A.scope.key,expectedPlanRevision:A.scope.planRevision}}:{},...A.template?{template:A.template}:{}}))}),et=()=>{if(K(!0),O.length)return;const A=G.flatMap(($e,Pe)=>pe.map((ze,wt)=>({id:`${Pe}:${wt}`,scope:$e.scope,location:$e.location,...w?{template:{templateId:w.id,templateVersion:w.version,bindingLocation:$e.location}}:{},query:kr({pattern:ze,variables:[...new Set([...ze.matchAll(/\{([^{}]+)\}/g)].map(it=>it[1]))]},$e.scope,$e.location).output})));F({signature:Te,rows:A})},zt=A=>{d(A),b([]),P(null),k(""),K(!1)},rt=A=>{if(E(""),c==="once")try{u(kr(A,he,ue(ve)).output)}catch{E("Select a matching market, property, or location before using this pattern.");return}else f(A.pattern);P(A)},tt=A=>{const $e=ee.current,Pe=$e?.selectionStart??x.length,ze=$e?.selectionEnd??Pe;f(`${x.slice(0,Pe)}{${A}}${x.slice(ze)}`),P(null),requestAnimationFrame(()=>{$e?.focus(),$e?.setSelectionRange(Pe+A.length+2,Pe+A.length+2)})},pt=Gt({...Uu(),onSuccess:async A=>{const $e={id:A.id,version:A.updatedAt,label:A.name,pattern:A.pattern,variables:A.variables};S(Pe=>[...Pe.filter(ze=>ze.id!==A.id),$e]),P($e),se(!1),M(""),E(""),W.current=null,await i.invalidateQueries({queryKey:Ku({client:ne,path:{name:s}})}),Ee({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>E("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{T.current=!1}}),Nt=()=>{if(!t.canWrite||t.isEmbed||T.current)return;const A=c==="once"?m:x,$e=c==="once"?[]:Ke;if(!Q.trim()||!A.trim()||A.length>4e3||c!=="once"&&Me){E("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const Pe={name:Q.trim(),pattern:A,variables:$e},ze=JSON.stringify(Pe);W.current?.fingerprint!==ze&&(W.current={fingerprint:ze,id:crypto.randomUUID()}),T.current=!0,pt.mutate({client:ne,path:{name:s,templateId:W.current.id},body:Pe})},_t=[...new Set([...D||oe.trim()?O:[],...xe])],Ve=me.filter(A=>{const $e=c==="once"?xo(he,ue(ve)):xo(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return A.variables.every(Pe=>$e[Pe]!==void 0)});return e.jsxs(Ne,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Test queries"}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-secondary",children:"See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics."})]})}),e.jsxs("fieldset",{"aria-label":"Research setup",className:"mt-5 min-w-0 space-y-5",disabled:t.isPending||pt.isPending,children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Run mode"}),e.jsxs("select",{className:Ms,value:c,disabled:t.isPending,onChange:A=>zt(A.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!ae.some(A=>A.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!ae.some(A=>A.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(ae.length>0||p!=="project")&&e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Save results under"}),e.jsxs("select",{className:Ms,value:p,onChange:A=>{g(A.target.value),P(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),p!=="project"&&!Z&&e.jsx("option",{value:p,disabled:!0,children:"Selected destination unavailable"}),ae.map(A=>e.jsxs("option",{value:`${A.kind}:${A.id}`,children:[A.label," (",A.kind,")"]},`${A.kind}:${A.id}`))]})]}),e.jsx(ji,{label:"Answer engine location",value:ve,locations:n,onChange:A=>{v(A),P(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Ms,placeholder:`Search ${c}`,value:L,onChange:A=>k(A.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(A=>({key:A.label,label:A.label})):Re.map(A=>({key:`${A.kind}:${A.id}`,label:A.label}))).filter(A=>A.label.toLocaleLowerCase().includes(L.toLocaleLowerCase())).map(A=>{const $e=C.includes(A.key);return e.jsxs("div",{className:"grid items-center gap-2 border-b border-default pb-2 sm:grid-cols-[minmax(0,1fr)_16rem]",children:[e.jsxs("label",{className:"flex min-h-11 items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:$e,onChange:()=>b(Pe=>$e?Pe.filter(ze=>ze!==A.key):[...Pe,A.key])}),A.label]}),$e&&c!=="locations"&&e.jsx(ji,{label:`Answer engine location for ${A.label}`,value:h[A.key]??Bn,locations:n,onChange:Pe=>j(ze=>({...ze,[A.key]:Pe}))})]},A.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[C.length," selected. A market or property name changes query text, not the answer engine's location."]})]}),t.scopeError&&e.jsxs("p",{className:"text-sm text-caution",children:["Markets and properties could not load. Whole-site and location research remain available. ",e.jsx(R,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:ee,className:`${Ms} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:oe,placeholder:c==="once"?Bt.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:A=>{c==="once"?u(A.target.value):(f(A.target.value),P(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>tt(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[B," / ",Ar," queries",c==="once"?"":` across ${G.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),Ve.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:Ve.map(A=>e.jsx(R,{size:"sm",variant:"outline",onClick:()=>rt(A),children:A.label},A.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),w&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",w.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(R,{size:"sm",variant:"outline",onClick:()=>se(!H),children:H?"Cancel save":"Save as a pattern"}),H&&e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("label",{className:"min-w-48 flex-1 text-sm text-heading",children:["Pattern name",e.jsx("input",{className:Ms,value:Q,maxLength:120,onChange:A=>M(A.target.value)})]}),e.jsx(R,{size:"sm",disabled:pt.isPending||!Q.trim()||!oe.trim(),onClick:Nt,children:pt.isPending?"Saving…":"Save pattern"})]})]}),J&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:J})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Answer engine",e.jsxs("select",{className:Ms,value:a,onChange:A=>t.onProviderChange(A.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(A=>e.jsx("option",{value:A.name,children:A.displayName??A.name},A.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:Ms,value:t.model,disabled:!a||!t.configurableModel,onChange:A=>t.onModelChange(A.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(A=>e.jsx("option",{value:A.id,children:A.displayName},A.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:Ms,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:A=>t.onModelChange(A.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(A=>e.jsx("option",{value:A.id,children:A.displayName},A.id))})]})]})]}),_t.length>0&&e.jsx(uf,{errors:_t}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(R,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:et,children:[e.jsx(ja,{size:14}),V?Bt.refreshPreview:"Preview queries"]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[Be.length," query executions in ",Ze.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(df,{rows:Be,locations:n,onChange:(A,$e)=>F(Pe=>Pe&&{...Pe,rows:Pe.rows.map(ze=>ze.id===A?{...ze,...$e}:ze)})})]})]}),t.errorMessage&&e.jsxs("p",{role:"alert",className:"text-sm text-negative",children:[t.errorMessage," Your entries are preserved. Retry unchanged entries to avoid duplicate work."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!t.isEmbed&&e.jsxs(R,{size:"sm",disabled:!jt,onClick:()=>{if(jt){const A=_e();t.onSubmit(A,JSON.stringify({projectName:s,...A}))}},children:[e.jsx(ur,{size:14}),t.isPending?"Starting…":Bt.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${we.length} queries`:`${Be.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function ji({label:t,value:s,locations:n,onChange:a}){return e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:t}),e.jsxs("select",{className:Ms,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:Bn,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function df({rows:t,locations:s,onChange:n}){return e.jsx("ol",{className:"divide-y divide-default",children:t.map((a,r)=>e.jsxs("li",{className:"grid gap-3 py-4 md:grid-cols-[10rem_minmax(0,1fr)_15rem]",children:[e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"block text-secondary",children:["Query ",r+1]}),e.jsx("span",{className:"font-medium text-heading",children:a.scope?.label??a.location?.label??"Whole site"}),a.scope&&e.jsx("span",{className:"block text-secondary",children:a.scope.kind})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Query",e.jsx("textarea",{className:`${Ms} min-h-20`,"aria-label":`Query ${r+1} for ${a.scope?.label??a.location?.label??"Whole site"}`,value:a.query,onChange:l=>n(a.id,{query:l.target.value})})]}),e.jsx(ji,{label:`Location for query ${r+1}`,value:a.location?.label??Bn,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function uf({errors:t}){return e.jsx("div",{role:"alert",className:"text-sm text-negative",children:e.jsx("ul",{className:"list-disc space-y-1 pl-5",children:t.map(s=>e.jsx("li",{children:s},s))})})}function mf(t){const s=new Map;for(const n of t){const a=JSON.stringify({scope:n.scope,location:n.location,template:n.template}),r=s.get(a)??{scope:n.scope,location:n.location,queries:[],...n.template?{template:n.template}:{}};r.queries.push(n.query),s.set(a,r)}return[...s.values()]}function hf({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=o.useState(null);o.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const l=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(Ne,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":Bt.resultsTitle,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${gf(t.id)}`:Bt.resultsEmpty})]}),t&&e.jsx(fe,{tone:sd(t.status),children:t.status})]}),t&&e.jsxs("div",{className:"mt-3 space-y-3 text-sm text-secondary",children:[e.jsxs("dl",{className:"flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Answer engine"}),e.jsx("dd",{children:t.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Requested model"}),e.jsx("dd",{className:"font-mono",children:t.requestedModel??t.resolvedModel})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Location"}),e.jsx("dd",{children:t.location?.label??"No location"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Destination"}),e.jsx("dd",{children:t.scope?.label??"Whole site"})]})]}),t.template&&e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Bt.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Bt.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Bt.methodology})]})]}),t?e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Brand-name match"}),e.jsx("th",{children:"Project domain cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:l?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(fe,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Bt.brandedQuery:i.queryClass==="non-brand"?Bt.discoveryQuery:Bt.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(fe,{tone:ff(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(fe,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===Rn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===Rn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(fe,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===Rn.failed?"negative":"caution",children:i.citationState===null?i.status===Rn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(xf,{query:l,scope:t.scope??null,isLoading:s,onReviewForTracking:n})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved run to inspect each answer and its source links."})]})}function xf({query:t,isLoading:s,scope:n,onReviewForTracking:a}){return t?e.jsxs("div",{className:"min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),!re()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(Ye,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1",children:e.jsx(Ei,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Rn.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r},r))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r.replace(/^www\./,"")},r))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-3",children:t.groundingSources.map((r,l)=>e.jsx("li",{className:"min-w-0",children:e.jsx(Ii,{url:r.uri,title:r.title})},`${r.uri}-${l}`))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function pf(t){const s=new Date(t);return Number.isNaN(s.valueOf())?t:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(s)}function gf(t){return t.length>8?t.slice(0,8):t}function sd(t){return t===xa.completed?"positive":t===xa.partial?"caution":t===xa.failed?"negative":"neutral"}function ff(t){return t===Rn.completed?"positive":t===Rn.failed?"negative":"neutral"}async function yf(t){await Dt(t,"researchRuns")}const Ni=new Set(["queued","seeding","probing"]);function vf({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:m}=Hs(),[u,x]=o.useState("tracked"),[f,p]=o.useState("find"),[g,y]=o.useState(null),v=m?.role==="viewer"?uc():null,C=Cc(m?.role,v),L=kc(s??u,C),k=a??f,h=P=>{s===void 0&&x(P),n?.(P)},j=P=>{a===void 0&&p(P),r?.(P)},w=(P,q)=>{const S={...l,measurementScope:q?.kind??"project",measurementScopeKey:q?.key};y({...P,trackingSelection:S}),q!==void 0&&i?.({measurementScope:S.measurementScope,measurementScopeKey:S.measurementScopeKey}),h("tracked")};return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"queries-heading",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"queries-heading",children:"Queries"})}),e.jsxs("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Query workspace",children:[e.jsx(yr,{active:L==="tracked",label:"Tracked",onClick:()=>h("tracked")}),C?e.jsx(yr,{active:L==="research",label:"Research",onClick:()=>h("research")}):null]}),e.jsx("div",{className:"mt-4",children:L==="tracked"?e.jsx(Ff,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:g,onPendingTrackingSourceHandled:()=>y(null)}):e.jsx(bf,{projectName:t,selection:l,mode:k,onModeChange:j,onReviewSavedSource:w,onSelectionChange:i,viewerResearchConfig:v})})]})}function yr({active:t,label:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":t,className:`-mb-px border-b-2 px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 focus-visible:ring-inset ${t?"border-mono-400 text-heading":"border-transparent text-muted hover:border-strong hover:text-strong"}`,onClick:n,children:s})}function bf({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=Hs(),c=!i||n==="test",d=Le({...qi({client:ne,path:{name:t}}),enabled:c,staleTime:6e4}),m=Le({...mc({client:ne,path:{name:t}}),enabled:c,staleTime:6e4}),u=o.useMemo(()=>{const p=d.data;if(!p)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const g=new Map(p.targets.map(v=>[v.stableKey,[]]));for(const v of p.groups)for(const C of v.targetKeys)g.get(C)?.push(v.stableKey);const y=new Map(p.markets.map(v=>[v.stableKey,new Set]));for(const v of p.markets)for(const C of v.usageEdges)for(const b of g.get(C.targetKey)??[])y.get(v.stableKey)?.add(b);return[{id:"project",label:"Whole site",kind:"project",targetCount:p.targets.length},...p.groups.map(v=>({id:v.stableKey,label:v.label,kind:"group",targetCount:v.targetKeys.length,...v.parentGroupKey?{parentGroupIds:[v.parentGroupKey]}:{}})),...p.markets.map(v=>{const C=[...y.get(v.stableKey)??[]];return{id:v.stableKey,label:v.label,kind:"market",targetCount:0,...C.length?{parentGroupIds:C}:{}}}),...p.targets.map(v=>({id:v.stableKey,label:v.label,kind:"property",targetCount:1,...g.get(v.stableKey)?.length?{parentGroupIds:g.get(v.stableKey)}:{}}))]},[d.data]),x=o.useMemo(()=>(m.data?.templates??[]).map(p=>({id:p.id,version:p.updatedAt,label:p.name,pattern:p.pattern,variables:p.variables})),[m.data]),f={projectName:t,scopeOptions:u,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const p=u.find(y=>y.kind===s.measurementScope&&y.id===s.measurementScopeKey),g=d.data?.active?.revision;return p&&g&&(p.kind==="market"||p.kind==="property")?{kind:p.kind,key:p.id,label:p.label,planRevision:g,expectedPlanRevision:g}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:g??0,expectedPlanRevision:g??0}:null})(),scopePending:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.refetch()},templates:x};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(yr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(yr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(Gf,{projectName:t,onReviewDiscoveryProbe:p=>r({source:"discovery",discoveryProbeId:p})}):e.jsx(hl,{...f,onReviewForTracking:({researchRunQueryId:p,scope:g})=>r({source:"research",researchRunQueryId:p},g??null)})})]}):e.jsx(hl,{...f,viewerResearchConfig:l})}function jf({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:m,isCommitting:u,onPreview:x,onCommit:f}){const[p,g]=o.useState(null),[y,v]=o.useState(()=>lr(s)),[C,b]=o.useState(null),L=o.useRef(null),k=o.useRef(null),h=Ac(t,s),j=o.useMemo(()=>Cf(t.tracked,s,t.mode),[s,t.mode,t.tracked]),w=rn({rows:j,getSearchText:H=>`${H.queryText} ${H.provenance?.source??"legacy"} ${H.assignments.map(se=>se.queryClass??"unknown").join(" ")}`});o.useEffect(()=>{if(h)return;if(!a){k.current=null;return}const H=`${a}:${Br(s)}`;if(k.current===H)return;const se=t.tracked.find(Q=>Q.queryId===a);se&&(k.current=H,g({kind:"edit",row:se,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Ur(s,t)}),v(xl(se,s)),b(null))},[s,a,h,t]),o.useEffect(()=>{if(h||!l)return;const H=lr(l.trackingSelection??s);g({kind:"add"}),v(l.source==="research"?{...H,source:"research",researchRunQueryId:l.researchRunQueryId}:{...H,source:"discovery",discoveryProbeId:l.discoveryProbeId}),b(null),i()},[i,l,s,h]),o.useEffect(()=>{h&&(g(null),b(null),a!==void 0&&r?.(void 0))},[r,a,h]),o.useEffect(()=>{if(!p||p.kind==="remove")return;const H=L.current;H&&(H.scrollIntoView?.({block:"start"}),H.focus({preventScroll:!0}))},[p]);function P(H="manual"){g({kind:"add"}),v({...lr(s),source:H}),b(null),r?.(void 0)}function q(H){k.current=`${H.queryId}:${Br(s)}`,g({kind:"edit",row:H,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Ur(s,t)}),v(xl(H,s)),b(null),r?.(H.queryId)}function S(H){k.current=`${H.queryId}:${Br(s)}`,g({kind:"remove",row:H,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Ur(s,t)}),b(null),r?.(H.queryId)}function V(){g(null),b(null),r?.(void 0)}const F=p?Nf(p,y,t):null,D=p!==null&&p.kind==="add"&&t.mode==="advanced"&&!Vi(y),K=F!==null&&(!D||y.contexts.length>0)&&!m;return h?e.jsx("div",{className:"query-tracking-workspace space-y-4",children:e.jsxs("section",{"aria-label":"Tracked queries",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["This saved ",s.measurementScope," filter is unavailable in the current measurement."]}),e.jsx(R,{type:"button",variant:"outline",className:"mt-3",onClick:()=>n?.({measurementScope:"project",measurementScopeKey:void 0}),children:"Show whole site"})]})}):e.jsxs("div",{className:"query-tracking-workspace space-y-4",children:[e.jsxs("section",{"aria-label":"Tracked queries",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[t.mode==="advanced"?e.jsx(kf,{selection:s,onSelectionChange:n}):null,e.jsx(Vs,{value:w.query,onChange:w.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!re()&&e.jsxs(Ye,{type:"button",size:"sm",onClick:()=>P(),children:[e.jsx(nx,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[w.totalRows.toLocaleString("en-US")," saved query ",w.totalRows===1?"record":"records"," in this view. Each record can have more than one property, group, or market assignment."]}),s.measurementScope==="group"?e.jsx("p",{className:"mt-1 text-xs leading-5 text-secondary",children:"Queries belong to properties, so a shared query can also cover other groups."}):null,t.active?null:e.jsx("p",{className:"mt-3 text-sm text-caution",children:"No published measurement yet."}),w.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:w.hasQuery?"No tracked queries match that search.":"No tracked queries in this scope yet."}):e.jsx("div",{className:"mt-5 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table min-w-[760px] table-auto",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Scope"}),t.mode==="advanced"?e.jsx("th",{children:"Class"}):null,e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Measurement"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:w.rows.map(H=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:H.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(Rf,{row:H,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(If,{row:H})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:Af(H)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Tf,{row:H,outsidePlan:t.mode==="advanced"&&H.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!re()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${H.queryText}`,onClick:()=>q(H),children:[e.jsx(ax,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${H.queryText}`,onClick:()=>S(H),children:[e.jsx(Sc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},H.queryId))})]})}),e.jsx(Ds,{page:w.page,pageSize:w.pageSize,visibleRows:w.rows.length,totalRows:w.totalRows,itemLabel:"queries",onPageChange:w.setPage})]}),p&&!re()&&e.jsx(Lf,{workspace:t,templates:c,action:p,draft:y,onDraftChange:H=>{v(H),b(null)},onClose:V,canReview:K,isPreviewing:m,editorHeadingRef:L,onReview:()=>{F&&(b(F),x(F))}}),d&&C&&p&&e.jsx(Ef,{preview:d,workspace:t,isCommitting:u,onConfirm:()=>{f({...C,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function lr(t){return{source:"manual",text:"",templateId:"",templateVersion:"",template:"",researchRunQueryId:"",discoveryProbeId:"",wholeSite:!1,targetKeys:t.measurementScope==="property"&&t.measurementScopeKey?[t.measurementScopeKey]:[],groupKeys:t.measurementScope==="group"&&t.measurementScopeKey?[t.measurementScopeKey]:[],marketKeys:t.measurementScope==="market"&&t.measurementScopeKey?[t.measurementScopeKey]:[],contexts:[],queryClass:"auto"}}function xl(t,s){return{...lr(s),text:t.queryText,queryClass:"keep"}}function Nf(t,s,n){const a=n.mode==="advanced";if(t.kind==="remove")return{additions:[],removals:[{queryId:t.row.queryId,...t.audience?{audience:t.audience}:{}}]};if(t.kind==="edit")return s.text.trim()?{additions:[],removals:[],edits:[{queryId:t.row.queryId,text:s.text.trim(),...t.audience?{audience:t.audience}:{},...a&&s.queryClass!=="keep"?{queryClass:s.queryClass==="auto"?null:s.queryClass}:{}}]}:null;const r=wf(s);if(!r||wi(s)||a&&!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const l=a?Sf(s,n):void 0;return{additions:[{input:r,...l?{audience:l}:{},...a&&!Vi(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...a&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function wf(t){return t.source==="manual"?t.text.trim()?{source:"manual",text:t.text.trim()}:null:t.source==="template"?t.templateId&&t.templateVersion&&t.template?{source:"template",templateId:t.templateId,templateVersion:t.templateVersion,template:t.template}:null:t.source==="research"?t.researchRunQueryId?{source:"research",researchRunQueryId:t.researchRunQueryId}:null:t.discoveryProbeId?{source:"discovery",discoveryProbeId:t.discoveryProbeId}:null}function Sf(t,s){if(t.wholeSite)return{targetKeys:s.targets.map(a=>a.stableKey)};const n={...t.targetKeys.length>0?{targetKeys:t.targetKeys}:{},...t.groupKeys.length>0?{groupKeys:t.groupKeys}:{},...t.marketKeys.length>0?{marketKeys:t.marketKeys}:{}};return Object.keys(n).length>0?n:void 0}function Vi(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function wi(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Kr(t){if(t.measurementScopeKey){if(t.measurementScope==="property")return{targetKeys:[t.measurementScopeKey]};if(t.measurementScope==="group")return{groupKeys:[t.measurementScopeKey]};if(t.measurementScope==="market")return{marketKeys:[t.measurementScopeKey]}}}function Ur(t,s){const a=(t.measurementScope==="property"?s.targets:t.measurementScope==="group"?s.groups:t.measurementScope==="market"?s.markets:[]).find(r=>r.stableKey===t.measurementScopeKey)?.label;return a?t.measurementScope==="group"?`${a} · Group`:t.measurementScope==="market"?`${a} · Market`:a:"Whole site"}function zi(t,s){return s.queryClass!=="all"&&(t.queryClass??"unknown")!==s.queryClass?!1:s.measurementScope==="project"||!s.measurementScopeKey?!0:s.measurementScope==="property"?t.targetKey===s.measurementScopeKey:s.measurementScope==="group"?t.groupKeys.includes(s.measurementScopeKey):t.marketKeys.includes(s.measurementScopeKey)}function Cf(t,s,n){return n==="simple"?[...t]:t.filter(a=>a.assignments.length===0?s.measurementScope==="project"&&(s.queryClass==="all"||s.queryClass==="unknown"):a.assignments.some(r=>zi(r,s)))}function kf({selection:t,onSelectionChange:s}){return e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-xs font-medium text-secondary",children:"Query type"}),e.jsxs("select",{"aria-label":"Query type",className:"h-11 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:t.queryClass,onChange:n=>s?.({queryClass:n.target.value}),children:[e.jsx("option",{value:"all",children:"All query types"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"unknown",children:"Unclassified"})]})]})}function Br(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function Af(t){switch(t.provenance?.source){case"manual":return"Manual";case"template":return"Template";case"research":return"Saved research";case"discovery":return"Discovery";default:return"Legacy"}}function nd(t,s,n){const a=new Map(s.targets.map(y=>[y.stableKey,y.label])),r=new Map(s.groups.map(y=>[y.stableKey,y.label])),l=new Map(s.markets.map(y=>[y.stableKey,y.label])),i=new Set(t.assignments.map(y=>y.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(y=>zi(y,n)):t.assignments,d=new Set(c.map(y=>y.targetKey));if(n?.measurementScope==="group"){const y=d.size,v=Math.max(0,i.size-y);return[`${y} ${y===1?"property":"properties"} in this group`,...v?[`Shared with ${v} other ${v===1?"property":"properties"}`]:[]].join(" · ")}const m=new Set,u=new Set;for(const y of c)y.groupKeys.forEach(v=>m.add(v)),y.marketKeys.forEach(v=>u.add(v));const f=n?.measurementScope==="property"&&i.has(n.measurementScopeKey??"")?i.size===1?["This property only"]:["This property",`Shared with ${i.size-1} other ${i.size===2?"property":"properties"}`]:d.size===1?[a.get([...d][0])??[...d][0]]:[`${d.size} properties`],p=m.size===1?r.get([...m][0])??[...m][0]:null,g=u.size===1?l.get([...u][0])??[...u][0]:null;return p&&g&&p===g?f.push(`${p} (group and market)`):(p?f.push(`Group: ${p}`):m.size>1&&f.push(`${m.size} groups`),g?f.push(`Market: ${g}`):u.size>1&&f.push(`${u.size} markets`)),f.join(" · ")}function Rf({row:t,workspace:s,selection:n}){const a=Pf(t,s,n);return e.jsxs("details",{className:"group min-w-48",children:[e.jsx("summary",{className:"cursor-pointer rounded px-1 py-1 text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:nd(t,s,n)}),e.jsxs("div",{className:"mt-2 rounded border border-default bg-surface p-2 text-xs leading-5 text-secondary",children:[e.jsx("p",{className:"font-medium text-strong",children:"Assigned relationships"}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-4",children:a.map(r=>e.jsx("li",{children:r},r))})]})]})}function Pf(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),l=new Map(s.markets.map(d=>[d.stableKey,d.label])),c=t.assignments.filter(d=>zi(d,n)).map(d=>{const m=a.get(d.targetKey)??d.targetKey??"Whole site",u=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(f=>f===n.measurementScopeKey).map(f=>r.get(f)??f):d.groupKeys.map(f=>r.get(f)??f),x=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(f=>f===n.measurementScopeKey).map(f=>l.get(f)??f):d.marketKeys.map(f=>l.get(f)??f);return[m,u.length?`Groups: ${u.join(", ")}`:null,x.length?`Markets: ${x.join(", ")}`:null].filter(f=>f!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function If({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(fe,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function Tf({row:t,outsidePlan:s=!1}){return s?e.jsx(fe,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(fe,{tone:"positive",children:"Measured"}):e.jsx(fe,{tone:"caution",children:"Awaiting sweep"})}function Lf({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:m}){const u=s.length>0;return n.kind==="remove"?e.jsxs(Ne,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Remove query"}),e.jsxs("p",{className:"mt-1 text-sm leading-6 text-secondary",children:["Remove “",n.row.queryText,"” from future tracking?"]}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-secondary",children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:"All assignments will be removed."," Earlier results stay unchanged."]})]})}),e.jsx(Vr,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):n.kind==="edit"?e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange:x=>r({...a,text:x.target.value})})]}),t.mode==="advanced"&&e.jsxs("label",{className:"block",htmlFor:"tracking-query-class",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:x=>r({...a,queryClass:x.target.value}),children:[e.jsx("option",{value:"keep",children:"Keep existing classifications"}),e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Existing locations and engines are preserved. Use Add query to create assignments in another scope."})]}),e.jsx(Vr,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Add query"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("div",{className:`mt-4 grid gap-4 ${t.mode==="advanced"?"lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]":"max-w-2xl"}`,children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:x=>r({...a,text:x.target.value})})]}):null,a.source==="template"?e.jsx($f,{templates:s,advanced:t.mode==="advanced",draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(pl,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(x=>({id:x.researchRunQueryId,label:x.queryText,detail:x.researchRunId})),onChange:x=>r({...a,researchRunQueryId:x})}):null,a.source==="discovery"?e.jsx(pl,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(x=>({id:x.discoveryProbeId,label:x.queryText,detail:x.discoverySessionId})),onChange:x=>r({...a,discoveryProbeId:x})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source","aria-describedby":u?void 0:"tracking-query-source-no-templates",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:x=>r({...a,source:x.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),u?e.jsx("option",{value:"template",children:"Saved template"}):null,e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]}),u?null:e.jsx("p",{id:"tracking-query-source-no-templates",className:"text-sm leading-6 text-secondary",children:"No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result."})]}),t.mode==="advanced"?e.jsx(Mf,{workspace:t,draft:a,onDraftChange:r}):null]}),t.mode==="advanced"&&!Vi(a)?e.jsx("div",{className:"mt-4",children:e.jsx(qf,{workspace:t,draft:a,onDraftChange:r})}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Measurement options"}),e.jsx("div",{className:"grid gap-4 pb-3 sm:grid-cols-2",children:t.mode==="advanced"?e.jsxs("div",{className:"block",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",htmlFor:"tracking-query-class",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:x=>r({...a,queryClass:x.target.value}),children:[e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}):e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:"Automatic"})]})})]}),a.source==="research"&&e.jsx("p",{className:"mt-4 rounded-md border border-default bg-surface-subtle px-3 py-2 text-sm text-secondary",children:"Only the saved query is added."}),e.jsx(Vr,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]})}function $f({templates:t,advanced:s,draft:n,onDraftChange:a}){return e.jsxs("div",{children:[e.jsxs("label",{className:"block",htmlFor:"tracking-template-source",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Saved template"}),e.jsxs("select",{id:"tracking-template-source","aria-describedby":wi(n)?"tracking-template-market-required":void 0,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:n.templateId,onChange:r=>{const l=t.find(i=>i.id===r.target.value);a({...n,templateId:l?.id??"",templateVersion:l?.updatedAt??"",template:l?.pattern??""})},children:[e.jsx("option",{value:"",children:"Choose a template"}),t.map(r=>e.jsx("option",{value:r.id,children:r.name},r.id))]}),n.template?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted",children:n.template}):null]}),wi(n)?e.jsx("p",{id:"tracking-template-market-required",role:"status",className:"mt-2 text-sm leading-5 text-caution",children:s?"Choose a Market under Apply to for this template. A location alone does not select a market.":"This template needs a market, and this project has no markets. Write a question instead."}):null]})}function pl({id:t,label:s,value:n,options:a,onChange:r}){return e.jsxs("label",{className:"block",htmlFor:t,children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:s}),e.jsxs("select",{id:t,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:n,onChange:l=>r(l.target.value),children:[e.jsx("option",{value:"",children:"Choose a saved query"}),a.map(l=>e.jsxs("option",{value:l.id,children:[l.label," · ",l.detail]},l.id))]})]})}function Qi(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function ua(t){return JSON.stringify({providers:[...t.providers].sort(),models:Object.fromEntries(Object.entries(t.models).sort(([s],[n])=>s.localeCompare(n))),location:t.location})}function ad(t){return[...new Map(t.map(s=>[ua(s),s])).values()]}function Hi(t){const s=t.providers.map(n=>{const a=t.models[n];return a?`${n} (${a})`:n}).join(", ");return`${t.location??"No location"} · ${s}`}function qf({workspace:t,draft:s,onDraftChange:n}){const a=o.useMemo(()=>ad([...t.defaultContexts.map(Qi),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?ua(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:l=>{const i=a.find(d=>ua(d)===l.target.value),c=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(l=>e.jsx("option",{value:ua(l),children:Hi(l)},ua(l)))]}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-secondary",children:a.length===0?"No configured measurement context is available.":"Choose where this query will be measured."})]})}function Mf({workspace:t,draft:s,onDraftChange:n}){const{canWrite:a}=Hs(),[r,l]=o.useState(""),[i,c]=o.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),d=o.useMemo(()=>[...t.targets.map(g=>({kind:"target",key:g.stableKey,label:g.label,detail:"Property"})),...t.groups.map(g=>({kind:"group",key:g.stableKey,label:g.label,detail:"Group"})),...t.markets.map(g=>({kind:"market",key:g.stableKey,label:g.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),m=r.trim().toLocaleLowerCase(),u=m?d.filter(g=>`${g.label} ${g.detail}`.toLocaleLowerCase().includes(m)):d,x=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function f(g,y,v){const C=g==="target"?"targetKeys":g==="group"?"groupKeys":"marketKeys",b=s[C];n({...s,wholeSite:!1,[C]:v?[...b,y]:b.filter(L=>L!==y)})}function p(g,y){return(g==="target"?s.targetKeys:g==="group"?s.groupKeys:s.marketKeys).includes(y)}if(!i){const g=t.targets.find(y=>y.stableKey===s.targetKeys[0]);return e.jsxs("fieldset",{className:"self-start rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-sm text-strong",children:["Property: ",g?.label??s.targetKeys[0]]}),e.jsx(R,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>c(!0),children:"Change"})]})]})}return e.jsxs("fieldset",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Choose where this question should be tracked."}),a?e.jsxs("label",{className:"mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-sm text-strong",children:[e.jsx("input",{type:"checkbox",checked:s.wholeSite,onChange:g=>{n({...s,wholeSite:g.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Every location (",t.targets.length,")"]}):null,!s.wholeSite&&!x?e.jsx("p",{role:"status",className:"mt-2 text-sm text-caution",children:"Choose at least one location, group, or market."}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsx(Vs,{value:r,onChange:l,label:"Filter assignments",placeholder:"Search Properties, Groups, Markets",className:"mt-3"}),e.jsx("div",{className:"mt-3 max-h-64 space-y-1 overflow-y-auto pr-1",children:u.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):u.map(g=>e.jsxs("label",{className:"flex min-h-9 items-center gap-2 rounded px-1 py-1 text-sm text-strong hover:bg-surface-hover",children:[e.jsx("input",{type:"checkbox","aria-label":`${g.label}, ${g.detail}`,checked:p(g.kind,g.key),onChange:y=>f(g.kind,g.key,y.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:g.label}),e.jsx("span",{className:"text-xs text-muted",children:g.detail})]},`${g.kind}:${g.key}`))})]})}function Vr({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(Ye,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Publishing does not run a sweep."})]})}function Ef({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=o.useRef(null);o.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const l=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:l?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:l?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(fe,{tone:l?"caution":"neutral",children:l?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(gl,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(gl,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(Ye,{type:"button",size:"sm",disabled:!l||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function gl({label:t,rows:s,workspace:n,tracked:a}){return e.jsxs("section",{"aria-label":`${t} queries`,children:[e.jsxs("p",{className:"text-xs font-medium text-secondary",children:[s.length," ",t.toLocaleLowerCase(),s.length===1?"":"s"]}),e.jsx("ul",{className:"mt-2 divide-y divide-default",children:s.map(r=>e.jsxs("li",{className:"py-2 text-sm",children:[e.jsx("p",{className:"font-medium text-strong",children:r.queryText}),e.jsx("p",{className:"mt-1 text-secondary",children:t==="Removed"?`${r.assignmentCount} ${r.assignmentCount===1?"assignment":"assignments"} removed`:Of(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(Df,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function Df({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const l=s.targets.find(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>Hi(Qi(d))).join("; ");return e.jsx("li",{children:[l,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function Of(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=ad(a.assignments.flatMap(i=>i.contexts).map(Qi)),l=r.length===1?Hi(r[0]):r.length>1?`${r.length} contexts`:null;return[nd(a,n),l].filter(i=>i!==null).join(" · ")}function Ff({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i}){const c=xs(),[d,m]=o.useState(null),u=Le({...qi({client:ne,path:{name:t}})}),x=Le({...mc({client:ne,path:{name:t}}),staleTime:6e4}),f=Gt({...Vu(),onSuccess:g=>m(g),onError:async g=>{m(null),await c.invalidateQueries({queryKey:Bu({client:ne,path:{name:t}})}),Ee({title:"Could not review tracking changes",detail:g instanceof Error?g.message:"Update the draft and review it again.",tone:"negative"})}}),p=Gt({...zu(),onSuccess:async g=>{m(null),r?.(void 0),await po(c,t),Ee({title:g.committed?"Tracked queries updated":"No tracked-query change",detail:g.active?`Measurement revision ${g.active.revision}.`:"No measurement revision is published yet.",tone:g.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async g=>{m(null),await po(c,t),Ee({title:"Could not confirm tracking changes",detail:g instanceof Error?g.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return u.isLoading?e.jsx(Ne,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):u.isError||!u.data?e.jsxs(Ne,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(jf,{workspace:u.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:x.data?.templates??[],preview:d,isPreviewing:f.isPending,isCommitting:p.isPending,onPreview:g=>{m(null),f.mutate({client:ne,path:{name:t},body:{...g,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:g=>p.mutate({client:ne,path:{name:t},body:g})})}function Gf({projectName:t,onReviewDiscoveryProbe:s}){const n=xs(),[a,r]=o.useState(null),[l,i]=o.useState(""),[c,d]=o.useState("100"),m=Le({...Qu({client:ne,path:{name:t},query:{limit:"10"}}),refetchInterval:b=>b.state.data?.some(k=>Ni.has(k.status))?3e3:!1}),u=m.data??[];o.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const x=u.find(b=>b.id===a)??null,f=Le({...Hu({client:ne,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:x&&Ni.has(x.status)?3e3:!1}),p=f.data??null,g=Gt({mutationFn:()=>{const b={},L=l.trim();L&&(b.icpDescription=L);const k=Number.parseInt(c,10);return Number.isFinite(k)&&k>0&&(b.maxProbes=k),Wu(t,b)},onSuccess:async b=>{r(b.sessionId),i(""),await Bf(n,t,b.sessionId),Ee({title:"Discovery started",detail:`Run ${zr(b.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${b.sessionId}`,dedupeMode:"replace"})},onError:b=>{Ee({title:"Discovery failed to start",detail:b instanceof Error?b.message:"Could not start discovery.",tone:"negative"})}}),y=p??x,v=o.useMemo(()=>(p?.probes??[]).slice(0,30),[p?.probes]);async function C(){try{const b=await m.refetch();if(b.error)throw b.error;const L=b.data?.length??0;Ee({title:"Discovery sessions refreshed",detail:`${L} recent session${L===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(b){Ee({title:"Discovery refresh failed",detail:b instanceof Error?b.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:re()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{C()},children:[e.jsx(ja,{className:`size-3.5 ${m.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(fe,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:l,onChange:b=>i(b.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:c,onChange:b=>d(b.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!re()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:g.isPending,onClick:()=>g.mutate(),children:[e.jsx(ur,{size:14}),g.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),m.isFetching&&e.jsx(fe,{tone:"neutral",children:"Loading"})]}),u.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:u.map(b=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===b.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(b.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:zr(b.id)}),e.jsx(fe,{tone:fl(b.status),children:b.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",b.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",b.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",b.wastedCount??0]})]})]},b.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:y?zr(y.id):"No run selected"})]}),y&&e.jsx(fe,{tone:fl(y.status),children:y.status})]}),y?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Qa,{label:"Questions tested",value:y.probeCount??0}),e.jsx(Qa,{label:"Cited queries",value:y.citedCount??0,tone:"positive"}),e.jsx(Qa,{label:"Worth tracking",value:y.aspirationalCount??0,tone:"caution"}),e.jsx(Qa,{label:"Skip",value:y.wastedCount??0,tone:"negative"})]}),y.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:y.error}),y.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:y.warning}),y.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:y.icpDescription})]}),y.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:y.competitorMap.slice(0,8).map(b=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[b.domain," ",e.jsx("span",{className:"text-muted",children:b.hits})]},b.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),y?.status==="completed"&&e.jsxs(Ne,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Review a discovery question for tracking"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:"Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-sweep change."})]})}),e.jsx("p",{className:"mt-3 text-xs leading-5 text-muted",children:"Discovery remains research. This review does not add competitors or start a sweep."})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),f.isFetching&&e.jsx(fe,{tone:"neutral",children:"Loading"})]}),v.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:v.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:b.query}),e.jsx("td",{children:e.jsx(fe,{tone:_f(b.bucket),children:Uf(b.bucket)})}),e.jsx("td",{className:"text-secondary",children:b.citedDomains.length>0?b.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!re()&&s&&(b.bucket==="cited"||b.bucket==="aspirational")&&e.jsx(Ye,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(b.id),children:"Review for tracking"})})]},b.id))})]})})]})]})]})]})}function Qa({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function fl(t){return t==="completed"?"positive":t==="failed"?"negative":Ni.has(t)?"caution":"neutral"}function _f(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Kf={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Uf(t){return t?Kf[t]:"Not classified"}function zr(t){return t.length>8?t.slice(0,8):t}async function Bf(t,s,n){await Promise.all([Dt(t,"discovery"),t.invalidateQueries({queryKey:Yu({client:ne})})])}function Vf({projectName:t}){const[s,n]=o.useState("changes"),[a,r]=o.useState(null),[l,i]=o.useState(null),c=Le({...Ju({client:ne,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=Le({...Xu({client:ne,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),m=(d.data??[]).filter(v=>(v.status==="completed"||v.status==="partial")&&v.trigger!=="probe").reverse(),u=l??m[0]?.id??"",x=a??m.find(v=>v.id!==u)?.id??"",f=!!(x&&u&&x!==u),p=Le({...Zu({client:ne,path:{name:t},query:{run1:x,run2:u}}),enabled:s==="compare"&&f}),g=c.data??[],y=p.data?.diff.filter(v=>v.changed||v.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([v,C])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===v,className:`filter-chip ${s===v?"filter-chip-active":""}`,onClick:()=>n(v),children:C},v))}),s==="changes"?e.jsx(ux,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&g.length===0?e.jsxs(Ne,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Yt()?Yn:"Complete an answer visibility sweep to create the first snapshot."})]}):null,g.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:g.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(v.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[v.mentionedPairs,"/",v.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Xe(v.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[v.citedPairs,"/",v.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Xe(v.overallCitedRate)})]},v.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:x,onChange:v=>r(v.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(v=>e.jsx("option",{value:v.id,children:new Date(v.createdAt).toLocaleString()},v.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:u,onChange:v=>i(v.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(v=>e.jsx("option",{value:v.id,children:new Date(v.createdAt).toLocaleString()},v.id))})]})]}),d.isLoading||p.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&m.length<2?e.jsxs(Ne,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Yt()?Yn:"Run another answer visibility sweep before comparing historical evidence."})]}):null,p.data&&y.length===0?e.jsxs(Ne,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,y.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:y.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:v.query??"Archived query"}),e.jsx("td",{children:e.jsxs(fe,{tone:v.changed?"caution":"neutral",children:[v.run1State??"none"," → ",v.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(fe,{tone:v.visibilityChanged?"caution":"neutral",children:[v.run1MentionState??"none"," → ",v.run2MentionState??"none"]})})]},v.queryId??v.query??"unknown"))})]})}):null]}):null]})}const yl={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},zf={contract:null,assessment:null,googleAds:yl,gtm:yl,snapshots:[]};function Qf(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Jf(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Hf(t){switch(t){case"configured":return{label:"Configured",detail:"The conversion is declared, but the static configuration is not yet proven consistent.",tone:"caution"};case"static-mismatch":return{label:"Static mismatch",detail:"Stored configuration does not match the declared conversion. Review the failing checks before relying on it.",tone:"negative"};case"statically-consistent":return{label:"Statically consistent",detail:"Stored Google Ads and Tag Manager configuration aligns with the declared conversion.",tone:"positive"};case"runtime-unverified":return{label:"Runtime verification needed",detail:"The stored configuration aligns, but a real browser event has not been observed.",tone:"caution"};case"observed":return{label:"Observed",detail:"Stored static evidence and a runtime observation support this conversion path.",tone:"positive"};case"not-configured":return{label:"Setup needed",detail:"Connect both providers, select their resources, then declare the conversion Canonry should inspect.",tone:"neutral"};case"contract-selection-required":return{label:"Choose conversion",detail:"Choose one of the declared conversions before Canonry evaluates its evidence.",tone:"neutral"};case"assessment-loading":return{label:"Checking configuration",detail:"Canonry is loading the selected conversion assessment.",tone:"neutral"};case"assessment-unavailable":return{label:"Assessment unavailable",detail:"The selected conversion could not be assessed. Retry before treating static evidence as current.",tone:"negative"}}}function Wf(t){switch(t.googleAds.state){case"not-connected":return{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."};case"selection-required":return{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."};case"stale":return{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."};default:return null}}function Yf(t){switch(t.gtm.state){case"not-connected":return{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."};case"selection-required":return{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."};case"stale":return{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."};default:return null}}function rd(t){return t.googleAds.state==="not-connected"?{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."}:t.googleAds.state==="unavailable"||t.gtm.state==="unavailable"?{id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."}:t.googleAds.state==="selection-required"?{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."}:t.googleAds.state==="stale"?{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."}:t.gtm.state==="not-connected"?{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."}:t.gtm.state==="selection-required"?{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."}:t.gtm.state==="stale"?{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."}:t.contractSelectionRequired?{id:"select-contract",label:"Select conversion",detail:"Choose the declared conversion Canonry should assess."}:t.contract?t.assessmentState==="loading"?{id:"waiting-for-integrity",label:"Checking configuration…",detail:"Canonry is loading the selected conversion assessment."}:t.assessmentState==="unavailable"?{id:"retry-integrity",label:"Retry assessment",detail:"Retry the selected conversion assessment before acting on its evidence."}:t.assessment?.status==="runtime-unverified"?{id:"review-runtime-verification",label:"Review runtime verification",detail:"Static configuration is aligned. Verify a real browser event separately."}:t.assessment?.status==="configured"&&Xf(t)?{id:"review-findings",label:"Review findings",detail:"Resolve the mismatched or unknown checks before treating this conversion as ready."}:{id:"sync-static-evidence",label:"Refresh static evidence",detail:"Queue fresh read-only Google Ads and Tag Manager observations."}:{id:"declare-contract",label:"Declare conversion",detail:"Name the website event, Google Ads action, and Tag Manager tag that must agree."}}function Jf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Xf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function id(t){switch(t){case"connected":return{label:"Connected",tone:"positive"};case"stale":return{label:"Needs refresh",tone:"caution"};case"selection-required":return{label:"Selection needed",tone:"caution"};case"not-connected":return{label:"Not connected",tone:"neutral"};case"unavailable":return{label:"Unavailable",tone:"negative"}}}function Zf(t,s){return t==="configured"?s==="not-configured"||s==="contract-selection-required"?"neutral":"positive":t==="static"?s==="assessment-unavailable"?"negative":s==="assessment-loading"?"neutral":s==="static-mismatch"?"negative":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"positive":s==="configured"?"caution":"neutral":s==="observed"?"positive":s==="runtime-unverified"?"caution":"neutral"}function ey(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function wn(t){return t.length<=12?t:`…${t.slice(-10)}`}function ty(t){const s=[];return t.googleAds.requirePrimaryAction&&s.push("primary action"),t.googleAds.requireBiddableGoal&&s.push("biddable goal"),s.length>0?s.join(" and "):"No bidding-goal assertion"}function sy(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"No additional event fields required"}const Qr={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function vl(t){return t.outcome==="pass"?{label:Qr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Qr[t.code],tone:"negative",outcome:"Fail"}:{label:Qr[t.code],tone:"caution",outcome:"Unknown"}}function ny(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function ay(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("conversion value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"no additional event fields"}function ry(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function bl({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=id(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(fe,{tone:l.tone,children:l.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Xt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const iy="A conversion names the website event, the Google Ads conversion action, and the Tag Manager tag that must agree. It needs both connections selected because it references resources from each.",oy="Available once Google Ads and Tag Manager are connected.",ly="Check that a conversion is wired the same way in Google Ads and Tag Manager, so the numbers you optimise against are the ones your site actually sends. Canonry only reads the configuration; it never changes or publishes it.";function cy({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:l}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",m=t.gtm.state==="unavailable",u=d||m||t.gtm.state==="unavailable",x={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},f=!i&&!c,p=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?x:Wf(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:m?x:Yf(t)}],g=i&&c&&!u?rd(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Oe,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),f?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:ly}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Oe,{text:iy})]}),g&&s?e.jsx(Ye,{type:"button",disabled:r,onClick:()=>s(g.id),children:r?"Working…":g.label}):e.jsx("p",{className:"text-sm text-secondary",children:oy})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:p.map(y=>{const v=y.ready?{label:"Ready",tone:"positive"}:id(y.state),C=y.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:y.title}),e.jsx(fe,{tone:v.tone,children:v.label}),y.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:y.summary}):null,C&&s?C.id==="retry-connection-status"?e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):null,y.summary&&y.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":y.changeLabel,disabled:r,onClick:y.onChange,children:"Change"}):null]},y.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function dy({workspace:t=zf,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:m,onChangeGoogleAdsSelection:u,onChangeGtmSelection:x,onAddContract:f}){const p=Qf(t),g=Hf(p),y=rd(t),v=t.assessment?.findings??[],C=v.filter(h=>h.outcome!=="pass"),b=v.filter(h=>h.outcome==="pass"),L=C.some(h=>h.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(cy,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:x,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(fe,{tone:g.tone,children:g.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Xt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:g.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(h=>e.jsxs("li",{className:"break-words",children:[ry(h)," ",h.kind,", captured ",Xt(h.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",h.id,")"]})]},h.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?y.id==="review-findings"||y.id==="review-runtime-verification"||y.id==="retry-connection-status"||y.id==="select-contract"||y.id==="retry-integrity"||y.id==="waiting-for-integrity"?e.jsx(R,{type:"button",disabled:n||y.id==="waiting-for-integrity",onClick:()=>s(y.id),children:n?"Working…":y.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(y.id),children:n?"Working…":y.label}):y.id==="review-findings"?e.jsx(R,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):p==="runtime-unverified"?e.jsx(R,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:y.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&f?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:f,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:l??"",onChange:h=>i?.(h.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(h=>e.jsx("option",{value:h.id,children:h.name},h.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:ty(t.contract)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Tag Manager"}),e.jsxs("dd",{className:"mt-1 text-sm text-secondary",children:[t.contract.gtm.triggerIds.length," ",t.contract.gtm.triggerIds.length===1?"trigger":"triggers"," and ",t.contract.gtm.variableIds.length," ",t.contract.gtm.variableIds.length===1?"variable":"variables"," required"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Runtime event fields"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:sy(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:wn(t.contract.googleAds.customerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads conversion action"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:wn(t.contract.googleAds.conversionActionId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager container"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:wn(t.contract.gtm.containerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager tag"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:wn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(R,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),C.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(fe,{tone:L,children:[C.length," ",C.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:C.map(h=>{const j=vl(h);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:j.label}),e.jsx(fe,{tone:j.tone,children:j.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",h.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",h.code]}),h.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",h.evidenceIds.join(", ")]}):null]},`${h.code}:${h.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Oe,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(h=>{const j=Zf(h.key,p);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${j==="positive"?"bg-positive-fill":j==="caution"?"bg-caution-fill":j==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:h.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:h.detail}),e.jsx(fe,{tone:j,children:ey(h.key,p)})]},h.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[bl({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),bl({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:x}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&m?e.jsx(R,{type:"button",variant:"outline",className:"mt-3",onClick:m,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(h=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:h.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:h.kind}),e.jsx("td",{className:"text-secondary",children:Xt(h.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:wn(h.id)})]},h.id))})]})})]}):null,b.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[b.length," ",b.length===1?"passing check":"passing checks"," from the latest assessment"]}),e.jsx("div",{className:"findings-table-wrap mt-3",children:e.jsxs("table",{className:"findings-table",children:[e.jsx("caption",{className:"sr-only",children:"Conversion integrity findings"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Check"}),e.jsx("th",{scope:"col",children:"Result"}),e.jsx("th",{scope:"col",children:"Subject"})]})}),e.jsx("tbody",{children:b.map(h=>{const j=vl(h);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:j.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",h.code]}),h.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",h.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(fe,{tone:j.tone,children:j.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:h.subject})]},`${h.code}:${h.subject}`)})})]})})]}):null,p==="runtime-unverified"?e.jsxs("section",{id:"conversion-integrity-runtime-guidance",className:"page-section-divider","aria-labelledby":"conversion-integrity-runtime-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Runtime verification"}),e.jsx("h3",{id:"conversion-integrity-runtime-title",className:"text-base font-semibold text-heading",children:"Runtime verification checklist"})]})}),e.jsxs("ol",{className:"max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted",children:[e.jsxs("li",{children:["Use a controlled browser session on ",ny(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:wn(t.contract.gtm.tagId)})," fires with ",ay(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:wn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Sn=3e4,jl={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Ut="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",ds="text-sm font-medium text-secondary";function Nl(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:Ct(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Ha(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function uy(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Google Ads connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Google Ads OAuth connection is stored for this project.",lastSnapshotAt:null};if(t.status==="selection-required"){const r=t.connection.selection.customerId;return r?{state:"stale",selection:`Selected customer ${r}`,...s,evidence:"A customer is selected, but Canonry needs a fresh conversion-goal observation.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}:{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs a customer account selection.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}const a=t.selectedCustomer;return{state:t.status,selection:a.descriptiveName??`Selected customer ${a.customerId}`,...s,evidence:t.status==="stale"?"The selected customer needs a fresh conversion-goal observation.":"Selected customer and conversion-goal evidence are stored.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}function my(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function hy(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Tag Manager connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Tag Manager OAuth connection is stored for this project.",lastSnapshotAt:null};const a=t.selection;return t.status==="selection-required"||!a.accountId||!a.containerId?{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs an account and container selection.",lastSnapshotAt:t.connection.lastSnapshotAt}:{state:t.status,selection:my(a.containerId,a.accountId,a.workspaceId),...s,evidence:t.status==="stale"?"The selected container needs a fresh static configuration observation.":"Selected container configuration evidence is stored.",lastSnapshotAt:t.connection.lastSnapshotAt}}function xy(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:Ha(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Ha(t.triggerIds),variableIds:Ha(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Ha(t.productionHosts)}}}function wl(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function Wa(t,s,n){if(!s)return null;const a=s.totalAccessible===1?t:`${t}s`;return s.truncated?`Incomplete result: showing ${n} of ${s.totalAccessible} accessible ${a}. Use the CLI or API if the resource is not shown.`:`${s.totalAccessible} accessible ${a} found.`}function Ya(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Ja({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:ds,children:[s,e.jsx("select",{id:t,className:Ut,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function Gn({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function Sl({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),m=o.useRef(null),u=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{const y=x.current;x.current=a,a?u.current?.focus():y&&m.current?.querySelector("button")?.focus()},[a]);function f(){d(null),r(!0)}function p(){d(null),r(!1)}async function g(){i(!0),d(null);try{await n()}catch(y){d(Ct(y)),i(!1)}}return e.jsx("div",{ref:m,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(R,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:p,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{g()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:f,children:["Disconnect ",t]})})}function Cl({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:c,value:d,onChange:m}){const u=n.some(y=>y.id===d),[x,f]=o.useState(!1),p=x||d!==""&&!u&&n.length>0,g=e.jsx("label",{htmlFor:t,className:ds,children:s});return r?e.jsxs("div",{children:[g,e.jsx("select",{id:t,className:Ut,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[g,e.jsx("input",{id:t,required:!0,className:Ut,value:d,onChange:y=>m(y.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[g,e.jsx("input",{id:t,required:!0,className:Ut,value:d,onChange:y=>m(y.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":c})]}):e.jsxs("div",{children:[g,p?e.jsx("input",{id:t,required:!0,className:Ut,value:d,onChange:y=>m(y.target.value)}):e.jsxs("select",{id:t,required:!0,className:Ut,value:d,onChange:y=>m(y.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(y=>e.jsxs("option",{value:y.id,children:[y.name,y.detail?` (${y.detail})`:"",y.active?"":" — inactive"]},y.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{f(!p),m("")},children:p?"Choose from synced list":"Enter an ID manually"})]})}function py({projectId:t,projectName:s}){const n=Hs(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),[m,u]=o.useState(""),[x,f]=o.useState(null),[p,g]=o.useState(!1),[y,v]=o.useState(!1),[C,b]=o.useState(""),[L,k]=o.useState(""),[h,j]=o.useState(""),[w,P]=o.useState(""),[q,S]=o.useState(""),[V,F]=o.useState(!1),[D,K]=o.useState(jl),[H,se]=o.useState(null),Q=o.useRef(null),M=Le({...em({client:ne,path:{name:s}}),staleTime:Sn}),J=Le({...tm({client:ne,path:{name:s}}),staleTime:Sn}),E=Le({...sm({client:ne,path:{name:s}}),staleTime:Sn}),W=Le({...nm({client:ne,path:{name:s}}),staleTime:Sn}),T=W.data,ee=Le({...am({client:ne,path:{name:s},query:{limit:5}}),staleTime:Sn}),_=Le({...rm({client:ne,path:{name:s},query:{limit:5}}),staleTime:Sn}),ae=E.data??[],Re=(H?ae.find($=>$.id===H)??null:null)??(ae.length===1?ae[0]??null:null),X=ae.length>1&&!Re,ue=Le({...im({client:ne,path:{name:s,contractId:Re?.id??""}}),enabled:!!Re,staleTime:Sn}),ve=Le({...om({client:ne,path:{name:s}}),enabled:x==="google-ads"&&M.data?.connected===!0,staleTime:0}),Z=Le({...lm({client:ne,path:{name:s}}),enabled:x==="gtm"&&J.data?.connected===!0,staleTime:0}),he=Le({...cm({client:ne,path:{name:s,accountId:h}}),enabled:x==="gtm"&&!!h,staleTime:0}),G=Le({...dm({client:ne,path:{name:s,accountId:h,containerId:w}}),enabled:x==="gtm"&&!!h&&!!w,staleTime:0}),me=Gt(um({client:ne})),De=Gt(mm({client:ne})),ke=Gt(hm({client:ne})),oe=Gt(xm({client:ne})),pe=Gt(pm({client:ne})),we=Gt(gm({client:ne})),Ke=Gt(fm({client:ne})),Me=Gt(ym({client:ne})),O=Gt(vm({client:ne}));o.useEffect(()=>{if(x!=="google-ads"||p||!M.isSuccess)return;const $=M.data.connection?.selection;b($?.customerId??""),k($?.loginCustomerId??""),g(!0)},[p,M.data,M.isSuccess,x]),o.useEffect(()=>{if(x!=="gtm"||y||!J.isSuccess)return;const $=J.data.selection;j($?.accountId??""),P($?.containerId??""),S($?.workspaceId??""),v(!0)},[y,J.data,J.isSuccess,x]),o.useEffect(()=>{!H||!E.data||E.data.some($=>$.id===H)||se(null)},[E.data,H]);const U=o.useMemo(()=>{const $=ee.data?.snapshots??[],Se=_.data?.snapshots??[],lt=[...$.map(ft=>({id:ft.id,provider:"google-ads",kind:ft.kind,capturedAt:ft.capturedAt})),...Se.map(ft=>({id:ft.id,provider:"gtm",kind:ft.kind,capturedAt:ft.capturedAt}))].sort((ft,Ws)=>Ws.capturedAt.localeCompare(ft.capturedAt)).slice(0,5),Pt=[],qt=ue.data?.googleAdsSnapshot,Qe=ue.data?.gtmSnapshot;return qt&&Pt.push({id:qt.id,provider:"google-ads",kind:qt.kind,capturedAt:qt.capturedAt}),Qe&&Pt.push({id:Qe.id,provider:"gtm",kind:Qe.kind,capturedAt:Qe.capturedAt}),{contract:ue.data?.assessment.contract??Re,assessment:ue.data?.assessment??null,contractSelectionRequired:X,assessmentState:Re?ue.isError?"unavailable":ue.isLoading?"loading":void 0:void 0,assessmentError:ue.isError?Ct(ue.error):null,googleAds:uy(M.data,Nl(ee.data?.total??0,ee.isLoading,ee.isError,ee.error),M.isError),gtm:hy(J.data,Nl(_.data?.total??0,_.isLoading,_.isError,_.error),J.isError),snapshots:lt,assessmentEvidenceSnapshots:Pt}},[Re,X,ee.data,ee.error,ee.isError,ee.isLoading,M.data,M.isError,_.data,_.error,_.isError,_.isLoading,J.data,J.isError,ue.data,ue.error,ue.isError,ue.isLoading]),B=o.useSyncExternalStore(ac,cr,cr),Te=Object.values(B.runs).some($=>$.projectId===t&&($.kind===Qs["google-ads-sync"]||$.kind===Qs["gtm-sync"])),He=me.isPending||De.isPending||ke.isPending||oe.isPending||pe.isPending||we.isPending||Ke.isPending||Me.isPending||O.isPending||Te;async function Be(){await Promise.all([M.refetch(),J.refetch(),E.refetch(),ee.refetch(),_.refetch(),W.refetch(),Re?ue.refetch():Promise.resolve()])}async function Ze($){await Be();for(let Se=0;Se<10&&!$();Se+=1)await new Promise(lt=>setTimeout(lt,1500)),await Be()}function xe(){const $=document.activeElement;Q.current=$ instanceof HTMLElement?$:null}function jt($){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame($);return}globalThis.setTimeout($,0)}function _e(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function et($){if(!$)return;!$.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!$.hasAttribute("tabindex")&&($.tabIndex=-1),$.focus({preventScroll:!0})}function zt($,Se=$){const lt=document.getElementById($);lt instanceof HTMLDetailsElement&&(lt.open=!0);const Pt=lt?.scrollIntoView;typeof Pt=="function"&&Pt.call(lt,{behavior:_e()?"auto":"smooth",block:"start"}),et(document.getElementById(Se)??lt)}function rt($,Se){xe(),jt(()=>zt($,Se))}function tt(){const $=Q.current;Q.current=null,$&&jt(()=>{$.isConnected&&$.focus({preventScroll:!0})})}function pt(){r(null),d(!1),tt()}function Nt(){r(null),f(null),tt()}function _t(){r(null),F(!1),tt()}function Ve(){r(null),f(null),d(!0),rt("google-ads-connect-panel","google-ads-connect-title")}function A(){r(null),b(""),k(""),g(!1),f("google-ads"),d(!1),rt("google-ads-selection-panel","google-ads-selection-title")}function $e(){r(null),j(""),P(""),S(""),v(!1),f("gtm"),d(!1),rt("gtm-selection-panel","gtm-selection-title")}function Pe(){r(null),F(!0),rt("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function ze($,Se){nc({id:$.id,projectId:$.projectId,kind:$.kind,projectLabel:s,sourceAction:Se}),Ee({title:Se==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${$.id}`,dedupeMode:"replace"})}async function wt(){Ps(n),r(null);try{const $=await me.mutateAsync({path:{name:s},body:{provider:"google-ads",...m.trim()?{developerToken:m.trim()}:{}}});u(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),wl($.authorizationUrl,()=>{Be(),i(null),tt()})}catch($){r(Ct($))}}async function it(){Ps(n),r(null);try{const $=await De.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),wl($.authorizationUrl,()=>{Be(),i(null),tt()})}catch($){r(Ct($))}}async function Fe(){if(Ps(n),!C){r("Select a Google Ads customer before saving.");return}r(null);try{await ke.mutateAsync({path:{name:s},body:{customerId:C,...L.trim()?{loginCustomerId:L.trim()}:{}}}),f(null),tt(),await Ze(()=>M.data?.selectedCustomer!=null)}catch($){r(Ct($))}}async function te(){if(Ps(n),!h||!w){r("Select a Tag Manager account and container before saving.");return}r(null);try{await oe.mutateAsync({path:{name:s},body:{accountId:h,containerId:w,...q?{workspaceId:q}:{}}}),f(null),tt(),await Ze(()=>J.data?.status==="connected")}catch($){r(Ct($))}}async function Ue(){Ps(n),r(null),await Ke.mutateAsync({path:{name:s}}),f(null),d(!1),b(""),k(""),g(!1),i(null),await Be(),Ee({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),Q.current=null,jt(()=>et(document.getElementById("conversion-integrity-title")))}async function qe(){Ps(n),r(null),await Me.mutateAsync({path:{name:s}}),f(null),j(""),P(""),S(""),v(!1),i(null),await Be(),Ee({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),Q.current=null,jt(()=>et(document.getElementById("conversion-integrity-title")))}async function Ce(){Ps(n),r(null);try{const $=await pe.mutateAsync({path:{name:s}});ze($,"google-ads-sync")}catch($){r(Ct($))}}async function gt(){Ps(n),r(null);try{const $=await we.mutateAsync({path:{name:s}});ze($,"gtm-sync")}catch($){r(Ct($))}}async function Qt(){Ps(n),r(null);try{const $=await Promise.allSettled([pe.mutateAsync({path:{name:s}}),we.mutateAsync({path:{name:s}})]),[Se,lt]=$;Se.status==="fulfilled"&&ze(Se.value,"google-ads-sync"),lt.status==="fulfilled"&&ze(lt.value,"gtm-sync");const Pt=$.find(qt=>qt.status==="rejected");if(Pt?.status==="rejected")throw Pt.reason}catch($){r(Ct($))}}async function Kt(){Ps(n);const $=M.data?.connection?.selection.customerId,Se=J.data?.selection;if(!$||!Se?.accountId||!Se.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const lt=await O.mutateAsync({path:{name:s},body:xy(D,$,{accountId:Se.accountId,containerId:Se.containerId})});K(jl),F(!1),tt(),(await E.refetch()).data?.some(qt=>qt.id===lt.id)&&se(lt.id)}catch(lt){r(Ct(lt))}}function Zt($){switch($){case"connect-google-ads":Ve();return;case"connect-gtm":xe(),it();return;case"select-google-ads":A();return;case"select-gtm":$e();return;case"sync-google-ads":Ce();return;case"sync-gtm":gt();return;case"sync-static-evidence":Qt();return;case"declare-contract":Pe();return;case"review-findings":rt("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":rt("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Be();return;case"select-contract":rt("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ue.refetch();return;case"waiting-for-integrity":return}}const It=ve.data?.customers??[],vt=Z.data?.accounts??[],ps=he.data?.containers??[],dt=G.data?.workspaces??[],gs=!!C&&!It.some($=>$.customerId===C),Fs=!!h&&!vt.some($=>$.id===h),St=!!w&&!ps.some($=>$.id===w),Gs=!!q&&!dt.some($=>$.id===q),Lt=gs&&ve.isSuccess&&ve.data.truncated===!1,fs=Fs&&Z.isSuccess&&Z.data.truncated===!1,es=St&&he.isSuccess&&he.data.truncated===!1,ts=Gs&&G.isSuccess&&G.data.truncated===!1,xt=fs||es||ts,Ht=fs?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":es?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":ts?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,ss=Ya(Lt,ve.data,ve.isError),ns=Ya(fs,Z.data,Z.isError),$t=Ya(es,he.data,he.isError),ys=Ya(ts,G.data,G.isError),ot=ve.isError?Ct(ve.error):null,At=Z.isError?Ct(Z.error):he.isError?Ct(he.error):G.isError?Ct(G.error):null,vs=x==="google-ads"?ot:x==="gtm"?At:null,z=Wa("customer",ve.data,It.length),le=Wa("account",Z.data,vt.length),Ae=Wa("container",he.data,ps.length),ce=Wa("draft workspace",G.data,dt.length),ge=Z.isError||he.isError||G.isError&&!!q,Ge=c||x!==null||V;function mt(){ve.refetch()}function Rt(){if(Z.isError){Z.refetch();return}if(he.isError){he.refetch();return}G.isError&&G.refetch()}return M.isLoading||J.isLoading||E.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map($=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"skeleton-text-sm w-full"}),e.jsx("div",{className:"skeleton-text-sm w-3/4"})]},$))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):E.isError&&!E.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",Ct(E.error)]}),e.jsx(R,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{E.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(dy,{workspace:U,onPrimaryAction:Zt,actionPending:He,actionError:Ge?null:a,contracts:ae,selectedContractId:Re?.id??null,onSelectContract:$=>se($||null),contractError:E.isError?Ct(E.error):null,onRetryContracts:()=>{E.refetch()},onRetryEvidence:()=>{Promise.all([ee.refetch(),_.refetch()])},onChangeGoogleAdsSelection:A,onChangeGtmSelection:$e,onAddContract:()=>Zt("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Je(async $=>{$.preventDefault(),await wt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ds,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:m,onChange:$=>u($.target.value),className:Ut,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:me.isPending,children:me.isPending?"Starting…":"Continue to Google"}),e.jsx(R,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]})]})]}):null,x==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),vs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:vs}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:mt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Lt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(Ja,{id:"google-ads-customer",label:"Customer account",value:C,onChange:$=>{g(!0),b($);const Se=It.find(lt=>lt.customerId===$);k(Se?.parentCustomerId??"")},disabled:ve.isLoading,children:[e.jsx("option",{value:"",children:ve.isLoading?"Loading accessible customers…":"Select a customer"}),gs?e.jsxs("option",{value:C,disabled:Lt,children:["Saved customer ",C," (",ss,")"]}):null,It.map($=>e.jsx("option",{value:$.customerId,children:$.descriptiveName??`Customer ${$.customerId}`},$.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ds,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Ut,value:L,onChange:$=>{g(!0),k($.target.value)},placeholder:"Use only when a manager context is required"})]})]}),z?e.jsx("p",{role:"status",className:`mt-3 text-sm ${ve.data?.truncated?"text-caution":"text-secondary"}`,children:z}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:ke.isPending||ve.isLoading||ve.isError||Lt||!C,onClick:Je(Fe),children:ke.isPending?"Saving…":"Save customer selection"}),e.jsx(R,{type:"button",variant:"outline",onClick:Nt,children:"Cancel"})]}),M.data?.connected?e.jsx(Sl,{providerLabel:"Google Ads",disabled:He,onDisconnect:Ue}):null]}):null,x==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),vs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:vs}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:Rt,children:Z.isError?"Retry account list":he.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ht?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Ht}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Ja,{id:"gtm-account",label:"Account",value:h,onChange:$=>{v(!0),$!==h&&(P(""),S("")),j($)},disabled:Z.isLoading,children:[e.jsx("option",{value:"",children:Z.isLoading?"Loading accounts…":"Select an account"}),Fs?e.jsxs("option",{value:h,disabled:fs,children:["Saved account ",h," (",ns,")"]}):null,vt.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]}),e.jsxs(Ja,{id:"gtm-container",label:"Container",value:w,onChange:$=>{v(!0),$!==w&&S(""),P($)},disabled:!h||he.isLoading,children:[e.jsx("option",{value:"",children:he.isLoading?"Loading containers…":"Select a container"}),St?e.jsxs("option",{value:w,disabled:es,children:["Saved container ",w," (",$t,")"]}):null,ps.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]}),e.jsxs(Ja,{id:"gtm-workspace",label:"Draft workspace (optional)",value:q,onChange:$=>{v(!0),S($)},disabled:!w||G.isLoading,children:[e.jsx("option",{value:"",children:G.isLoading?"Loading workspaces…":"No draft workspace"}),Gs?e.jsxs("option",{value:q,disabled:ts,children:["Saved draft workspace ",q," (",ys,")"]}):null,dt.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[le?e.jsx("p",{role:"status",className:Z.data?.truncated?"text-caution":"text-secondary",children:le}):null,Ae?e.jsx("p",{role:"status",className:he.data?.truncated?"text-caution":"text-secondary",children:Ae}):null,ce?e.jsx("p",{role:"status",className:G.data?.truncated?"text-caution":"text-secondary",children:ce}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:oe.isPending||Z.isLoading||he.isLoading||G.isLoading&&!!q||ge||xt||!h||!w,onClick:Je(te),children:oe.isPending?"Saving…":"Save container selection"}),e.jsx(R,{type:"button",variant:"outline",onClick:Nt,children:"Cancel"})]}),J.data?.connected?e.jsx(Sl,{providerLabel:"Tag Manager",disabled:He,onDisconnect:qe}):null]}):null,V?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Je(async $=>{$.preventDefault(),await Kt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ds,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Ut,value:D.name,onChange:$=>K(Se=>({...Se,name:$.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ds,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Ut,value:D.eventName,onChange:$=>K(Se=>({...Se,eventName:$.target.value})),placeholder:"booking_complete"})]}),e.jsx(Cl,{id:"contract-conversion-action",label:"Google Ads conversion action",options:T?.googleAds.conversionActions??[],synced:T?.googleAds.syncedAt!=null,loading:W.isLoading,failed:W.isError,onRetry:()=>{W.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:D.conversionActionId,onChange:$=>K(Se=>({...Se,conversionActionId:$}))}),e.jsx(Cl,{id:"contract-gtm-tag",label:"Tag Manager tag",options:T?.gtm.tags??[],synced:T?.gtm.syncedAt!=null,loading:W.isLoading,failed:W.isError,onRetry:()=>{W.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:D.tagId,onChange:$=>K(Se=>({...Se,tagId:$}))})]}),e.jsxs("details",{className:"inline-disclosure mt-5 max-w-3xl",children:[e.jsx("summary",{children:"Additional matching rules"}),e.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-conversion-id",className:ds,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Ut,value:D.conversionId,onChange:$=>K(Se=>({...Se,conversionId:$.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ds,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Ut,value:D.conversionLabel,onChange:$=>K(Se=>({...Se,conversionLabel:$.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ds,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Ut,value:D.triggerIds,onChange:$=>K(Se=>({...Se,triggerIds:$.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ds,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Ut,value:D.variableIds,onChange:$=>K(Se=>({...Se,variableIds:$.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ds,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Ut,value:D.campaignIds,onChange:$=>K(Se=>({...Se,campaignIds:$.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ds,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Ut,value:D.productionHosts,onChange:$=>K(Se=>({...Se,productionHosts:$.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(Gn,{id:"contract-primary-action",checked:D.requirePrimaryAction,onChange:$=>K(Se=>({...Se,requirePrimaryAction:$})),children:"Google Ads action is primary"}),e.jsx(Gn,{id:"contract-biddable-goal",checked:D.requireBiddableGoal,onChange:$=>K(Se=>({...Se,requireBiddableGoal:$})),children:"Google Ads goal is biddable"}),e.jsx(Gn,{id:"contract-runtime-verification",checked:D.verificationRequired,onChange:$=>K(Se=>({...Se,verificationRequired:$})),children:"Runtime proof is required"}),e.jsx(Gn,{id:"contract-transaction-id",checked:D.requireTransactionId,onChange:$=>K(Se=>({...Se,requireTransactionId:$})),children:"Transaction ID is required"}),e.jsx(Gn,{id:"contract-value",checked:D.requireValue,onChange:$=>K(Se=>({...Se,requireValue:$})),children:"Conversion value is required"}),e.jsx(Gn,{id:"contract-currency",checked:D.requireCurrency,onChange:$=>K(Se=>({...Se,requireCurrency:$})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:O.isPending,children:O.isPending?"Saving…":"Save conversion contract"}),e.jsx(R,{type:"button",variant:"outline",onClick:_t,children:"Cancel"})]})]})]}):null]})}const gy=6e4,fy=["7d","14d","30d"],Wi="not available",yy='Figures come from the stored Google Ads snapshot; this view never calls Google. The window ends on the newest CLOSED day, because the capture day is only partly recorded and would read as a drop. A calendar day the provider returned no row for is zero delivery, so it is charted as zero. Rates with a zero denominator read "not available", never 0%.',vy="No Google Ads snapshot stored yet",by="Connect a Google Ads account in Conversion Integrity below, choose the customer, then run a Google Ads sync. Spend, clicks, impressions, and conversions appear here once the first snapshot is stored.",jy="No closed days yet",Ny="The stored snapshot covers no completed day yet. Figures appear after a full day closes in the account time zone; the day a snapshot is captured is partial and is left out on purpose. If this persists, check the latest Google Ads sync in Activity.",wy={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},en=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Hr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Sy=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function _n(t,s){return t===null||!Number.isFinite(t)?Wi:s===null?Sy.format(t/1e6):hx(t,s)}function Wr(t){return t===null||!Number.isFinite(t)?Wi:Xe(t)}function Cy(t,s){return t===null||!Number.isFinite(t)?`${Wi} vs prior ${s}d`:t===0?`no change vs prior ${s}d`:`${t>0?"↑":"↓"} ${Xe(Math.abs(t))} vs prior ${s}d`}function ky(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Ay(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Ry(t,s){return s==="none"||t===null||!Number.isFinite(t)||t===0?"text-muted":(s==="up-good"?t>0:t<0)?"text-positive":"text-negative"}function Py({projectName:t}){const[s,n]=o.useState("14d"),[a,r]=o.useState(()=>new Set(["costMicros","conversions"])),l=Le({...bm({client:ne,path:{name:t},query:{window:s}}),staleTime:gy}),i=l.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Oe,{text:yy})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Tt(i.startDate)," to ",Tt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(La,{windows:fy,value:s,onChange:n,label:"Google Ads time period"})]});if(l.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(h=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},h))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(l.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",Ct(l.error)]}),e.jsx(R,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:d,daily:m,campaigns:u,comparison:x,comparisonUnavailableReason:f,source:p}=i;if(!p){const h=f==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:h?jy:vy}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:h?Ny:by})]})]})}const g=p.currencyCode,y=p.campaignsInInventory>0&&p.campaignsQueried<p.campaignsInInventory?{queried:p.campaignsQueried,inInventory:p.campaignsInInventory}:null,v=d.costMicros>0&&d.conversions===0,C=[{key:"spend",comparable:!0,label:"Spend",value:_n(d.costMicros,g),change:x?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Hr.format(d.conversions),change:x?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:v?"no conversions":_n(d.costPerConversionMicros,g),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Wr(d.conversionRate),change:x?.change.conversionRate??null,direction:"up-good",seriesKey:null}],b=[{key:"clicks",label:"Clicks",value:en.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:en.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Wr(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:_n(d.cpcMicros,g),seriesKey:null}],L={costMicros:{label:"Spend",color:ct[1],axisId:"spend",formatValue:h=>_n(h,g)},conversions:{label:"Conversions",color:ct[0],axisId:"conversions",formatValue:h=>Hr.format(h)},clicks:{label:"Clicks",color:ct[2],axisId:"clicks",formatValue:h=>en.format(h)},impressions:{label:"Impressions",color:ct[3],axisId:"impressions",formatValue:h=>en.format(h)}},k=[...a].map(h=>({dataKey:h,...L[h]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,y!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",en.format(y.queried)," of"," ",en.format(y.inInventory)," campaigns, so they are a subset of the account."]}):null,p.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!x&&f==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:wy["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:C.map(h=>{const j=h.seriesKey!==null&&a.has(h.seriesKey),w=j&&a.size===1,P=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[h.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?L[h.seriesKey].color:"var(--color-mono-600)"}}):null,h.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:h.value}),x&&h.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Ry(h.change,h.direction)}`,children:Cy(h.change,x.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:h.comparable?`no prior ${s} period stored`:" "})]});return h.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:P},h.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:w,onClick:()=>r(q=>{const S=new Set(q);return S.has(h.seriesKey)?S.delete(h.seriesKey):S.add(h.seriesKey),S.size===0?q:S}),className:`rounded-md border px-3 py-2 text-left transition-colors ${j?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${w?"cursor-default":""}`,children:P},h.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:b.map(h=>{const j=h.seriesKey!==null&&a.has(h.seriesKey),w=j&&a.size===1,P=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[h.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?L[h.seriesKey].color:"var(--color-mono-600)"}}):null,h.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:h.value})]});return h.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:P},h.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:w,onClick:()=>r(q=>{const S=new Set(q);return S.has(h.seriesKey)?S.delete(h.seriesKey):S.add(h.seriesKey),S.size===0?q:S}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${w?"cursor-default":"hover:bg-surface-hover"}`,children:P},h.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Nc,{data:m,xKey:"date",series:k,xTickFormatter:Pn,labelFormatter:Tt}),e.jsx("ul",{className:"sr-only",children:m.map(h=>e.jsxs("li",{children:[Tt(h.date),":"," ",k.map(j=>`${j.label} ${L[j.dataKey].formatValue(h[j.dataKey])}`).join(", "),h.origin==="filled"?", no delivery reported":""]},h.date))})]}),e.jsxs("div",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):u.map(h=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:h.name??h.campaignId,children:h.name??e.jsx("span",{className:"font-mono text-secondary",children:h.campaignId})}),e.jsx("td",{children:e.jsx(fe,{tone:ky(h.status),children:Ay(h.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:en.format(h.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:en.format(h.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:_n(h.totals.costMicros,g)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Hr.format(h.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Wr(h.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:h.totals.costMicros>0&&h.totals.conversions===0?e.jsx(fe,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:_n(h.totals.costPerConversionMicros,g)})})]},h.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Aa(Ot(p.capturedAt))," · ","customer ",p.customerId," · ","latest closed day ",Tt(p.asOfDate),p.openDate?e.jsxs(e.Fragment,{children:[" · ",Tt(p.openDate)," still open, excluded"]}):null,p.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",p.timeZone]}):null]})]})]})}const Yr=20,Us=50,Iy=50,Ty=50;function Yi(t){return t==="viewer"}function Ji(t){return t?.status==="unavailable"}function od(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function ld(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function Xa(t,s,n){if(t.kind==="none")return[];if(t.kind==="all")return s.map(l=>l.id);if(t.kind==="specific")return s.filter(l=>t.propertyIds.includes(l.id)).map(l=>l.id);const a=new Set(t.groupIds),r=new Set(n.filter(l=>a.has(l.id)).flatMap(l=>l.propertyIds));return s.filter(l=>r.has(l.id)).map(l=>l.id)}function Ly(t,s,n){if(t.kind==="all")return`every location (${n})`;if(t.kind==="specific")return n===1?"1 location":`${n} locations`;const a=t.groupIds.map(r=>s.find(l=>l.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function Jr(t,s){const n=new Set(s.map(r=>r.id)),a=t.propertyIds.filter(r=>n.has(r)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function kl(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Al(t){return t==="matched"?"Matched":t==="duplicate"?"Duplicate":t==="ambiguous"?"Ambiguous":t==="proposed"?"Property needs review":t==="excluded"?"Property excluded":t==="invalid"?"Invalid row":"Not matched"}function Za(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function Si(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Xr(t){return Si(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Ci({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=o.useState(""),[c,d]=o.useState(!1),m=l.trim().toLocaleLowerCase(),u=m?t.filter(g=>g.label.toLocaleLowerCase().includes(m)):t,x=c?u:u.slice(0,Iy),f=x.length<u.length;function p(){const g=new Set([...s,...x.map(y=>y.id)]);n(t.filter(y=>g.has(y.id)).map(y=>y.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:l,onChange:g=>i(g.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:x.length===0,onClick:p,children:"Select all shown"}),e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),u.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",x.length," of ",u.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:x.map(g=>{const y=s.includes(g.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${g.label}`,checked:y,type:"checkbox",onChange:v=>n(od(s,g.id,v.currentTarget.checked))}),e.jsx("span",{children:g.label})]}),g.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[g.urlCount," URLs"]})]},g.id)})}),f?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function Xi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(fe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Zi({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function $y({value:t}){const[s,n]=o.useState(0),[a,r]=o.useState(0),[l,i]=o.useState(null),c=t.preview,d=c?.counts.needsAttention??0,m=c?.rows.filter(w=>w.status==="matched")??[],u=c?.rows??[],x=u.filter(w=>w.status!=="matched"),f=Math.max(1,Math.ceil(u.length/Us)),p=Math.min(s,f-1),g=u.slice(p*Us,(p+1)*Us),y=Math.max(1,Math.ceil(x.length/Us)),v=Math.min(a,y-1),C=x.slice(v*Us,(v+1)*Us),b=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,L=m.length>0&&!t.isApplying,k=c!==null&&l===c.previewChecksum,h=x.length>0&&v===y-1;o.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function j(w){if(w)try{t.onCsvChange(await w.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:w=>{j(w.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:w=>t.onCsvChange(w.currentTarget.value),placeholder:`property,group,url
3
- Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!b,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:w.label}),e.jsx("td",{className:"text-secondary",children:w.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:w.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[w.addedTargetKeys.length,w.unchangedTargetKeys.length>0?` · ${w.unchangedTargetKeys.length} already members`:""]})]},w.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:g.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:w.dataRow}),e.jsx("td",{className:"text-heading",children:w.property}),e.jsx("td",{className:"text-secondary",children:w.group}),e.jsxs("td",{children:[e.jsx(fe,{tone:kl(w.status),children:Al(w.status)}),Za(w)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Za(w)}):null]})]},w.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",p+1," of ",f," · ",c.rows.length," rows"]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>n(w=>Math.max(0,w-1)),children:"Previous 50 rows"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===f-1,onClick:()=>n(w=>Math.min(f-1,w+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:C.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:w.dataRow}),e.jsx("td",{className:"text-heading",children:w.property}),e.jsx("td",{className:"text-secondary",children:w.group}),e.jsxs("td",{children:[e.jsx(fe,{tone:kl(w.status),children:Al(w.status)}),Za(w)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Za(w)}):null]})]},w.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",v+1," of ",y]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:v===0,onClick:()=>r(w=>Math.max(0,w-1)),children:"Previous 50 exceptions"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:v===y-1,onClick:()=>r(w=>Math.min(y-1,w+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:k,disabled:t.isApplying||!h,onChange:w=>i(w.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!L||!k,onClick:()=>{t.onApply(m.map(w=>w.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${m.length} matched row${m.length===1?"":"s"}`})]}):e.jsx(R,{type:"button",className:"mt-3 min-h-11",disabled:!L,onClick:()=>{t.onApply(m.map(w=>w.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${m.length} membership${m.length===1?"":"s"}`})]}):null]})}const qy="—";function My({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:l=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:m,onClearQueryAssignments:u,onRemoveQuery:x,onCreateQueries:f,onCreateAndPairQuestions:p,isCreatingQueries:g=!1,createQueriesError:y=null,onManageProjectQueries:v,groups:C,audience:b,onAudienceChange:L,assignmentImpact:k=null,isPreviewingAssignmentImpact:h=!1,assignmentImpactError:j=null,onRetryAssignmentImpact:w,assignmentNotice:P=null,onReplaceAssignments:q,isReplacingAssignments:S=!1,onBack:V,onContinue:F}){const[D,K]=o.useState(""),[H,se]=o.useState(!1),[Q,M]=o.useState(!1),[J,E]=o.useState(""),[W,T]=o.useState(""),[ee,_]=o.useState(null);if(Ji(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Zi,{message:s.message})});const ae=Yi(t),ie=b,Re=L,X=Xa(ie,n,C),ue=X.length,ve=ue>0&&r.length>0&&!l&&!i&&!h&&k!==null&&j===null,Z=u??x,he=D.trim().toLocaleLowerCase(),G=he?a.filter(B=>Xr(B).toLocaleLowerCase().includes(he)):a,me=G.filter(B=>(B.propertyIds?.length??0)===0),De=Q?me:G,ke=H?De:De.slice(0,Ty),oe=ke.filter(B=>!Si(B)),pe=[...new Set(J.split(`
4
- `).map(B=>B.trim()).filter(Boolean))],we=[...W.matchAll(/\{([a-z][\w-]*)\}/gi)].map(B=>B[1]),Ke=n.filter(B=>X.includes(B.id)),Me=we.length===0||W.trim()===""?[]:Ke.map(B=>({propertyId:B.id,text:we.reduce((Te,He)=>Te.replaceAll(`{${He}}`,B.label),W.trim())})),O=[...new Set(Me.map(B=>B.text))];function U(){const B=new Set([...r,...oe.map(Te=>Te.id)]);d(a.filter(Te=>B.has(Te.id)).map(Te=>Te.id))}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose queries, then apply them to locations."})]})}),ae?e.jsx(Xi,{}):null,ae?null:e.jsxs("fieldset",{className:"border-y border-default py-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Apply to"}),e.jsx("div",{className:"mt-3 max-w-xl",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"sr-only",children:"Apply to"}),e.jsxs("select",{"aria-label":"Apply to",value:ie.kind==="none"?"":ie.kind==="all"?"all":ie.kind==="specific"?"specific":`group:${ie.groupIds[0]??""}`,onChange:B=>{const Te=B.currentTarget.value;Te==="all"?Re({kind:"all"}):Te==="specific"?Re({kind:"specific",propertyIds:[]}):Te.startsWith("group:")&&Re({kind:"groups",groupIds:[Te.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",disabled:!0,children:"Choose where to apply"}),e.jsxs("option",{value:"all",children:["Every location (",n.length,")"]}),C.length>0?e.jsx("optgroup",{label:"Groups",children:C.map(B=>{const Te=Xa({kind:"groups",groupIds:[B.id]},n,C).length;return e.jsx("option",{value:`group:${B.id}`,disabled:Te===0,children:Jr(B,n)},B.id)})}):null,e.jsx("option",{value:"specific",children:"Specific locations…"})]})]})}),ie.kind==="groups"?e.jsxs("div",{className:"mt-3 max-w-2xl space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:ie.groupIds.map(B=>{const Te=C.find(He=>He.id===B);return Te?e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-sm text-primary",children:[Jr(Te,n),e.jsx("button",{type:"button","aria-label":`Remove ${Te.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const He=ie.groupIds.filter(Be=>Be!==Te.id);Re(He.length>0?{kind:"groups",groupIds:He}:{kind:"none"})},children:"×"})]},Te.id):null})}),C.some(B=>!ie.groupIds.includes(B.id)&&Xa({kind:"groups",groupIds:[B.id]},n,C).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:B=>{B.currentTarget.value&&Re({kind:"groups",groupIds:[...ie.groupIds,B.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),C.filter(B=>!ie.groupIds.includes(B.id)).map(B=>{const Te=Xa({kind:"groups",groupIds:[B.id]},n,C).length;return e.jsx("option",{value:B.id,disabled:Te===0,children:Jr(B,n)},B.id)})]})]}):null,ue===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,ie.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(Ci,{legend:"Specific locations",properties:n,selectedPropertyIds:ie.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:B=>{Re({kind:"specific",propertyIds:B})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),ae||!f?null:e.jsxs("details",{open:a.length===0,className:"border-y border-default py-4",children:[e.jsx("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:"Add queries"}),e.jsxs("div",{className:"pt-3",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:a.length===0?"Add the queries you want to track":"Add more queries"}),e.jsx("p",{className:"mt-1 mb-2 text-sm text-secondary",children:"One per line. Add them to the project, then apply them to Properties."}),e.jsx("textarea",{"aria-label":"New queries, one per line",className:"w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:4,value:J,onChange:B=>E(B.currentTarget.value),placeholder:`best apartments in dallas
5
- luxury apartments atlanta
6
- pet friendly apartments austin`}),y?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:y}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:pe.length===0||g||i,onClick:()=>{Promise.resolve(f(pe)).then(()=>E(""),()=>{})},children:g?"Adding…":`Add ${pe.length||""} ${pe.length===1?"query":"queries"}`.replace(" "," ")}),v?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:v,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:W,onChange:B=>T(B.target.value),placeholder:"apartments near {property}"}),W.trim()===""?null:we.length===0?e.jsxs("p",{className:"mt-2 text-sm text-caution",children:["Add ","{property}"," to the pattern, or use the box above for a single query."]}):Ke.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write queries for."}):e.jsxs("div",{className:"mt-2 rounded-md border border-base bg-bg-elevated p-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:[O.length," ",O.length===1?"query":"queries",", one per selected Property:"]}),e.jsx("ul",{className:"mt-1 mb-0 list-none space-y-0.5 p-0",children:O.slice(0,3).map(B=>e.jsx("li",{className:"text-sm text-strong",children:B},B))}),O.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",O.length-3," more"]}):null]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Me.length===0||g||i||!p,onClick:()=>{p&&Promise.resolve(p(Me)).then(()=>T(""),()=>{})},children:g?"Adding…":`Add ${Me.length||""} ${Me.length===1?"query":"queries"}`.replace(" "," ")}),Me.length>0?e.jsxs("p",{className:"mt-2 mb-0 text-sm text-secondary",children:["Each query is measured on the one Property it names, so this adds"," ",Me.length," assignment",Me.length===1?"":"s","."]}):null]})]})]}),ae?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:oe.length===0,onClick:U,children:"Select all shown queries"}),e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(R,{type:"button",size:"sm",className:"min-h-11",disabled:!ve,onClick:()=>{m({queryIds:r,propertyIds:X,...ie.kind==="groups"?{groupIds:ie.groupIds}:{}})},children:l?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"}${ie.kind==="none"?"":` to ${Ly(ie,C,ue)}`}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[h?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,k?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",k.assignmentCount," Property assignment",k.assignmentCount===1?"":"s"," · ",k.addedAssignments," new, ",k.alreadyPresentAssignments," already assigned"," · ",k.fullRunProviderCalls," provider request",k.fullRunProviderCalls===1?"":"s"," per full run"," · ",k.addedProviderCalls," new",ie.kind==="groups"?` · ${k.resolvedPropertyCount} unique ${k.resolvedPropertyCount===1?"Property":"Properties"}${k.overlapCount>0?`, ${k.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):j?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:j}),w?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:w,children:"Retry impact"}):null,V?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:V,children:"Back to Groups"}):null]}):ie.kind==="none"?e.jsx("p",{className:"text-sm text-secondary",children:"Choose where to apply first."}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ue," Properties = ",r.length*ue," assignments"]})]}),P?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:P}):null]})}),a.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search queries"}),e.jsx("input",{type:"search",value:D,onChange:B=>{K(B.currentTarget.value),se(!1)},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",ke.length," of ",De.length," queries,"," ",G.length-me.length," of ",G.length," applied"]}),ae||me.length===0?null:e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{M(B=>!B),se(!1)},children:Q?"Show all queries":`Show the ${me.length} not applied`})]})]}):null,ke.length>0?e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[ae?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),ae?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:ke.map(B=>{const Te=Si(B),He=Xr(B),Be=r.includes(B.id),Ze=(B.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[ae?null:Te?e.jsx("td",{"aria-hidden":"true"}):e.jsx("td",{className:"p-0",children:e.jsx("label",{className:"flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{"aria-label":`Select query ${He}`,checked:Be,type:"checkbox",onChange:xe=>d(od(r,B.id,xe.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:He})}),e.jsx("td",{className:"text-secondary",children:ld(B.propertyIds??[],n)}),ae?null:e.jsx("td",{className:"text-right",children:Ze?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[q?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||S,onClick:()=>_({queryId:B.id,propertyIds:[...B.propertyIds??[]]}),"aria-label":`Replace query assignments for ${He}`,children:"Replace assignments"}):null,e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{Z(B.id)},"aria-label":`Clear query assignments for ${He}`,children:"Clear assignments"})]}):null})]},B.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,ae||!ee?null:(()=>{const B=a.find(Be=>Be.id===ee.queryId),Te=B?Xr(B):"this query",He=ee.propertyIds.filter(Be=>n.some(Ze=>Ze.id===Be));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",Te,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(Ci,{legend:"Properties for this query",properties:n,selectedPropertyIds:He,onSelectedPropertyIdsChange:Be=>_(Ze=>Ze&&{...Ze,propertyIds:[...Be]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:S||i,onClick:()=>_(null),children:"Keep current assignments"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:He.length===0||S||i||!q,onClick:()=>{q&&Promise.resolve(q({queryId:ee.queryId,propertyIds:He}))},children:S?"Replacing assignments…":`Replace with ${He.length} ${He.length===1?"Property":"Properties"}`})]})]})})(),ke.length<De.length?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>se(!0),children:"Show all queries"}):null,ae?null:e.jsxs(e.Fragment,{children:[c?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${V?"justify-between":"justify-end"}`,children:[V?e.jsx(R,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:V,children:"Back"}):null,e.jsx(R,{type:"button",variant:ve?"outline":"default",className:"min-h-11",disabled:!c||i,onClick:F,children:"Continue"})]})]})]})}function Ey({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:l=!1,onGroupDraftChange:i,onSaveGroup:c,onEditGroup:d,onRemoveGroup:m,onClearGroupDraft:u,membershipImport:x,onBack:f,onContinue:p}){if(Ji(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Zi,{message:s.message})});const g=Yi(t),y=r.name.trim().length>0&&r.propertyIds.length>0&&!l,v=n.filter(k=>r.propertyIds.includes(k.id)).length,C=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,b=!g&&(d!==void 0||m!==void 0);function L(){if(u){u();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),g?e.jsx(Xi,{}):null,g||!x?null:e.jsx($y,{value:x}),g?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:k=>i({...r,name:k.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[v," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(Ci,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:k=>i({...r,propertyIds:k})})})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Competitor domains"}),e.jsx("input",{"aria-label":"Competitor domains",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.competitorDomains,onChange:k=>i({...r,competitorDomains:k.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!y,onClick:()=>{c(r)},children:l?"Saving group…":"Save group"}),e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!C,onClick:L,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),C?e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Save this group or clear the form before continuing."}):null]}),e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Competitors"}),b?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:k.name}),e.jsx("td",{className:"text-secondary",children:ld(k.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:k.competitors.length>0?k.competitors.join(", "):"None"}),b?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${k.name}`,onClick:()=>d(k),children:"Edit"}):null,m?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${k.name}`,onClick:()=>{m(k.id)},children:"Remove"}):null]})}):null]},k.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,g?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${f?"justify-between":"justify-end"}`,children:[f?e.jsx(R,{type:"button",variant:"outline",className:"min-h-11",onClick:f,children:"Back"}):null,e.jsx(R,{type:"button",className:"min-h-11",disabled:C,onClick:p,children:a.length===0&&!C?"Continue without groups":"Continue"})]})]})}function Dy({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:l,onReviewChanges:i,isReviewing:c=!1,canReviewChanges:d=!0,reviewedChanges:m,reviewChangesError:u,canPublish:x,isPublishing:f=!1,onPublish:p}){const[g,y]=o.useState(Yr),[v,C]=o.useState(Yr),[b,L]=o.useState(Yr);if(Ji(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Zi,{message:s.message})});const k=Yi(t),h=r?.items??[],j=r?.coverageItems??[],w=h.slice(0,g),P=j.slice(0,v),q=a.slice(0,b),S=i!==void 0,V=m!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),k?e.jsx(Xi,{}):null,r?e.jsx("section",{"aria-labelledby":"advanced-measurement-sitemap-review-title",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{id:"advanced-measurement-sitemap-review-title",className:"text-sm font-medium text-heading",children:"Sitemap changes need review"}),r.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.exceptionCount," sitemap ",r.exceptionCount===1?"entry needs":"entries need"," review."]}):null,r.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.coverageReviewCount," ",r.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),r.exceptionCount>0?e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["URLs not added to Properties (",r.exceptionCount,")"]}),h.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:w.map(F=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:F.url}),e.jsx("p",{className:"mt-1 text-secondary",children:F.reason})]},`${F.url}-${F.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",w.length," of ",h.length]}),w.length<h.length?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>y(F=>F+Us),children:"Show next 50 URLs"}):null]})]}):null,k?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[r.coverageReviewCount>0?e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"For changed Property URLs"}),e.jsxs("p",{className:"text-sm text-secondary",children:["This choice applies to all ",r.coverageReviewCount," changed ",r.coverageReviewCount===1?"Property":"Properties","."]}),e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review Property URL changes (",r.coverageReviewCount,")"]}),P.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[P.map(F=>e.jsxs("section",{"aria-label":`${F.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:F.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:F.savedUrls.map(D=>e.jsx("li",{className:"break-all text-secondary",children:D},D))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),F.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:F.currentSitemapUrls.map(D=>e.jsx("li",{className:"break-all text-secondary",children:D},D))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},F.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",P.length," of ",j.length]}),P.length<j.length?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>C(F=>F+Us),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(R,{type:"button",className:"min-h-11",onClick:()=>{r.onResolve()},children:"Confirm sitemap changes"})]})]})}):null,e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Groups"}),e.jsx("th",{children:"Assignments"}),e.jsx("th",{children:"Provider requests / run"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-heading",children:n.properties}),e.jsx("td",{className:"tabular-nums text-heading",children:n.queries}),e.jsx("td",{className:"tabular-nums text-heading",children:n.groups}),e.jsx("td",{className:"tabular-nums text-heading",children:n.assignments??"—"}),e.jsx("td",{className:"tabular-nums text-heading",children:n.providerCalls??qy})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,m?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:m.title}),m.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:m.items.map((F,D)=>e.jsx("li",{children:F},`${F}-${D}`))}):null]}):null,e.jsxs("section",{"aria-labelledby":"advanced-measurement-flagged-exceptions-title",className:"space-y-3",children:[e.jsx("h4",{id:"advanced-measurement-flagged-exceptions-title",className:"text-sm font-medium text-heading",children:"Flagged exceptions"}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No flagged exceptions."}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"divide-y divide-default border-y border-default",children:q.map(F=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:F.title}),F.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:F.detail}):null]}),e.jsx(fe,{tone:F.tone??"caution",children:"Needs attention"})]},F.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",q.length," of ",a.length]}),q.length<a.length?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>L(F=>F+Us),children:"Show next 50 exceptions"}):null]})]})]}),k?null:e.jsxs(e.Fragment,{children:[S&&u?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:u}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${l?"justify-between":"justify-end"}`,children:[l?e.jsx(R,{type:"button",variant:"outline",className:"min-h-11",onClick:l,children:"Back"}):null,i!==void 0&&!V?e.jsx(R,{type:"button",className:"min-h-11",disabled:c||!d,onClick:()=>{i()},children:c?"Reviewing changes…":"Review changes"}):e.jsx(R,{type:"button",className:"min-h-11",disabled:!x||f,onClick:()=>{p()},children:f?"Publishing setup…":"Publish setup"})]})]})]})}const Oy={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Fy(t){return t.trim().toLocaleLowerCase()}function Gy(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function _y({property:t}){const s=t.urls??[t.url];return s.length<=1?e.jsx("span",{children:s[0]??"No URL"}):e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-xs font-medium text-primary",children:[s.length," URLs"]}),e.jsx("ul",{className:"mt-2 space-y-1",children:s.map(n=>e.jsx("li",{className:"break-all font-mono text-xs text-secondary",children:n},n))})]})}function Ky({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const l=!t||r==="reviewing",i=l||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function c(d,m){n({...s,[d]:m})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(fe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:l,onChange:d=>c("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:l,onChange:d=>c("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:l,onChange:d=>c("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:l,onChange:d=>c("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:l,onChange:d=>c("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:l,onChange:d=>c("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:l,onChange:d=>c("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(R,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Uy({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:l,onSelectedPropertyIdsChange:i,onContinue:c,isContinuing:d=!1,onRetryProperties:m,onReturnToImport:u,maxVisibleProperties:x,onShowAllProperties:f}){const p=Fy(a),g=s.filter(q=>Gy(q,p)),y=Math.max(1,x??g.length),v=g.slice(0,y),C=new Set(l),b=s.filter(q=>C.has(q.id)).map(q=>q.id),L=v.length<g.length;function k(q){const S=new Set(q);i(s.filter(V=>S.has(V.id)).map(V=>V.id))}function h(q,S){if(!t||d)return;const V=new Set(b);S?V.add(q):V.delete(q),k(V)}function j(){!t||d||k([...b,...v.map(q=>q.id)])}function w(){!t||d||i([])}function P(){!t||d||b.length===0||c(b)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||d,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:m,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:m,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:d,onChange:q=>r(q.target.value),className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:j,children:"Select all shown"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",disabled:d||b.length===0,onClick:w,children:"Clear selection"})]}):null]}),g.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",v.length," of ",g.length," Properties"]}),e.jsxs("p",{children:[b.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:v.map(q=>{const S=Oy[q.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:q.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(_y,{property:q})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(fe,{tone:S.tone,children:S.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${q.name}`,checked:b.includes(q.id),disabled:d,onChange:V=>h(q.id,V.target.checked),className:"size-6 accent-accent"})})}):null]},q.id)})})]})}),L&&f?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:f,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(R,{type:"button",variant:"ghost",disabled:d,onClick:u,children:"Back"}),e.jsx(R,{type:"button",disabled:d||b.length===0,onClick:P,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function By(t){return t.activeStep==="import"?e.jsx(Ky,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Uy,{...t})}const Vy=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function zy({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:l}){const i=o.useRef(null),c=o.useRef(null),d=o.useRef(null),m=o.useRef(null),u=o.useRef(!1),[x,f]=o.useState(!1);return o.useEffect(()=>{s||f(!1)},[s]),o.useEffect(()=>{const p=u.current;u.current=x,x?d.current?.focus():p&&m.current?.focus()},[x]),o.useEffect(()=>{const p=i.current;if(i.current=t,p===null||p===t)return;const g=c.current?.querySelector('h1, h2, h3, [role="heading"]');g&&(g.tabIndex=-1,g.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(fe,{tone:"caution",children:"Unpublished changes"}),n&&a?x?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(R,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>f(!1),children:"Keep editing"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(R,{ref:m,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>f(!0),children:"Discard changes"}):null]}):null]}),e.jsx("div",{role:"group","aria-label":"Advanced measurement setup progress",className:"overflow-x-auto border-b border-default",children:e.jsx("ol",{className:"flex min-w-max gap-6",children:Vy.map(p=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===p.id?"step":void 0,onClick:()=>r(p.id),className:`block min-h-11 border-b-2 bg-transparent px-1 py-3 text-left text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${t===p.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:p.label}):e.jsx("span",{"aria-current":t===p.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===p.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:p.label})},p.id))})}),e.jsx("div",{ref:c,children:l})]})}function Qy(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(By,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(My,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Ey,{...t.groups,access:s}):"review"in t?e.jsx(Dy,{...t.review,access:s}):null}function er(t){return e.jsx(zy,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Qy(t)})}const Rl={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},la={name:"",propertyIds:[],competitorDomains:""},Pl=50;function ma(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Hy(t){const s=t.trim();if(!s)throw new Error("Add a sitemap URL.");let n;try{n=new URL(s.includes("://")?s:`https://${s}`)}catch{throw new Error("Sitemap URL must be a valid web address.")}return(n.pathname===""||n.pathname==="/")&&(n.pathname="/sitemap.xml"),n.toString()}function Il(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(i=>i==="*"||i==="{slug}").length!==1||r.some(i=>i.includes("*")&&i!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(i=>i==="*"?"{slug}":i).join("/")}`}const n=t.examplePropertyUrl.trim();if(!n)throw new Error("Add one example Property page so Canonry can identify the matching URLs.");try{const a=new URL(n).pathname.split("/").filter(Boolean);if(a.length===0)throw new Error;return a[a.length-1]="{slug}",`/${a.join("/")}`}catch{throw new Error("Example Property page must be a valid web address.")}}function Wy(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,c=i.startsWith("*"),d=i.endsWith("*"),m=i.slice(c?1:0,d?-1:void 0).trim();if(!m)throw new Error("Ignored URL patterns must include text besides *.");const u=c&&d?"contains":c?"suffix":d?"prefix":"exact",x=`${u}:${m}`;n.has(x)||(n.add(x),s.push({kind:u,value:m}))}return s}function Yy(t){const s=Hy(t.sitemapUrl),n=t.examplePropertyUrl.trim()?ma(t.examplePropertyUrl):null,a=ma(t.preferredHost)??n??ma(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=ma(t.additionalHost),l=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(l!==i||l&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const c=Wy(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Il(t)},...r?{aliases:[{host:r,pathTemplate:Il({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...c.length>0?{excludedSlugPatterns:c}:{}}}}function Jy(t){return!t||t.authoring.targets.length===0?"import":t.authoring.targets.some(s=>s.status==="proposed")?"properties":t.authoring.assignments.length===0?"groups":t.baseActiveRevision===null?"review":"properties"}function Xy(t,s){return!t||t.authoring.targets.length===0?"import":!t.authoring.targets.some(n=>n.status!=="excluded")||t.authoring.targets.some(n=>n.status==="proposed")?"properties":t.authoring.assignments.length===0&&s==="review"?"groups":s}function Tl(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Zy(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Zr(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function ki(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Ll(t){return ma(t)}function cd(t,s){if(s[0]!=="targets")return;const n=s[1];if(typeof n=="number")return t?.targets[n];if(typeof n=="string")return t?.targets.find(a=>a.stableKey===n)}function dd(t,s){if(s[0]!=="groups")return;const n=s[1];if(typeof n=="number")return t?.groups[n];if(typeof n=="string")return t?.groups.find(a=>a.stableKey===n)}function ud(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function md(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function ev(t,s){const n=cd(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const l=n.urlMatchers[r];return l?`${n.label} — ${l}`:n.label}if(a==="aliases"&&typeof r=="number"){const l=n.aliases[r];return l?`${n.label} — ${l}`:n.label}return n.label}function tv(t,s){const n=dd(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const l=n.competitors.at(r)?.domain;return l?`${n.label} — ${l}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const l=md(t.authoring,n.targetKeys[r]);return`${n.label} — ${l}`}return n.label}function sv(t,s){const n=ud(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${md(t.authoring,n.targetKey)} — ${a}`}function nv(t,s){return s.path[0]==="identities"?"Project domain":ev(t,s)??tv(t,s)??sv(t,s)}function $l(t,s,n){const a=ud(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},l=s.path.at(-1);if(n==="models"&&typeof l=="string")return r.models?.[l];if(n==="locations"&&typeof l=="number")return r.locations?.[l]}function av(t,s){const n=nv(s,t);switch(t.ruleId){case"invalid-project-identity":return{title:"Fix the project domain",detail:"The project domain is not valid. Update it in project settings, then review again.",tone:"negative",affected:n};case"target-limit-exceeded":return{title:"Reduce Properties",detail:"This setup exceeds the Properties publishing limit. Remove some Properties, then review again.",tone:"negative"};case"duplicate-target-key":return{title:"Resolve duplicate Properties",detail:"Two Properties use the same setup identifier. Rename or recreate one, then review again.",tone:"negative",affected:n};case"no-included-targets":return{title:"Include a Property",detail:"Include at least one Property before publishing.",tone:"negative"};case"target-url-matcher-invalid":return{title:"Fix a Property URL",detail:"Use a valid web address, site-wide address, or URL pattern for this Property.",tone:"negative",affected:n};case"target-url-matcher-unowned":return{title:"Use a project domain",detail:"This Property URL must use the project domain or one of its subdomains.",tone:"negative",affected:n};case"target-url-matcher-ambiguous":return{title:"Separate Property URL coverage",detail:"This URL is assigned to more than one Property at the same specificity. Update one of the URLs.",tone:"negative",affected:n};case"target-alias-ambiguous":return{title:"Use distinct Property names",detail:"This name or alias matches another Property. Make each Property name and alias distinct.",tone:"negative",affected:n};case"execution-context-no-provider":return{title:"Choose a provider",detail:"Choose at least one provider before publishing.",tone:"negative",affected:n};case"invalid-provider-model":return{title:"Fix provider settings",detail:"Choose the provider that runs this model, or remove the model setting.",tone:"negative",affected:[n,$l(s,t,"models")].filter(Boolean).join(" — ")||void 0};case"invalid-location":return{title:"Fix a location",detail:"Choose a location configured for this project, or remove it from the query.",tone:"negative",affected:[n,$l(s,t,"locations")].filter(Boolean).join(" — ")||void 0};case"target-without-aliases":return{title:"Add Property aliases",detail:"Add a name or alias to measure mentions.",tone:"caution",affected:n};case"duplicate-group-key":return{title:"Resolve duplicate groups",detail:"Two groups use the same setup identifier. Rename one group, then review again.",tone:"negative",affected:n};case"group-unknown-target":return{title:"Fix group Properties",detail:"This group contains a Property that is no longer in setup. Remove it or add the Property back.",tone:"negative",affected:n};case"group-excluded-target":return{title:"Include or remove a grouped Property",detail:"This group contains an excluded Property. Include it or remove it from the group.",tone:"negative",affected:n};case"competitor-invalid-domain":return{title:"Fix a competitor domain",detail:"Enter a valid competitor domain.",tone:"negative",affected:n};case"competitor-matches-project":return{title:"Remove a project domain",detail:"A competitor cannot use the project domain.",tone:"negative",affected:n};case"competitor-duplicate":return{title:"Remove a duplicate competitor",detail:"List each competitor domain only once in a group.",tone:"negative",affected:n};case"duplicate-assignment":return{title:"Remove a duplicate query",detail:"Assign each query to a Property only once.",tone:"negative",affected:n};case"assignment-unknown-target":return{title:"Fix a query assignment",detail:"This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.",tone:"negative",affected:n};case"assignment-excluded-target":return{title:"Include or unassign a Property",detail:"This query is assigned to an excluded Property. Include it or remove the assignment.",tone:"negative",affected:n};case"assignment-unknown-query":return{title:"Remove an unavailable query",detail:"This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.",tone:"negative",affected:n};case"assignment-unclassified":return{title:"Classify a query",detail:"Choose Branded or Non-brand for this query before publishing.",tone:"negative",affected:n};case"query-limit-exceeded":return{title:"Reduce queries",detail:"This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.",tone:"negative"};case"target-without-assignments":return{title:"Assign queries",detail:"Assign at least one query to measure a Property.",tone:"caution",affected:n};case"invalid-compiled-plan":return{title:"Fix setup details",detail:"A setup value could not be validated. Review the affected item, then review again.",tone:"negative",affected:n};case"compiled-plan-too-large":return{title:"Reduce setup size",detail:"This setup is too large to publish. Remove Properties, queries, or groups, then review again.",tone:"negative"};case"active-revision-schema-v1":return{title:"Historical results will be kept",detail:"Existing results remain visible after you publish this setup.",tone:"neutral"}}return{title:t.severity==="fail"?"An unexpected setup issue blocks publishing":"An unexpected setup issue needs review",detail:t.severity==="fail"?"Review the affected item, make a correction, and review again. If it remains blocked, contact support.":"Review the affected item before publishing. If it remains, contact support.",tone:t.severity==="fail"?"negative":"caution",affected:n}}function tr(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function hd(t){const s=[...new Set(t)];return s.length===0?"":s.length===1?` Affected: ${s[0]}.`:s.length<=3?` Affected: ${s.join(", ")}.`:` Affected: ${s.slice(0,3).join(", ")}, and ${s.length-3} more.`}function rv(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${tr(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${tr(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${tr(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${tr(n,"item")} need review.`:s}})()}${hd(a)}`}function iv(t,s){const n=new Map;for(const a of t){const r=av(a,s),l=[a.ruleId,a.severity,r.title,r.detail].join("\0"),i=n.get(l)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};i.paths.add(JSON.stringify(a.path)),r.affected&&i.affected.add(r.affected),n.set(l,i)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:rv(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function ei(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function ti(t,s,n){const a=cd(n,t.path),r=dd(n,t.path),l=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=l?n?.targets.find(u=>u.stableKey===l):void 0,c=a?.label??r?.label,d=hd(c?[c]:[]),m={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...m,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...m,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${d}`};case"group-unknown-target":return{...m,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const u=ei(a)??"the proposed Property";return{...m,title:"Review a new Property",detail:`Review ${u}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const u=ei(a)??"the proposed Property",x=i?.label??"an existing Property";return{...m,title:"Review a moved Property",detail:`Review ${u}. It may be the same Property as ${x}.`}}case"measurement.discovery.rebind_ambiguous":{const u=ei(a)??"the proposed Property",x=i?.label??"an existing Property";return{...m,title:"Choose an existing Property",detail:`Review ${u}. It may match ${x}; choose the correct Property.`}}default:return{...m,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function ov(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,r=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,l=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),l>0&&n.push(`${l} query assignment ${l===1?"change":"changes"}`),r>0&&n.push(`${r} group ${r===1?"change":"changes"}`),s&&n.unshift("Existing results remain visible after you publish this setup."),{title:s?"Historical results will be kept":t.activeRevision===null?"New setup ready":"Changes ready",items:n.length>0?n:["No changes from the published setup."]}}function Ls(t){return[...new Set(t)]}function an(t){return Ls(t).sort()}function lv(t,s,n){return t.kind==="groups"?{groupKeys:an(t.groupIds),queryIds:an(n)}:{targetKeys:an(t.kind==="all"?s:t.kind==="specific"?t.propertyIds:[]),queryIds:an(n)}}function cv(t){return{assignmentCount:t.assignments.requested,addedAssignments:t.assignments.added,alreadyPresentAssignments:t.assignments.alreadyPresent,resolvedPropertyCount:t.resolvedTargetKeys.length,overlapCount:t.overlapCount,addedProviderCalls:t.execution.addedProviderCalls,fullRunProviderCalls:t.execution.fullRunProviderCalls}}function ql(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function dv(t){const s=t.plan;if(s.schemaVersion===2)return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urlMatchers.map(ql).filter(Boolean),source:a.discoveryIdentity?"sitemap":"manual",...a.discoveryIdentity?{discoveryIdentity:a.discoveryIdentity}:{}})),assignments:s.assignments.map(a=>({targetKey:a.targetKey,queryId:a.queryId,queryClass:a.queryClass,classificationSource:"operator"})),groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:a.competitors.map(r=>({...r,aliases:[...r.aliases]}))}))};const n=s.targetQuerySelections.flatMap(a=>a.queryIds.map(r=>({targetKey:a.targetKey,queryId:r,queryClass:"unclassified",classificationSource:"rule"})));return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urls.map(ql).filter(Boolean),source:"manual"})),assignments:n,groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:(a.competitors??[]).map(r=>({stableKey:ki(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function uv({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:l,canEdit:i=!0,onCreateQueries:c,onManageProjectQueries:d,onPublished:m,service:u=_h}){const[x,f]=o.useState(null),[p,g]=o.useState(null),[y,v]=o.useState("import"),[C,b]=o.useState(!0),[L,k]=o.useState(null),[h,j]=o.useState(null),[w,P]=o.useState([]),[q,S]=o.useState({...Rl}),[V,F]=o.useState("idle"),[D,K]=o.useState(""),[H,se]=o.useState(Pl),[Q,M]=o.useState([]),[J,E]=o.useState([]),[W,T]=o.useState({kind:"none"}),[ee,_]=o.useState(null),[ae,ie]=o.useState(null),[Re,X]=o.useState(!1),[ue,ve]=o.useState(null),[Z,he]=o.useState(0),[G,me]=o.useState(null),[De,ke]=o.useState({...la}),[oe,pe]=o.useState(null),[we,Ke]=o.useState(""),[Me,O]=o.useState(null),[U,B]=o.useState(!1),[Te,He]=o.useState(!1),[Be,Ze]=o.useState(null),[xe,jt]=o.useState(null),[_e,et]=o.useState(null),[zt,rt]=o.useState(null),[tt,pt]=o.useState(null),Nt=o.useRef(0),_t=o.useRef(0),Ve=p?.draft??null,A=p?.etag??null,$e=o.useMemo(()=>!i&&l?{baseActiveRevision:l.revision,authoring:dv(l)}:null,[i,l]),Pe=Ve??$e;async function ze(z){const le=++Nt.current;b(!0),k(null);try{let[Ae,ce]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);if(!ce.draft&&z&&i&&(await u.createDraft(t,Ae.activeRevision),[Ae,ce]=await Promise.all([u.loadSetup(t),u.loadDraft(t)])),le!==Nt.current)return;f(Ae),g(ce),v(Jy(ce.draft));const ge=Zr(ce.draft);M(ge)}catch(Ae){if(le!==Nt.current)return;k(ls(Ae,"Could not load advanced measurement setup."))}finally{le===Nt.current&&b(!1)}}o.useEffect(()=>(ze(!0),()=>{Nt.current+=1}),[t,i,u]),o.useEffect(()=>{!C&&!Ve&&$e&&v("properties")},[Ve,C,$e]);async function wt(){const z=await u.loadDraft(t);return g(z),z}async function it(z){pt(null);try{const[le,Ae]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);f(le),g(Ae);const ce=Zr(Ae.draft);M(ce),v(ge=>Xy(Ae.draft,ge)),j(z)}catch(le){j(ls(le,z))}}async function Fe(z,le,Ae,ce={}){const{preserveBusyAction:ge=!1}=ce;if(!i||!A||_e&&!ge)return null;ge||et(z),j(null),pt(null);try{const Ge=await le(A),mt=await wt();return P((Ge.warnings??[]).map((Rt,bs)=>ti(Rt,bs,mt.draft?.authoring))),mt}catch(Ge){return jn(Ge)?await it("This setup changed in another session. The latest draft is loaded; review your changes again."):j(ls(Ge,Ae)),null}finally{ge||et(null)}}const te=o.useMemo(()=>(Pe?.authoring.targets??[]).map(z=>{const le=Tl(z);return{id:z.stableKey,name:z.label,url:le[0]??"No URL",urls:le,state:Zy(z.status)}}),[Pe]),Ue=o.useMemo(()=>Pe?.authoring.targets.filter(z=>z.status==="included")??[],[Pe]),qe=o.useMemo(()=>Ue.map(z=>({id:z.stableKey,label:z.label,urlCount:Tl(z).length})),[Ue]),Ce=Pe?.authoring.assignments.length??0,gt=o.useMemo(()=>{if(!Pe)return[];const z=new Set(s.map(ce=>ce.id)),le=s.map(ce=>({id:ce.id,text:ce.query,source:"saved-project-queries",propertyIds:Ls(Pe.authoring.assignments.filter(ge=>ge.queryId===ce.id).map(ge=>ge.targetKey))})),Ae=Ls(Pe.authoring.assignments.map(ce=>ce.queryId).filter(ce=>!z.has(ce))).map(ce=>({id:ce,source:"unavailable-tracked-query",state:"missing",propertyIds:Ls(Pe.authoring.assignments.filter(ge=>ge.queryId===ce).map(ge=>ge.targetKey))}));return[...le,...Ae]},[s,Pe]),Qt=o.useMemo(()=>(Pe?.authoring.groups??[]).map(z=>({id:z.stableKey,name:z.label,propertyIds:z.targetKeys,competitors:z.competitors.map(le=>le.domain)})),[Pe]),Kt=o.useMemo(()=>{if(J.length===0)return null;const z=lv(W,qe.map(Ae=>Ae.id),J);return(z.groupKeys?.length??z.targetKeys?.length??0)>0?z:null},[W,qe,J]),Zt=Kt?JSON.stringify(Kt):"";o.useEffect(()=>{const z=Kt,le=++_t.current;if(!i||!Ve||!A||!z){_(null),ie(null),ve(null),X(!1);return}_(null),ie(null),ve(null),X(!0);const Ae=window.setTimeout(()=>{u.previewAssignments(t,z).then(ce=>{if(le===_t.current){if(ce.draftEtag!==A){_(null),ie(null),ve("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}_(ce),ie(Zt)}}).catch(ce=>{le===_t.current&&(_(null),ie(null),ve(Kh(ce)))}).finally(()=>{le===_t.current&&X(!1)})},250);return()=>{window.clearTimeout(Ae),_t.current+=1}},[Kt,Zt,Z,i,Ve,A,t,u]);const It=o.useMemo(()=>[...Ce===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...Pe?.authoring.assignments.some(z=>z.queryClass==="unclassified")&&!($e&&l?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...w],[Ce,$e,l,w,Pe]),vt=n?{status:"unavailable",message:"Tracked queries are loading."}:a?{status:"unavailable",message:"Tracked queries could not be loaded. Retry before assigning Properties."}:{status:"available"};async function ps(z){let le;try{le=Yy(z)}catch(ce){j(ls(ce,"Check the sitemap details and try again."));return}S(z),F("reviewing");const Ae=await Fe("import",ce=>u.importSitemap(t,ce,le),"Could not review this sitemap.");if(Ae?.draft){const ce=Ae.draft.authoring.targets.filter(Ge=>Ge.status==="proposed").map(Ge=>Ge.stableKey),ge=Ae.draft.authoring.targets.filter(Ge=>Ge.status==="included").map(Ge=>Ge.stableKey);M([...ge,...ce]),K(""),se(Pl),v("properties"),F("idle")}else F("error")}async function dt(z){if(!c||z.length===0||_e)return[];et("create-queries"),rt(null);try{return await c(z)}catch(le){throw rt(Ct(le)),le}finally{et(null)}}async function gs(z){if(!Ve||!A||_e)return;const le=new Set(z),ce=Ve.authoring.targets.filter(Ge=>Ge.status==="proposed"&&Ge.discoveryIdentity).map(Ge=>({discoveryIdentity:Ge.discoveryIdentity,action:le.has(Ge.stableKey)?"create":"ignore"})),ge=ce.length>0||Ve.authoring.targets.some(Ge=>Ge.status!=="proposed"&&Ge.status==="included"!==le.has(Ge.stableKey));et("properties"),j(null),pt(null);try{if(!ge){M([...le]),T({kind:"none"}),v("groups");return}await u.applySitemapSelection(t,A,ce,[...le]);const Ge=await wt(),mt=Zr(Ge.draft);M(mt),T({kind:"none"}),v("groups")}catch(Ge){jn(Ge)?await it("This setup changed in another session. The latest Properties are loaded."):j(ls(Ge,"Could not save the selected Properties."))}finally{et(null)}}async function Fs(z){const le=z.groupIds&&z.groupIds.length>0?{groupKeys:an(z.groupIds),queryIds:an(z.queryIds)}:{targetKeys:an(z.propertyIds),queryIds:an(z.queryIds)};if(!ee||ae!==JSON.stringify(le)||!A||ee.draftEtag!==A){j("Review the latest assignment impact before assigning queries.");return}await Fe("assignments",ce=>u.applyAssignments(t,ce,le),"Could not apply these queries.")&&(E([]),me(`${ee.assignments.added} new assignment${ee.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function St(z){if(z.propertyIds.length===0)return;await Fe("replace-assignments",Ae=>u.replaceAssignments(t,Ae,{targetKeys:Ls(z.propertyIds),queryIds:[z.queryId]}),"Could not replace this query assignment.")&&(E(Ae=>Ae.filter(ce=>ce!==z.queryId)),me("Query assignments replaced."))}async function Gs(z,le=!1){if(z.length===0)return;if(!await Fe("paired-assignments",ce=>u.applyPairedAssignments(t,ce,[...z]),"Could not assign these queries.",{preserveBusyAction:le}))throw new Error("Could not assign these queries.")}async function Lt(z){if(!(!i||!c||z.length===0||_e)){et("create-and-pair-questions"),rt(null);try{let le;try{le=await c(Ls(z.map(ge=>ge.text)))}catch(ge){throw rt(Ct(ge)),ge}const Ae=new Map(le.map(ge=>[ge.query,ge.id])),ce=z.map(ge=>({targetKey:ge.propertyId,queryId:Ae.get(ge.text)})).filter(ge=>ge.queryId!==void 0);if(ce.length!==z.length){const ge=new Error("The created queries could not be matched to their Properties.");throw rt("The queries were added, but could not be paired with every Property. Try again to pair them."),ge}try{await Gs(ce,!0)}catch(ge){throw rt("The queries were added, but could not be assigned to their Properties. Try again to pair them."),ge}}finally{et(null)}}}async function fs(z){if(!Ve)return;const le=Ls(Ve.authoring.assignments.filter(ce=>ce.queryId===z).map(ce=>ce.targetKey));if(le.length===0)return;await Fe(`remove-${z}`,ce=>u.removeAssignment(t,ce,le,z),"Could not clear this query assignment.")&&E(ce=>ce.filter(ge=>ge!==z))}async function es(z){if(!Ve||!A||_e)return;const le=z.name.trim();if(!le)return;const Ae=oe??ki(le,"group"),ce=Ve.authoring.groups.find(Rt=>Rt.stableKey===Ae);if(ce&&oe===null){j(`A group named "${ce.label}" already exists. Edit it or choose a different name.`);return}const ge=z.competitorDomains.split(/[\s,]+/).map(Rt=>Rt.trim()).filter(Boolean),Ge=ge.find(Rt=>Ll(Rt)===null);if(Ge){j(`"${Ge}" is not a valid competitor domain.`);return}const mt=Ls(ge.map(Rt=>Ll(Rt)));et("group"),j(null),pt(null);try{const Rt=await u.upsertGroup(t,A,{stableKey:Ae,label:le,targetKeys:Ls(z.propertyIds),competitors:mt.map($=>ce?.competitors.find(Se=>Se.domain===$)??{stableKey:ki($,"competitor"),label:$,domain:$,aliases:[]})}),bs=await wt();P(Rt.warnings.map(($,Se)=>ti($,Se,bs.draft?.authoring))),ke({...la}),pe(null)}catch(Rt){jn(Rt)?await it("This setup changed in another session. The latest groups are loaded."):j(ls(Rt,"Could not save this group."))}finally{et(null)}}function ts(z){const le=Ve?.authoring.groups.find(Ae=>Ae.stableKey===z);le&&(pe(z),ke({name:le.label,propertyIds:[...le.targetKeys],competitorDomains:le.competitors.map(Ae=>Ae.domain).join(", ")}))}async function xt(z){await Fe("remove-group",Ae=>u.removeGroup(t,Ae,z),"Could not remove this group.")&&(T(Ae=>Ae.kind==="groups"&&Ae.groupIds.includes(z)?{kind:"none"}:Ae),oe===z&&(pe(null),ke({...la})))}function Ht(z){Ke(z),O(null),Ze(null),jt(null)}async function ss(){if(!(!i||!we.trim()||U||Te)){B(!0),Ze(null),jt(null);try{O(await u.previewGroupMembership(t,{csv:we}))}catch(z){O(null),Ze(ls(z,"Could not review this CSV."))}finally{B(!1)}}}async function ns(z){if(!(!i||!A||!Me||z.length===0||_e)){if(Me.draftEtag!==A){Ze("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}He(!0),et("group-import"),Ze(null),jt(null),pt(null);try{const le=await u.applyGroupMembership(t,A,{csv:we,sourceChecksum:Me.sourceChecksum,previewChecksum:Me.previewChecksum,acceptedRows:Ls(z.map(String)).map(Number)}),Ae=await wt();P(le.warnings.map((ce,ge)=>ti(ce,ge,Ae.draft?.authoring))),Ke(""),O(null),jt(`${le.addedMemberships} membership${le.addedMemberships===1?"":"s"} added${le.unchangedMemberships>0?`; ${le.unchangedMemberships} already present`:""}.`)}catch(le){jn(le)?(await it("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ze("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ze(ls(le,"Could not apply this CSV."))}finally{et(null),He(!1)}}}async function $t(){if(!(!Ve||!A||_e||Ce===0)){et("review"),j(null),pt(null);try{const[z,le]=await Promise.all([u.compilePreview(t),u.diffPreview(t)]),Ae=[...z.checks,...le.checks],ce=Ae.some(ge=>ge.ruleId==="active-revision-schema-v1");if(P(iv(Ae.filter(ge=>ge.ruleId!=="active-revision-schema-v1"),{authoring:Pe?.authoring,queries:s})),!z.ok||!le.ok)return;if(le.diff.activeRevision!==Ve.baseActiveRevision){await it("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(z.compiledChecksum!==le.compiledChecksum){j("The setup changed while it was being reviewed. Review the latest changes again.");return}pt({etag:A,baseActiveRevision:Ve.baseActiveRevision,compiledChecksum:z.compiledChecksum,changes:ov(le.diff,ce),providerCalls:z.plan.executionNodes.reduce((ge,Ge)=>ge+Ge.expectedSnapshots,0)})}catch(z){j(ls(z,"Could not review this setup."))}finally{et(null)}}}async function ys(){if(!(!Ve||!A||!tt||_e)){if(A!==tt.etag||Ve.baseActiveRevision!==tt.baseActiveRevision){pt(null),j("The setup changed after review. Review the latest changes before publishing.");return}et("publish"),j(null);try{await u.publish(t,A,{expectedActiveRevision:tt.baseActiveRevision,expectedCompiledChecksum:tt.compiledChecksum}),g({draft:null,etag:null}),pt(null),m?.()}catch(z){jn(z)?await it("The setup changed before it could be published. Review the latest draft and publish again."):j(ls(z,"Could not publish this setup."))}finally{et(null)}}}async function ot(){if(!(!A||_e)){et("discard"),j(null);try{await u.discard(t,A),g({draft:null,etag:null}),pt(null),m?.()}catch(z){jn(z)?await it("This setup changed in another session. The latest draft is loaded."):j(ls(z,"Could not discard these changes."))}finally{et(null)}}}async function At(){if(!(!Ve||!A||!x||_e)){et("restart"),j(null),pt(null);try{await u.discard(t,A),await u.createDraft(t,x.activeRevision),S({...Rl}),K(""),M([]),E([]),T({kind:"none"}),_(null),ve(null),me(null),ke({...la}),pe(null),Ke(""),O(null),Ze(null),jt(null),await ze(!1)}catch(z){jn(z)?await it("The setup changed again. Reloaded the latest draft and published setup."):j(ls(z,"Could not restart this setup."))}finally{et(null)}}}if(C)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if(L)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-error-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-error-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:L}),e.jsx(R,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{ze(!0)},children:"Try again"})]})]});if(!Pe||i&&!A)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-empty-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-empty-title",children:"Advanced measurement setup"})}),e.jsx("p",{className:"text-sm text-secondary",children:i?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(i&&Ve&&x&&Ve.baseActiveRevision!==x.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(R,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:_e==="restart",onClick:()=>{At()},children:_e==="restart"?"Restarting…":"Discard draft and restart"})]}),h?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:h}):null]});const vs=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[x?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,h?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:h}):null,vs,y==="import"||y==="properties"?e.jsx(er,{currentStep:y,hasDraft:Ve!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{ot()},importProperties:{importDraft:q,onImportDraftChange:z=>{S(z),F("idle"),j(null)},onReviewSitemap:z=>{ps(z)},reviewState:V,properties:te,propertiesState:"ready",propertiesSearch:D,onPropertiesSearchChange:K,maxVisibleProperties:H,onShowAllProperties:()=>se(te.length),selectedPropertyIds:Q,onSelectedPropertyIdsChange:z=>M([...z]),onContinue:z=>{gs(z)},isContinuing:_e==="properties",onRetryProperties:()=>{wt()},onReturnToImport:()=>v("import")}}):y==="queries"?e.jsx(er,{currentStep:"queries",hasDraft:Ve!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{ot()},onManageProjectQueries:d,queries:{onCreateQueries:c?z=>dt(z):void 0,isCreatingQueries:_e==="create-queries"||_e==="create-and-pair-questions",isBusy:_e!==null,createQueriesError:zt,availability:vt,properties:qe,queries:gt,selectedQueryIds:J,isApplying:_e==="assignments"||_e==="paired-assignments",onSelectedQueryIdsChange:z=>E([...z]),onApplySelectedQueries:z=>Fs(z),groups:Qt,audience:W,onAudienceChange:z=>{T(z),me(null)},assignmentImpact:ee&&ae===Zt&&ee.draftEtag===A?cv(ee):null,isPreviewingAssignmentImpact:Re,assignmentImpactError:ue,onRetryAssignmentImpact:()=>he(z=>z+1),assignmentNotice:G,onReplaceAssignments:St,isReplacingAssignments:_e==="replace-assignments",onCreateAndPairQuestions:i&&c?Lt:void 0,onClearQueryAssignments:fs,onRemoveQuery:fs,canContinue:Ce>0,onBack:()=>v("groups"),onContinue:()=>v("review")}}):y==="groups"?e.jsx(er,{currentStep:"groups",hasDraft:Ve!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{ot()},groups:{properties:qe,groups:Qt,groupDraft:De,isSaving:_e==="group",onGroupDraftChange:ke,onSaveGroup:es,onEditGroup:z=>ts(z.id),onRemoveGroup:xt,onClearGroupDraft:()=>{pe(null),ke({...la})},membershipImport:{csv:we,preview:Me,isReviewing:U,isApplying:Te,error:Be,notice:xe,onCsvChange:Ht,onReview:ss,onApply:ns},onBack:()=>{v("properties")},onContinue:()=>v("queries")}}):e.jsx(er,{currentStep:"review",hasDraft:Ve!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{ot()},review:{counts:{properties:Ue.length,queries:new Set(Pe.authoring.assignments.map(z=>z.queryId)).size,groups:Pe.authoring.groups.length,assignments:Pe.authoring.assignments.length,providerCalls:tt?.providerCalls},flaggedExceptions:It,reviewedChanges:tt?.changes,isReviewing:_e==="review",canReviewChanges:Ce>0&&!_e,onReviewChanges:$t,onBack:()=>v("queries"),canPublish:tt!==null&&!_e,isPublishing:_e==="publish",onPublish:ys}})]})}const mv="Mentioned = the property’s name in the answer. Cited = one of the property’s own pages in the sources. Neither implies the other.",hv=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Ml(t){return t.label!=="Complete"}const Cn="__all_properties__",xv=50,xd=50,pv=20,gv=50,fv=250,yv=5,vv=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],bv={"this-property":"Matches this Property","another-property":"Matches another Property","owned-unassigned":"Site URL not included in a Property",external:"External URL","multiple-properties":"Matches multiple Properties","invalid-url":"Invalid URL"},pd={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",identity_ambiguous:`${go}.`,"identity-ambiguous":`${go}.`,not_applicable:"Not applicable.",incomplete:"The latest measurement is incomplete.","evidence-incomplete":"Some source evidence is incomplete.","no-population":"No measurements are available for this selection.",unavailable:"This measurement is unavailable."},jv={numerator:null,denominator:null,reason:"plan_v1"};function Vn(t){return t.numerator===null?!1:Number.isFinite(t.numerator)&&Number.isFinite(t.denominator)&&t.numerator>=0&&t.denominator>0&&t.numerator<=t.denominator}function Nv(t){return Vn(t)?`${t.numerator} of ${t.denominator} (${Xe(t.numerator/t.denominator)})`:"N/A"}function gd(t){if(Vn(t))return"";const s=t.reason??"unavailable";return pd[s]??s}function El(t){const s=[];return t.market&&s.push(t.market),t.urls.length>0&&s.push(`${t.urls.length} ${t.urls.length===1?"URL":"URLs"}`),s.join(" · ")}function wv(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function Sv(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function Cv(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function ha({metric:t,signal:s,compact:n=!1}){const a=n?Vn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Vn(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary",r=Vn(t)?$i(t,s):null;return e.jsxs("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...Vn(t)?{}:{title:gd(t)},children:[e.jsx("span",{className:a,children:Nv(t)}),r?e.jsx("span",{className:"text-xs text-secondary",children:r}):null]})}function eo({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Dl({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,l]=o.useState(xd),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((c,d)=>e.jsx("li",{className:a,children:c},`${c}:${d}`))}),e.jsx(eo,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>l(Number.MAX_SAFE_INTEGER)})]})]})}function kv({evidence:t,state:s="ready",onRetry:n}){const[a,r]=o.useState(xd),l=t.slice(0,a);return e.jsxs("section",{"aria-label":"Evidence",children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:"Evidence"}),s==="loading"?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Loading evidence…"}):s==="error"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsx("span",{children:"Evidence could not be loaded."}),n?e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:l.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(fe,{tone:i.tone,children:bv[i.kind]}),i.historical?e.jsx(fe,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(eo,{shown:l.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Av({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Dl,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Dl,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(kv,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Rv({values:t}){return e.jsxs("section",{"aria-labelledby":"advanced-measurement-share-of-voice",className:"border-y border-default py-4",children:[e.jsx("h2",{id:"advanced-measurement-share-of-voice",className:"text-sm font-medium text-heading",children:"Brand share of voice"}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[420px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Share of voice"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.name}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:s.coverage,signal:"mentioned",compact:!0})})]},s.name))})]})})]})}function Ol({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function l(i){if(r)return;const c=n.findIndex(u=>u.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(c+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(c-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const m=n[d];a(m.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:l,children:n.map(i=>{const c=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":c,tabIndex:c?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${c?"segmented-option-active":""}`,children:i.label},i.value)})})}function Pv({outcomes:t}){const s=[{key:"both",count:t.bothSignals,label:"mentioned and cited",tone:"text-primary"},{key:"mentioned-only",count:t.mentionedOnly,label:"mentioned only",tone:"text-primary"},{key:"cited-only",count:t.citedOnly,label:"cited only",tone:"text-primary"},{key:"neither",count:t.neither,label:"neither signal",tone:"text-negative"},...t.notMeasured>0?[{key:"not-measured",count:t.notMeasured,label:"not measured",tone:"text-faint"}]:[]];return e.jsx("div",{"aria-label":"Property outcomes",className:"flex flex-wrap gap-x-8 gap-y-3 py-3",children:s.map(n=>e.jsxs("div",{className:"whitespace-nowrap",children:[e.jsx("p",{className:`font-mono text-xl font-semibold leading-none tabular-nums ${n.tone}`,children:n.count}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary",children:[n.label,n.key==="not-measured"?e.jsx(Oe,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function Iv({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:l=!1,isViewLoading:i=!1,isLoadingMore:c=!1,isLoadMoreError:d=!1,viewSearch:m,onViewChange:u,onLoadMore:x,onPropertyExpand:f,onRetryEvidence:p,renderPropertyLink:g}){const y=t.currentView!=null,v=t.classReporting==="available"&&(y||t.classScopes!=null),[C,b]=o.useState(t.currentView?.queryClass??"all"),[L,k]=o.useState(t.currentView?.scope.key??Cn),[h,j]=o.useState(m??""),[w,P]=o.useState(xv),[q,S]=o.useState(pv),[V,F]=o.useState(t.currentView?.sort??"label-asc"),[D,K]=o.useState(null),H=o.useRef(m??""),se=v&&!y&&C!=="all"?C==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,Q=y?{aggregate:t.currentView.aggregate,groups:[]}:se,M=o.useCallback(O=>{if(!y||!u)return;const U=O.scope??(L===Cn?"all":"group"),B=O.search??h;H.current=B,u({scope:U,...U==="group"?{groupKey:O.groupKey??L}:{},queryClass:O.queryClass??C,...B?{search:B}:{},...O.sort?{sort:O.sort}:{}})},[u,h,C,L,y]);o.useEffect(()=>{!t.currentView||i||(b(t.currentView.queryClass),k(t.currentView.scope.key??Cn),t.currentView.sort&&F(t.currentView.sort))},[i,t.currentView]),o.useEffect(()=>{m!==void 0&&(H.current=m,j(O=>O.trim()===m.trim()?O:m))},[m]),o.useEffect(()=>{if(!y||!u||h===H.current)return;const O=window.setTimeout(()=>M({search:h}),fv);return()=>window.clearTimeout(O)},[u,M,h,y]);const J=t.availableGroups??Q.groups;o.useEffect(()=>{L===Cn||J.some(O=>O.id===L)||k(Cn)},[J,L]);const E=y?void 0:Q.groups.find(O=>O.id===L),W=E?.aggregate??Q.aggregate,T=O=>v?O:jv,ee=V,_=h.trim().toLocaleLowerCase(),ae=o.useMemo(()=>!y&&_?W.properties.filter(O=>O.name.toLocaleLowerCase().includes(_)):W.properties,[W.properties,_,y]),ie=y?ae:ae.slice(0,w),Re=(y?t.currentView?.scope.kind==="group":E!=null)&&C==="non-brand"&&v&&(y||E.confirmedCompetitorCount>0)&&(W.shareOfVoice?.length??0)>0,X=v?W.unavailablePropertyCount??0:0,ue=t.flaggedResults.reduce((O,U)=>O+(U.count??1),0),ve=t.flaggedResultsTotal??ue,Z=[T(W.metrics.propertiesMentioned),T(W.metrics.mentionCoverage),T(W.metrics.citationCoverage)].map(gd).find(Boolean),he=v?t.nextActionText??Z??(X>0?`${X} ${X===1?"property is":"properties are"} unavailable.`:ve>0?`${ve} flagged ${ve===1?"result needs":"results need"} review.`:null):pd.plan_v1,De=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?wv(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,ke=Sv(t.latestMeasurement.date),oe=[{value:Cn,label:"All properties"},...J.map(O=>({value:O.id,label:O.label}))],pe=J.length>yv;function we(O){k(O),M(O===Cn?{scope:"all"}:{scope:"group",groupKey:O})}function Ke(O){b(O),M({queryClass:O})}function Me(O){const U=D!==O;K(U?O:null),U&&f?.(O)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(fe,{tone:"caution",children:"Includes historical data"}):null,De?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:De}):null,ke?e.jsx("span",{className:"text-sm text-secondary",children:ke}):null,he?e.jsx("span",{className:"text-sm text-secondary",children:he}):null,s&&v&&n?e.jsx(R,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!v?e.jsx(R,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||l,children:l?"Opening setup…":"Republish setup"}):null]})})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-b border-default pb-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-group-label",htmlFor:pe?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),pe?e.jsx("select",{id:"advanced-measurement-group",value:L,onChange:O=>we(O.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:oe.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))}):e.jsx(Ol,{ariaLabelledBy:"advanced-measurement-group-label",value:L,options:oe,onChange:we})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-class-label",className:"block text-sm font-medium text-heading",children:"Query type"}),e.jsx(Ol,{ariaLabelledBy:"advanced-measurement-class-label",value:C,options:vv,onChange:Ke,disabled:!v})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:h,onChange:O=>j(O.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&Re?e.jsx(Rv,{values:W.shareOfVoice??[]}):null,i?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(Oe,{text:mv})]}),e.jsxs("span",{className:"text-sm text-secondary",children:[t.currentView?.propertyTotal??ae.length," ",(t.currentView?.propertyTotal??ae.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Pv,{outcomes:t.currentView.outcomes}):null,e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("caption",{className:"sr-only",children:"Property measurement results"}),e.jsx("thead",{children:e.jsxs("tr",{children:[hv.map(O=>{const U=ee.startsWith(`${O.key}-`),B=U&&ee.endsWith("-desc")?"descending":U?"ascending":"none";return e.jsx("th",{"aria-sort":B,className:(O.numeric,void 0),children:u?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const Te=`${O.key}-${U&&ee.endsWith("-asc")?"desc":"asc"}`;F(Te),M({sort:Te})},"aria-label":`Sort by ${O.label.toLowerCase()}`,children:[O.label,e.jsx(Jn,{className:`h-3 w-3 transition-transform ${U?"opacity-100":"opacity-0"} ${B==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):O.label},O.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[ie.map(O=>{const U=D===O.id;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:B=>{Cv(B.target)||Me(O.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[g?g({id:O.id,name:O.name}):O.name,Ml(O.status)||O.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Ml(O.status)?e.jsx(fe,{tone:O.status.tone,children:O.status.label}):null,O.historical?e.jsx(fe,{tone:"caution",children:"Historical"}):null]}):null,El(O)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:El(O)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:O.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:O.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(R,{size:"icon",variant:"ghost","aria-expanded":U,"aria-label":U?`Hide details for ${O.name}`:`Show details for ${O.name}`,onClick:()=>Me(O.id),children:e.jsx(Jn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${U?"rotate-180":""}`,"aria-hidden":"true"})})})]},O.id),U?(O.providers??[]).map(B=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:B.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:B.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:B.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{})]},`${O.id}:${B.provider}`)):null,U?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Av,{property:O,onRetryEvidence:p})})},`${O.id}:details`):null]},O.id)}),ie.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),y&&t.currentView.nextCursor&&x?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",ie.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(R,{size:"sm",variant:"outline",disabled:c,onClick:()=>x(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):y?ie.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",ie.length," of ",t.currentView.propertyTotal]}):null:e.jsx(eo,{shown:ie.length,total:ae.length,itemLabel:"properties",onShowAll:()=>P(Number.MAX_SAFE_INTEGER)})]}),!i&&!_&&ve>0?e.jsx("section",{"aria-label":"Flagged results",className:"border-t border-default pt-4",children:e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:["Flagged results (",ve,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,q).map(O=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(fe,{tone:O.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:O.property}),e.jsx("span",{className:"text-secondary",children:O.summary})]},O.id))}),q<t.flaggedResults.length?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",t.flaggedResults.slice(0,q).reduce((O,U)=>O+(U.count??1),0)," of ",ve," flagged results"]}),e.jsx(R,{size:"sm",variant:"outline",onClick:()=>S(O=>Math.min(t.flaggedResults.length,O+gv)),children:"Show 50 more"})]}):ue<ve?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ue," of ",ve," flagged results"]}),y&&t.currentView.nextCursor&&x?e.jsx(R,{size:"sm",variant:"outline",disabled:c,onClick:()=>x(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function fd(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function Tv(t){return t.activePlanSchemaVersion===null?{surface:"simple-overview",setupAction:t.hasDraft?"continue":"set-up"}:t.activePlanSchemaVersion<2?{surface:"advanced-overview-v1",setupAction:"republish"}:{surface:"advanced-overview",setupAction:t.hasDraft?"continue":"edit"}}function Lv(t){const s=t.targets.length,n=t.groups.filter(r=>r.parentGroupKey===void 0).length,a=[`${s} ${s===1?"property":"properties"}`];return n>0&&a.push(`${n} ${n===1?"market":"markets"}`),a.join(" · ")}function $v({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:l,onRunMeasurement:i,onRetryReport:c,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:x,renderPropertyLink:f,isRunningMeasurement:p,isOpeningSetup:g,isViewLoading:y,isLoadingMore:v,isLoadMoreError:C,viewSearch:b}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&l?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",disabled:g,onClick:l,children:g?"Opening setup…":fd(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),c?e.jsx(R,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:c,children:"Retry report"}):null]}):a?e.jsx(Iv,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:l,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:x,renderPropertyLink:f,isRunningMeasurement:p,isRepublishingSetup:g,isViewLoading:y,isLoadingMore:v,isLoadMoreError:C,viewSearch:b}):e.jsx("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-secondary",children:"No advanced measurement report is available yet."})]})}const Kn={numerator:null,denominator:null,reason:"plan_v1"};function qv(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Fl(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator,...t.unattributed===void 0?{}:{unattributed:t.unattributed},...t.unchecked===void 0?{}:{unchecked:t.unchecked}}}function Mv(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Ev(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Dv(t){if(!t)return"Date unavailable";const s=new Date(t);return Number.isFinite(s.getTime())?s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}):"Date unavailable"}function Ov(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Fv(t){const s=new Map;for(const n of t){const a=Ov(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function Gv(t,s){if(t.plan.schemaVersion!==1)throw new Error("Version-one report adapter received a different setup version.");const n=t.plan,a=new Map(n.targets.map(g=>[g.stableKey,g])),r=new Map(n.querySnapshots.map(g=>[g.queryId,g.queryText])),l=new Map;for(const g of n.targetQuerySelections){const y=l.get(g.targetKey)??[];y.push(...g.queryIds.map(v=>r.get(v)).filter(v=>!!v)),l.set(g.targetKey,[...new Set(y)])}const i=Fv(s.evidence),c=n.executionNodes.reduce((g,y)=>g+y.expectedSnapshots,0),d=s.run?.status==="completed"&&c>0,m=d?c:0,u=d?c:0,x=s.targets.map(g=>{const y=a.get(g.id),v=i.get(g.id)??[],C=v.map(k=>({id:`${k.observationId}:${k.usageEdgeId}:${k.sourceUrl}`,kind:Mv(k.classification),query:k.queryText,url:k.sourceUrl,tone:Ev(k.classification),historical:k.historical||k.bridged})),b=v.some(k=>k.historical||k.bridged),L=s.run?g.completeness.complete?y?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${g.completeness.executed} of ${g.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:g.id,name:g.label,mentionCoverage:Fl(g.mentionCoverage),citationCoverage:Fl(g.citationCoverage),status:L,assignedQueries:l.get(g.id)??[],urls:y?.urls.map(qv)??[],evidence:C,historical:b}}),f=new Map(x.map(g=>[g.id,g])),p=new Map(n.groups.map(g=>[g.stableKey,g]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:m,totalSlots:u,date:Dv(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Kn,mentionCoverage:Kn,citationCoverage:Kn},properties:x},groups:s.groups.map(g=>({id:g.id,label:g.label,confirmedCompetitorCount:p.get(g.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Kn,mentionCoverage:Kn,citationCoverage:Kn},properties:g.targetIds.map(y=>f.get(y)).filter(y=>!!y)}}))},flaggedResults:[]}}function _v({project:t,onUpdateProject:s}){const[n,a]=o.useState(!1),[r,l]=o.useState(!1),[i,c]=o.useState(null),[d,m]=o.useState(t.displayName),[u,x]=o.useState(t.canonicalDomain),[f,p]=o.useState(t.country),[g,y]=o.useState(t.language),[v,C]=o.useState(t.ownedDomains??[]),[b,L]=o.useState(""),[k,h]=o.useState(t.aliases??[]),[j,w]=o.useState(""),[P,q]=o.useState(null),[S,V]=o.useState(!1),[F,D]=o.useState(!1),[K,H]=o.useState(""),[se,Q]=o.useState(""),[M,J]=o.useState(""),[E,W]=o.useState(""),[T,ee]=o.useState(""),[_,ae]=o.useState(null),[ie,Re]=o.useState(null);o.useEffect(()=>{n||(m(t.displayName),x(t.canonicalDomain),p(t.country),y(t.language),C(t.ownedDomains??[]),h(t.aliases??[]))},[t,n]);function X(){a(!1),c(null),m(t.displayName),x(t.canonicalDomain),p(t.country),y(t.language),C(t.ownedDomains??[]),h(t.aliases??[]),L(""),w("")}function ue(){const U=b.trim();U&&(v.includes(U)||C([...v,U]),L(""))}function ve(U){C(v.filter(B=>B!==U))}function Z(){const U=j.trim();if(!U)return;const B=U.toLowerCase();k.some(Te=>Te.toLowerCase()===B)||h([...k,U]),w("")}function he(U){h(k.filter(B=>B!==U))}async function G(){if(!(!d.trim()||!u.trim()||!f.trim()||!g.trim())){l(!0),c(null);try{await s(t.name,{displayName:d.trim(),canonicalDomain:u.trim(),ownedDomains:v,aliases:k,country:f.trim(),language:g.trim()}),a(!1),Ee({title:"Project settings saved",detail:`${d.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(U){c(U instanceof Error?U.message:"Failed to save")}finally{l(!1)}}}async function me(){const U=K.trim(),B=se.trim(),Te=M.trim(),He=E.trim();if(!(!U||!B||!Te||!He)){V(!0),q(null);try{const Be={label:U,city:B,region:Te,country:He};T.trim()&&(Be.timezone=T.trim()),await wm(t.name,Be),H(""),Q(""),J(""),W(""),ee(""),D(!1),Ee({title:"Search location added",detail:`${U} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${U}`,dedupeMode:"drop"})}catch(Be){q(Be instanceof Error?Be.message:"Failed to add search location")}finally{V(!1)}}}async function De(U){V(!0),q(null);try{await Nm(t.name,U),Ee({title:"Search location removed",detail:`${U} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${U}`,dedupeMode:"drop"})}catch(B){q(B instanceof Error?B.message:"Failed to remove search location")}finally{V(!1)}}async function ke(U){V(!0),q(null);try{await jm(t.name,U),Ee({title:"Default search location updated",detail:`${U} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(B){q(B instanceof Error?B.message:"Failed to set default search location")}finally{V(!1)}}async function oe(U){ae(U),Re(null);try{await Sm(t.name,U),Ee({title:`${U.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(B){Re(B instanceof Error?B.message:"Could not download tracking results.")}finally{ae(null)}}const pe=d!==t.displayName||u!==t.canonicalDomain||f!==t.country||g!==t.language||JSON.stringify(v)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(k)!==JSON.stringify(t.aliases??[]),we=!re()&&!is(),Ke="w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",Me="mb-1 block text-sm font-medium text-secondary",O=K.trim()&&se.trim()&&M.trim()&&E.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),we&&!n&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),i&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[i,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),we&&n?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Me,children:"Display name"}),e.jsx("input",{className:Ke,type:"text",value:d,onChange:U=>m(U.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Me,children:"Canonical domain"}),e.jsx("input",{className:Ke,type:"text",value:u,onChange:U=>x(U.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Me,children:"Country"}),e.jsx("input",{className:Ke,type:"text",value:f,onChange:U=>p(U.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Me,children:"Language"}),e.jsx("input",{className:Ke,type:"text",value:g,onChange:U=>y(U.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Me,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:v.map(U=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[U,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>ve(U),"aria-label":`Remove ${U}`,children:"×"})]},U))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ke} flex-1`,type:"text",placeholder:"docs.example.com",value:b,onChange:U=>L(U.target.value),onKeyDown:U=>U.key==="Enter"&&(U.preventDefault(),ue())}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:!b.trim(),onClick:ue,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Me,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:k.map(U=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[U,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>he(U),"aria-label":`Remove ${U}`,children:"×"})]},U))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ke} flex-1`,type:"text",placeholder:"Facebook",value:j,onChange:U=>w(U.target.value),onKeyDown:U=>U.key==="Enter"&&(U.preventDefault(),Z())}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:!j.trim(),onClick:Z,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(R,{type:"button",disabled:r||!pe||!d.trim()||!u.trim(),onClick:Je(G),children:r?"Saving...":"Save changes"}),e.jsx(R,{type:"button",variant:"outline",disabled:r,onClick:X,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(U=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:U},U))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(U=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:U},U))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),t.tags?.length?e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Tags"}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map(U=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:U},U))})})]}):null,e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Search Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[P&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[P,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>q(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(U=>e.jsxs("tr",{className:"border-t border-mono-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium ${U.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[U.label,U.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:U.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:U.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:U.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:U.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[we&&U.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:S,onClick:()=>{ke(U.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${U.label} as default search location`,children:"Set default"}),we&&e.jsx("button",{type:"button",disabled:S,onClick:()=>{De(U.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove search location ${U.label}`,children:"Remove"})]})})]},U.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No search locations configured"}),we?F?e.jsxs("div",{className:"mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Add search location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Label *"}),e.jsx("input",{className:Ke,type:"text",value:K,onChange:U=>H(U.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"City *"}),e.jsx("input",{className:Ke,type:"text",value:se,onChange:U=>Q(U.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Region *"}),e.jsx("input",{className:Ke,type:"text",value:M,onChange:U=>J(U.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Country *"}),e.jsx("input",{className:Ke,type:"text",value:E,onChange:U=>W(U.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Timezone (optional)"}),e.jsx("input",{className:Ke,type:"text",value:T,onChange:U=>ee(U.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(R,{type:"button",size:"sm",disabled:S||!O,onClick:Je(me),children:S?"Adding...":"Add search location"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:S,onClick:()=>{D(!1),q(null)},children:"Cancel"})]})]}):e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:()=>D(!0),children:"+ Add search location"}):null]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:_!==null,onClick:Je(()=>oe("csv")),children:_==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:_!==null,onClick:Je(()=>oe("json")),children:_==="json"?"Preparing JSON...":"Download JSON"})]})]}),ie&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:ie})]})]})]})}function ca(t){return{...t??{}}}function Kv(t,s){const n=Object.entries(t).sort(([r],[l])=>r.localeCompare(l)),a=Object.entries(s).sort(([r],[l])=>r.localeCompare(l));return n.length===a.length&&n.every(([r,l],i)=>{const c=a[i];return c?.[0]===r&&c[1]===l})}function Uv({project:t,onSave:s}){const{isAdmin:n}=Hs(),a=Le({queryKey:["settings"],queryFn:sc,staleTime:6e4,enabled:n&&!re()}),[r,l]=o.useState(t.providers.length===0),[i,c]=o.useState(t.providers),[d,m]=o.useState(()=>ca(t.providerModels)),[u,x]=o.useState({providers:t.providers,providerModels:ca(t.providerModels)}),[f,p]=o.useState(!1),[g,y]=o.useState(!1),[v,C]=o.useState(null),[b,L]=o.useState(null),k=o.useRef(null),h=a.data?.providerCatalog??[],j=o.useMemo(()=>new Set((a.data?.providers??[]).filter(K=>K.configured).map(K=>K.name)),[a.data]),w=o.useMemo(()=>{const K=new Map(a.data?.providers.map(se=>[se.name,se.model])),H=new Map(h.map(se=>[se.name,{...se,defaultModel:K.get(se.name)||se.defaultModel}]));for(const se of Object.keys(d))H.has(se)||H.set(se,{name:se,displayName:se,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...H.values()].sort((se,Q)=>se.displayName.localeCompare(Q.displayName))},[h,d,a.data?.providers]),P=!Kv(d,u.providerModels);o.useEffect(()=>{if(f||g)return;const K={providers:t.providers,providerModels:ca(t.providerModels)};x(K),l(K.providers.length===0),c(K.providers),m(K.providerModels)},[t]);function q(){y(!0),l(!1),i.length===0&&c([...j])}function S(K,H,se=!1){y(!0),m(Q=>{const M={...Q};return H==="__inherit__"?delete M[K]:H==="__custom__"?M[K]=se?"":M[K]??"":M[K]=H,M}),H==="__custom__"&&queueMicrotask(()=>k.current?.focus())}function V(K,H){y(!0),c(se=>H?[...new Set([...se,K])]:se.filter(Q=>Q!==K))}function F(){y(!1),l(u.providers.length===0),c(u.providers),m(ca(u.providerModels)),C(null),L(null)}async function D(){if(!(a.isError||a.isLoading||!r&&i.length===0)){p(!0),C(null),L(null);try{const K=Object.fromEntries(Object.entries(d).filter(([se,Q])=>Q.trim()!==""&&(r||i.includes(se)))),H={providers:r?[]:i,providerModels:K};await s(H),x({providers:[...H.providers],providerModels:ca(H.providerModels)}),y(!1),L("Engine settings saved. They apply on the next sweep.")}catch(K){C(va(K))}finally{p(!1)}}}return re()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):h.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):j.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(Ss,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":f,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:f,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{y(!0),l(!0)}})," All configured engines"]}),e.jsx("p",{className:"project-engine-help",children:"Includes engines configured later in global Settings."}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!r,onChange:q})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:w.map(K=>{const H=i.includes(K.name),se=j.has(K.name),Q=H&&!se,M=d[K.name],J=K.knownModels.some(W=>W.id===M),E=M===void 0?"__inherit__":J?M:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:H,disabled:!se&&!H,onChange:W=>V(K.name,W.target.checked)})," ",e.jsx("span",{children:K.displayName}),Q&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),H&&(K.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${K.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${K.name}`,value:E,onChange:W=>S(K.name,W.target.value,J),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",K.defaultModel||"default"]}),K.knownModels.map(W=>e.jsx("option",{value:W.id,children:W.displayName},W.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),E==="__custom__"&&e.jsx("input",{ref:k,"aria-label":`${K.displayName} custom model ID`,value:M??"",onChange:W=>{y(!0),m(T=>({...T,[K.name]:W.target.value}))},"aria-describedby":`project-model-hint-${K.name}`}),e.jsxs("p",{id:`project-model-hint-${K.name}`,className:"project-engine-help",children:[M?"Project override":"Inherited from instance settings",". ",K.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},K.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),v&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:v}),b&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:b}),P&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{type:"button",onClick:()=>{D()},disabled:f||!r&&i.length===0,children:f?"Saving engines…":"Save engines"}),e.jsx(R,{type:"button",variant:"outline",onClick:F,disabled:f,children:"Cancel"})]})]})}const Ts={heading:"Site Health scans",help:`Used by every scan that sets no budget, scheduled or manual. Onboarding's first look always checks ${Oh(Am)}.`,pageBudget:"Page budget",customOption:"Custom number...",customLabel:"Custom page budget",customError:`Enter a whole number from 1 to ${hc.toLocaleString("en-US")}.`,save:"Save page budget",saving:"Saving page budget…",saved:"Page budget saved."},to="full",zn="custom";function sr(t){return t===null?{choice:to,customText:""}:jc.some(s=>s.value===t)?{choice:String(t),customText:""}:{choice:zn,customText:String(t)}}function Bv({choice:t,customText:s}){if(t===to)return null;if(t!==zn)return Number(t);const n=s.trim();if(n==="")return;const a=km.safeParse(Number(n));return a.success?a.data:void 0}function Vv({project:t,onSave:s}){const{canWrite:n,isAdmin:a}=Hs(),r=n&&!re()&&!is()&&(!Cm(Qs["site-audit"])||a),l=t.siteAuditMaxPages??null,[i,c]=o.useState(l),[d,m]=o.useState(()=>sr(l)),[u,x]=o.useState(!1),[f,p]=o.useState(!1),[g,y]=o.useState(!1),[v,C]=o.useState(null),[b,L]=o.useState(null),k=o.useRef(null),h=o.useId(),j=`${h}-heading`,w=`${h}-page-budget`,P=`${h}-custom-page-budget`,q=`${h}-custom-page-budget-error`;o.useEffect(()=>{g||f||(c(l),m(sr(l)))},[l]);const S=Bv(d),F=d.choice===zn&&S===void 0&&(u||d.customText.trim()!==""),D=S!==void 0&&S!==i;function K(J){p(!0),C(null),L(null),m(E=>({...E,choice:J})),J===zn&&(x(!1),queueMicrotask(()=>k.current?.focus()))}function H(J){p(!0),C(null),L(null),x(!0),m(E=>({...E,customText:J}))}function se(){p(!1),m(sr(i)),x(!1),C(null),L(null)}async function Q(){if(!(g||S===void 0)){y(!0),C(null),L(null);try{await s(S),c(S),m(sr(S)),x(!1),p(!1),L(Ts.saved)}catch(J){C(va(J))}finally{y(!1)}}}const M="h-9 w-full rounded-md border border-base bg-bg px-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600 disabled:opacity-60";return e.jsxs("section",{className:"project-engine-settings","aria-labelledby":j,"aria-busy":g,children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:j,children:Ts.heading}),e.jsx(Oe,{text:Ts.help})]})}),r?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid max-w-sm gap-1",children:[e.jsx("label",{htmlFor:w,className:"text-sm font-medium text-heading",children:Ts.pageBudget}),e.jsxs("select",{id:w,value:d.choice,disabled:g,onChange:J=>K(J.target.value),className:M,children:[e.jsx("option",{value:to,children:Eh}),jc.map(J=>e.jsx("option",{value:String(J.value),children:J.label},J.value)),e.jsx("option",{value:zn,children:Ts.customOption})]}),d.choice===zn&&e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:P,className:"mt-2 text-sm font-medium text-heading",children:Ts.customLabel}),e.jsx("input",{ref:k,id:P,type:"number",inputMode:"numeric",min:1,max:hc,step:1,value:d.customText,disabled:g,"aria-invalid":F,"aria-describedby":F?q:void 0,onChange:J=>H(J.target.value),className:M}),F&&e.jsx("p",{id:q,role:"alert",className:"text-sm text-negative",children:Ts.customError})]})]}),v&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:v}),b&&e.jsx("p",{role:"status",className:"mt-3 text-sm text-positive",children:b}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(R,{type:"button",onClick:()=>{Q()},disabled:g||!D,children:g?Ts.saving:Ts.save}),e.jsx(R,{type:"button",variant:"outline",onClick:se,disabled:g||!f,children:"Cancel"})]})]}):e.jsxs("p",{className:"text-sm text-secondary",children:[Ts.pageBudget,": ",e.jsx("span",{className:"text-strong",children:Dh(i)})]})]})}function Gl(t,s,n){return Le({...Rm({client:ne,path:{name:t},query:{selection:n}}),enabled:s&&!!t,staleTime:fo,refetchOnWindowFocus:"always",refetchInterval:a=>{const r=Object.values(a.state.data?.providers??{}).map(i=>Date.parse(i.retryAfter)).filter(Number.isFinite);if(r.length===0)return!1;const l=Math.min(...r)-Date.now();return l>0?l:fo},retry:!1})}function _l(t){switch(t){case $s.PROVIDER_BILLING:return{sentence:s=>`${s.name} ran out of credit`,label:"out of credit"};case $s.PROVIDER_AUTH:return{sentence:s=>`${s.possessive} key was rejected or access was denied`,label:"key rejected or access denied"};case $s.RATE_LIMITED:case $s.PROVIDER_UNAVAILABLE:case $s.NETWORK:case $s.TIMEOUT:case $s.PARSE_ERROR:case $s.UNKNOWN:return{sentence:s=>`${s.name} failed with ${t}`,label:t}}}function nr({iso:t}){return e.jsx("time",{dateTime:t,children:ka(t)})}function Kl({admission:t,canFix:s,selection:n}){const a=o.useId(),r=Object.entries(t.providers);if(r.length===0)return null;const[l,i]=r[0],c=at(l),d=r.length===1,m=i.consecutiveRuns,u=r.find(([,g])=>g.code===$s.PROVIDER_AUTH),x=n?`${n} sweeps`:"sweeps",f=t.refused?`${n?n==="manual"?"Manual sweeps":"Scheduled sweeps":"Sweeps"} are on hold`:d?`${c} is left out of ${x}`:`${r.length} providers are left out of ${x}`;let p;if(d){const g=_l(i.code).sentence(t.refused?{name:c,possessive:`${c}'s`}:{name:"It",possessive:"Its"}),y=t.refused?t.retryAfter??i.retryAfter:i.retryAfter,v=i.code===$s.PROVIDER_BILLING?e.jsxs(e.Fragment,{children:["; add credit in ",c,"'s console before then."]}):e.jsx(e.Fragment,{children:", or as soon as its key, model or endpoint is saved."});p=t.refused?e.jsxs(e.Fragment,{children:[g," in each of its last ",m," runs, so a sweep would fail the same way. The hold lifts ",e.jsx(nr,{iso:y}),v]}):e.jsxs(e.Fragment,{children:[g," in each of its last ",m," runs. Sweeps run without it until ",e.jsx(nr,{iso:y}),v]})}else p=t.refused?e.jsxs(e.Fragment,{children:["Every provider failed on its account in each of its last ",m," runs, so a sweep would fail the same way. The hold lifts"," ",t.retryAfter?e.jsx(nr,{iso:t.retryAfter}):"at the first time below",", or as soon as a provider's key, model or endpoint is saved."]}):e.jsxs(e.Fragment,{children:["Each failed on its account in each of its last ",m," runs. Sweeps run without them until the times below, or until a key, model or endpoint is saved."]});return e.jsxs("section",{"aria-labelledby":a,className:`mb-5 flex flex-wrap items-start justify-between gap-3 rounded-md border px-4 py-3 text-sm ${t.refused?"border-negative bg-negative-soft":"border-caution bg-caution-soft"}`,children:[e.jsxs("div",{className:"min-w-0 max-w-[29rem] space-y-1",children:[e.jsx("h2",{id:a,className:`text-sm font-medium ${t.refused?"text-negative":"text-caution"}`,children:f}),e.jsx("p",{className:"text-secondary",children:p}),d?null:e.jsx("ul",{className:"text-secondary",children:r.map(([g,y])=>e.jsxs("li",{children:[at(g),": ",_l(y.code).label,", until ",e.jsx(nr,{iso:y.retryAfter})]},g))}),s?null:e.jsxs("p",{className:"text-secondary",children:["Ask an administrator to fix ",d?c:"these providers","."]})]}),s&&u?e.jsx(R,{asChild:!0,variant:"outline",size:"sm",className:"h-11 md:h-8",children:e.jsx(Ss,{to:"/settings",hash:`provider-${u[0]}`,children:d?`Update ${c} key`:"Open provider settings"})}):null]})}const ar={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},zv=[{value:"daily",label:"Every day"},{value:"weekly@mon",label:"Every Monday"},{value:"weekly@wed",label:"Every Wednesday"},{value:"weekly@fri",label:"Every Friday"},{value:"twice-daily",label:"Twice a day (6am & 6pm)"},{value:"calendar",label:"Every N days"},{value:"custom",label:"Custom cron expression"}],Ul=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Vancouver","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Australia/Sydney"];function si(t,s){const n=s==="UTC"?"UTC":s.split("/").pop()?.replace(/_/g," ")??s,a=new Date(`${t.startDate}T00:00:00Z`),r=Number.isNaN(a.getTime())?t.startDate:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(a),[l,i]=t.time.split(":").map(Number),c=Number.isInteger(l)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,l,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${c} · ${n}`}function Qv({projectName:t}){const s=Yt(),n=!re()&&!is()&&!s,a=xs(),[r,l]=o.useState(!1),[i,c]=o.useState("daily"),[d,m]=o.useState(6),[u,x]=o.useState(""),[f,p]=o.useState(14),[g,y]=o.useState(""),[v,C]=o.useState("00:00"),[b,L]=o.useState("UTC"),[k,h]=o.useState(!1),[j,w]=o.useState(""),[P,q]=o.useState(!1),[S,V]=o.useState(!1),[F,D]=o.useState(null),[K,H]=o.useState(void 0),se=Pm({client:ne,path:{name:t}}),Q=Le({...xc({client:ne,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),M=Q.isPending||Q.isFetching,J=Q.isError,E=Q.data?.find(Z=>Z.kind==="answer-visibility")??null,W=r&&K!==void 0&&(E?.updatedAt??null)!==K,T=Z=>{a.setQueryData(se,he=>{const G=(he??[]).filter(me=>me.kind!=="answer-visibility");return Z?[...G,Z]:G})},ee=Z=>{if(Z){if(Z.recurrence)c("calendar"),p(Z.recurrence.everyDays),y(Z.recurrence.startDate),C(Z.recurrence.time);else{const G=qm(Z.preset??null,Z.cronExpr);c(G.freq),m(G.hour),x(G.customCron)}const he=Ul.includes(Z.timezone);L(he?Z.timezone:"Other"),h(!he),w(he?"":Z.timezone)}else c("daily"),m(6),x(""),p(14),y(""),C("00:00"),L("UTC"),h(!1),w("");H(Z?.updatedAt??null)},_=()=>{n&&(ee(E),D(null),l(!0))},ae=()=>{ee(E),D(null)},ie=async()=>{(await Q.refetch()).isError?D("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):D(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},Re=async(Z,he)=>{if(Z instanceof ni&&Z.code==="SCHEDULE_VERSION_CONFLICT"){await ie();return}D(Z instanceof Error?Z.message:he)},X=async()=>{if(n&&!(W||K===void 0)){q(!0),D(null);try{const Z=await Q.refetch();if(Z.isError||Z.data===void 0){D("Canonry could not verify the latest schedule. Try again before saving.");return}const he=Z.data.find(ke=>ke.kind==="answer-visibility")??null;if((he?.updatedAt??null)!==K)return;const me={timezone:k?j.trim()||"UTC":b,enabled:he?.enabled??!0,providers:he?.providers??[],expectedUpdatedAt:K};i==="calendar"?me.recurrence={everyDays:f,startDate:g,time:v}:i==="custom"?me.cron=u.trim():me.preset=$m(i,d);const De=await yo(t,me);l(!1),H(void 0),T(De),Ee({title:"Schedule saved",detail:De.recurrence?si(De.recurrence,De.timezone):Rr(De.preset??null,De.cronExpr,De.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(Z){await Re(Z,"Failed to save schedule")}finally{q(!1)}}},ue=async()=>{if(!n||!E)return;const Z=E.updatedAt;q(!0),D(null);try{const he=await Q.refetch();if(he.isError||he.data===void 0){D("Canonry could not verify the latest schedule. Try again before updating it.");return}const G=he.data.find(ke=>ke.kind==="answer-visibility")??null;if(!G||G.updatedAt!==Z){D("This schedule changed elsewhere. Review the latest version and try again.");return}const me={timezone:G.timezone,enabled:!G.enabled,providers:G.providers,expectedUpdatedAt:Z};G.recurrence?me.recurrence=G.recurrence:G.preset?me.preset=G.preset:me.cron=G.cronExpr;const De=await yo(t,me);T(De),Ee({title:De.enabled?"Schedule resumed":"Schedule paused",detail:De.recurrence?si(De.recurrence,De.timezone):Rr(De.preset??null,De.cronExpr,De.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(he){await Re(he,"Failed to update schedule")}finally{q(!1)}},ve=async()=>{if(!n||!E)return;const Z=E.updatedAt;V(!0),D(null);try{await Lm(t,Z),T(null),l(!1),H(void 0),Ee({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(he){await Re(he,"Failed to remove schedule")}finally{V(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!M&&!J&&!r&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:_,children:E?ar.edit:"+ Set schedule"})]}),M&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),F&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:F}),!M&&J&&e.jsxs(Ne,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{Q.refetch()},children:"Retry"})]}),!M&&!J&&!r&&E===null&&e.jsx(Ne,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Yn:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!M&&!J&&!r&&E!==null&&e.jsx(Ne,{className:"surface-card compact-card",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[s&&e.jsx("p",{className:"text-sm text-secondary",children:Yn}),e.jsx("p",{className:"text-sm font-medium text-strong",children:E.recurrence?si(E.recurrence,E.timezone):Rr(E.preset??null,E.cronExpr,E.timezone)}),!E.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:E.cronExpr})]}),E.enabled&&E.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",Im(E.nextRunAt,E.timezone)]}),E.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(E.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(fe,{tone:E.enabled?"positive":"neutral",children:E.enabled?"Active":"Paused"}),n&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:P,onClick:Je(ue),children:E.enabled?ar.pause:ar.resume}),n&&e.jsx(R,{type:"button",variant:"ghost",size:"sm",disabled:S,onClick:Je(ve),children:S?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[W&&!P&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",role:"alert",children:[e.jsx("p",{children:"This schedule changed elsewhere. Load the latest version before saving."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:ae,children:"Load latest schedule"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Frequency",value:i,onChange:Z=>c(Z.target.value),children:zv.map(Z=>e.jsx("option",{value:Z.value,children:Z.label},Z.value))})]}),i!=="calendar"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:d,disabled:i==="twice-daily"||i==="custom",onChange:Z=>m(parseInt(Z.target.value)),children:Array.from({length:24},(Z,he)=>e.jsx("option",{value:he,children:Tm(he)},he))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:u,onChange:Z=>x(Z.target.value)})]}),i==="calendar"&&e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Repeat every"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Repeat every days",type:"number",min:"1",max:"3650",value:f,onChange:Z=>p(Number(Z.target.value))}),e.jsx("p",{className:"text-xs text-muted",children:"days"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Start date"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Start date",type:"date",value:g,onChange:Z=>y(Z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:v,onChange:Z=>C(Z.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Timezone",value:k?"Other":b,onChange:Z=>{Z.target.value==="Other"?(h(!0),L("Other")):(h(!1),L(Z.target.value))},children:[Ul.map(Z=>e.jsx("option",{value:Z,children:Z},Z)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),k&&e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:j,onChange:Z=>w(Z.target.value)})]}),F&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:F}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{l(!1),H(void 0),D(null)},children:"Cancel"}),e.jsx(R,{type:"button",size:"sm",disabled:P||Q.isFetching||J||W||i==="custom"&&!u.trim()||i==="calendar"&&(!Number.isInteger(f)||f<1||f>3650||!g||!v),onClick:Je(X),children:P?"Saving...":ar.save})]})]})]})}const Hv=[{value:"citation.lost",label:"Citation lost"},{value:"citation.gained",label:"Citation gained"},{value:"run.completed",label:"Run completed"},{value:"run.failed",label:"Run failed"}];function Wv({projectName:t}){const[s,n]=o.useState("loading"),[a,r]=o.useState(!1),[l,i]=o.useState(""),[c,d]=o.useState(["citation.lost","citation.gained"]),[m,u]=o.useState(!1),[x,f]=o.useState(null),[p,g]=o.useState({}),[y,v]=o.useState(new Set),C=!re()&&!is();o.useEffect(()=>{Mm(t).then(n).catch(()=>n([]))},[t]);const b=j=>{d(w=>w.includes(j)?w.filter(P=>P!==j):[...w,j])},L=async()=>{if(!(!l.trim()||c.length===0)){u(!0),f(null);try{const j=await Em(t,{channel:"webhook",url:l.trim(),events:c});n(w=>w==="loading"?[j]:[...w,j]),i(""),d(["citation.lost","citation.gained"]),r(!1),Ee({title:"Webhook added",detail:`Notifications will be sent to ${j.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(j){f(j instanceof Error?j.message:"Failed to add webhook")}finally{u(!1)}}},k=async j=>{if(!y.has(j)){v(w=>new Set(w).add(j));try{await Om(t,j),n(w=>w==="loading"?w:w.filter(P=>P.id!==j)),Ee({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${j}`,dedupeMode:"drop"})}catch(w){f(w instanceof Error?w.message:"Failed to remove webhook")}finally{v(w=>{const P=new Set(w);return P.delete(j),P})}}},h=async j=>{g(w=>({...w,[j]:{state:"testing"}}));try{const w=await Dm(t,j);g(P=>({...P,[j]:{state:w.ok?"ok":"fail",status:w.status}})),w.ok&&Ee({title:"Test notification sent",detail:`Webhook returned status ${w.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${j}`,dedupeMode:"replace"})}catch{g(w=>({...w,[j]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),C&&s!=="loading"&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),f(null)},children:a?"Cancel":"+ Add webhook"})]}),C&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:j=>i(j.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Hv.map(j=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:c.includes(j.value),onChange:()=>b(j.value)}),e.jsx("span",{className:"text-sm text-neutral",children:j.label})]},j.value))})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm",children:x}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),f(null)},children:"Cancel"}),e.jsx(R,{type:"button",size:"sm",disabled:m||!l.trim()||c.length===0,onClick:Je(L),children:m?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(Ne,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:j.urlHost,children:j.urlDisplay??j.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:j.events.map(w=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:w.replace("."," ")},w))})}),e.jsx("td",{children:e.jsx(fe,{tone:j.enabled?"positive":"neutral",children:j.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[p[j.id]&&(()=>{const w=p[j.id],P=w.state==="testing"?"Sending…":w.state==="ok"?`Delivered${w.status?` (${w.status})`:""}`:`Failed${w.status?` (${w.status})`:""}`;return e.jsx(fe,{tone:w.state==="ok"?"positive":w.state==="fail"?"negative":"neutral",children:P})})(),C&&e.jsx(R,{variant:"ghost",size:"sm",type:"button",disabled:p[j.id]?.state==="testing",onClick:()=>{h(j.id)},children:"Test"}),C&&e.jsx(R,{variant:"ghost",size:"sm",type:"button",disabled:y.has(j.id),onClick:()=>{k(j.id)},children:y.has(j.id)?"Removing…":"Remove"})]})})]},j.id))})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:x})]})]})}function Yv({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:l,leftOut:i=[]}){return re()||Yt()?null:e.jsx(Gm,{open:t,onOpenChange:n,children:e.jsxs(_m,{onCloseAutoFocus:c=>{r&&(c.preventDefault(),r())},children:[e.jsxs(Km,{children:[e.jsx(Um,{children:"Run AI sweep for the whole project?"}),e.jsxs(Bm,{children:["Runs all tracked queries for ",s,". View filters do not limit the sweep. Provider charges apply.",i.length>0?` ${i.map(at).join(" and ")} ${i.length===1?"is":"are"} left out: ${i.length===1?"it keeps failing on its account":"they keep failing on their accounts"}.`:null]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(R,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Ye,{disabled:l,onClick:a,children:"Run project-wide sweep"})]})]})})}const Bl=2e3,Vl=3e5;function Jv(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Xv(t,s){t.setQueriesData({predicate:n=>n.queryKey[0]==="project-dashboard-full"&&n.queryKey[1]===s.id},n=>!n||typeof n!="object"||!("project"in n)?n:{...n,project:s})}function Zv({projectName:t,refreshNonce:s}){const n=xs(),[a,r]=o.useState(null),[l,i]=o.useState([]),[c,d]=o.useState(null),[m,u]=o.useState([]),[x,f]=o.useState([]),[p,g]=o.useState(null),[y,v]=o.useState(""),[C,b]=o.useState(""),[L,k]=o.useState(""),[h,j]=o.useState(!0),[w,P]=o.useState(!1),[q,S]=o.useState(null),[V,F]=o.useState("performance");o.useEffect(()=>{D()},[t,s]);async function D(){j(!0),S(null);try{const T=await n.fetchQuery({...bc({client:ne,path:{name:t}}),staleTime:Jt});if(r(T),T.connected){const[ee,_,ae,ie]=await Promise.all([n.fetchQuery({...Rh({client:ne,path:{name:t}}),staleTime:Jt}).catch(()=>null),n.fetchQuery({...Ph({client:ne,path:{name:t}}),staleTime:Jt}).catch(()=>[]),n.fetchQuery({...Ih({client:ne,path:{name:t}}),staleTime:Jt}).catch(()=>[]),T.siteUrl?Promise.resolve([]):n.fetchQuery({...Th({client:ne,path:{name:t}}),staleTime:Jt}).then(Re=>Re.sites).catch(()=>[])]);d(ee),u(_),f(ae),i(ie)}else d(null),u([]),f([]),i([])}catch(T){S(T instanceof Error?T.message:"Failed to load Bing data")}finally{j(!1)}}async function K(){if(C.trim()){S(null);try{const T=await Lh(t,C.trim());await Dt(n,"bing"),b(""),T.availableSites.length>0&&i(T.availableSites),await D()}catch(T){S(T instanceof Error?T.message:"Failed to connect")}}}async function H(){try{await $h(t),await Dt(n,"bing"),r(null),i([]),d(null),u([]),f([]),g(null),k(""),S(null)}catch(T){S(T instanceof Error?T.message:"Failed to disconnect")}}async function se(){if(L)try{await qh(t,L),await Dt(n,"bing"),await D()}catch(T){S(T instanceof Error?T.message:"Failed to set site")}}async function Q(){if(y.trim())try{const T=await Mh(t,y.trim());await Dt(n,"bing"),g(T),u(ee=>[T,...ee])}catch(T){S(T instanceof Error?T.message:"Inspection failed")}}async function M(T){P(!0),S(null);try{const ee=await jo(t,{urls:[T]}),{succeeded:_,failed:ae,total:ie}=ee.summary;Ee({title:"Bing submission requested",detail:ae===0?`${_} URL submitted to Bing.`:`${_}/${ie} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}catch(ee){const _=ee instanceof Error?ee.message:"Submission failed";S(_),Ee({title:"Bing submission failed",detail:_,tone:"negative",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}finally{P(!1)}}async function J(){P(!0),S(null),Ee({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const T=await jo(t,{allUnindexed:!0}),{succeeded:ee,failed:_,total:ae}=T.summary;Ee({title:"Bing submissions requested",detail:_===0?`${ee}/${ae} URL${ae!==1?"s":""} submitted to Bing.`:`${ee}/${ae} submitted successfully, ${_} failed.`,tone:_===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(T){const ee=T instanceof Error?T.message:"Batch submission failed";S(ee),Ee({title:"Bing submissions failed",detail:ee,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{P(!1)}}if(h)return e.jsx(Ne,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return re()?e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(fe,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(fe,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:C,onChange:T=>b(T.target.value),onKeyDown:T=>{T.key==="Enter"&&K()}}),e.jsx(Ye,{size:"sm",disabled:!C.trim(),onClick:Je(K),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),q&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:q})]});if(!a.siteUrl)return e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{tone:"positive",children:"Connected"}),!re()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Je(H),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Xt(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),l.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:L,onChange:T=>k(T.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(T=>e.jsxs("option",{value:T.url,children:[T.url,T.verified?" (verified)":""]},T.url))]}),!re()&&e.jsx(Ye,{size:"sm",disabled:!L,onClick:Je(se),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),q&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:q})]});const E=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],W=E.find(T=>T.key===V)??E[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{tone:"positive",children:"Connected"}),!re()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Je(H),children:"Disconnect"})]})]}),q&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:q}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["This project uses ",e.jsx("code",{children:a.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Xt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(Ne,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:W.eyebrow}),e.jsx("h3",{children:W.title})]}),e.jsx("p",{className:"text-xs text-muted",children:c?.lastInspectedAt?`Last inspected ${Xt(c.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:E.map(T=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${V===T.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>F(T.key),children:T.label},T.key))}),V==="coverage"&&c&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(_a,{label:"Indexed",value:c.summary.indexed,tone:"positive"}),e.jsx(_a,{label:"Not in index",value:c.summary.notIndexed+(c.summary.unknown??0),tone:"negative"}),e.jsx(_a,{label:"Status unknown",value:c.summary.unknown??0,tone:"neutral"}),e.jsx(_a,{label:"Coverage",value:Xe(c.summary.percentage,ea.percent),tone:"neutral"})]}),c.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",c.notIndexed.length,")"]}),!re()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:w,onClick:Je(J),children:w?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!re()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:c.notIndexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),!re()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:w,onClick:()=>{M(T.url)},children:"Submit"})})]},T.id))})]})})]}),(c.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(c.unknown??[]).length,")"]}),!re()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:w,onClick:Je(J),children:w?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!re()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(c.unknown??[]).map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Xt(T.lastCrawledDate):"—"}),!re()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:w,onClick:()=>{M(T.url)},children:"Submit"})})]},T.id))})]})})]}),c.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",c.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:c.indexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Xt(T.lastCrawledDate):"—"})]},T.id))})]})})]})]}),V==="coverage"&&!c&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),V==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!re()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:y,onChange:T=>v(T.target.value),onKeyDown:T=>{T.key==="Enter"&&Q()}}),e.jsx(Ye,{size:"sm",disabled:!y.trim(),onClick:Je(Q),children:"Inspect"})]}),p&&e.jsxs("div",{className:"rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-strong",children:p.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:p.inIndex?"text-positive-400":"text-negative-400",children:p.inIndex?"Yes":"No"})," · ","HTTP: ",p.httpCode??"—"," · ","Crawled: ",p.lastCrawledDate??"—"]})]}),m.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:m.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(fe,{tone:T.inIndex?"positive":"negative",children:T.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Xt(T.inspectedAt)})]},T.id))})]})})]}),V==="performance"&&e.jsx("div",{className:"mt-4",children:x.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Fa[An.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Fa[An.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Fa[An.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Fa[An.Position]})]})}),e.jsx("tbody",{children:x.map((T,ee)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:T.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.impressions}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:Xe(T.ctr)}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.averagePosition.toFixed(1)})]},ee))})]})})})]})]})}function eb({projectName:t}){const s=xs(),[n,a]=o.useState("google"),[r,l]=o.useState(!0),[i,c]=o.useState("idle"),[d,m]=o.useState(null),u=o.useRef(null),[x,f]=o.useState(null),[p,g]=o.useState(null),[y,v]=o.useState(0);async function C(L=!1){L||l(!0),m(null);try{const[k,h]=await Promise.all([s.fetchQuery({...Ti({client:ne,path:{name:t}}),staleTime:Jt}).catch(()=>[]),s.fetchQuery({...bc({client:ne,path:{name:t}}),staleTime:Jt}).catch(()=>null)]),j=k.find(w=>w.connectionType==="gsc")??null;f(j),g(h)}catch(k){m(k instanceof Error?k.message:"Failed to load search engine connections")}finally{l(!1)}}async function b(){if(i!=="idle")return;u.current?.abort();const L=new AbortController;u.current=L;const k=L.signal;c("syncing"),m(null),Ee({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const h=[],j=[];try{async function w(){if(!x)return;const S=await kh(t);if(!S?.id)return;const V=Date.now()+Vl;for(;Date.now()<V;){if(k.aborted||(await new Promise(D=>setTimeout(D,Bl)),k.aborted))return;const F=await ai(S.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled"].includes(F.status)){F.status!=="completed"&&h.push(`Google sync ${F.status}`);return}}j.push("Google sync is still running — search data will appear shortly")}async function P(){if(!p?.connected)return;const S=await Ah(t).catch(()=>null);if(!S?.id){h.push("Bing sweep could not be started");return}const V=Date.now()+Vl;for(;Date.now()<V;){if(k.aborted||(await new Promise(D=>setTimeout(D,Bl)),k.aborted))return;const F=await ai(S.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled","partial"].includes(F.status)){F.status==="failed"?h.push("Bing sweep failed"):F.status==="partial"&&j.push("Bing sweep finished with some pages unverified");return}}j.push("Bing sweep is still running — coverage will update shortly")}const q=await Promise.allSettled([w(),P()]);for(const S of q)S.status==="rejected"&&h.push(S.reason instanceof Error?S.reason.message:"Sync failed");if(await Promise.all([Dt(s,"gsc"),Dt(s,"bing")]),k.aborted)return;if(c("reloading"),await C(!0),v(S=>S+1),h.length>0){const S=`Partial refresh: ${[...h,...j].join("; ")}`;m(S),Ee({title:"Search coverage partially refreshed",detail:S,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else j.length>0?Ee({title:"Search coverage refresh incomplete",detail:j.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Ee({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(w){if(!k.aborted){const P=w instanceof Error?w.message:"Refresh failed";m(P),Ee({title:"Search coverage refresh failed",detail:P,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{k.aborted||c("idle")}}return o.useEffect(()=>(C(),()=>{u.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([L,k])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===L,className:`project-subnav-link ${n===L?"project-subnav-link-active":""}`,onClick:()=>a(L),children:k},L))}),!re()&&e.jsxs(Ye,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{b()},children:[e.jsx(ja,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),d&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:d}),n==="google"&&e.jsx(_p,{projectName:t,refreshNonce:y}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Zv,{projectName:t,refreshNonce:y})]})]})}function zl({label:t,summary:s,displayValue:n,tooltip:a}){const{figure:r,sign:l}=Ri(s.value),i=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Oe,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${ya[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[r,l?e.jsx("span",{className:"text-faint",children:l}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${i}%`}})})]})}function tb({id:t,title:s,meta:n,defaultOpen:a=!1,children:r}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:a||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsx("h2",{className:"overview-disclosure-title",children:s}),e.jsxs("span",{className:"overview-disclosure-meta",children:[n&&e.jsx("span",{children:n}),e.jsx(Jn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function sb({insights:t,suggestedQueries:s,onManageQueries:n,siteDomain:a}){const{openEvidence:r}=Pi(),l=n?s.rows:[];if(t.length===0&&l.length===0)return null;const i=p=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:p.title}),p.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:p.detail}):null]}),e.jsx(fe,{tone:p.tone,children:p.actionLabel})]}),p.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",p.affectedPhrases.length," affected ",p.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:p.affectedPhrases.map((g,y)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ci,{state:g.citationState,...a&&g.siteCitation!==!1?{label:Hl(a,g.citationState)}:{}}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:g.query}),g.provider?e.jsx(Ch,{provider:g.provider}):null,!re()&&g.evidenceId?e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{r(g.evidenceId)},children:"View evidence"}):null]},g.evidenceId||`${p.id}-${y}`))})]}):null]},p.id),c=p=>e.jsxs("div",{className:"flex items-start justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:p.query}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:p.reason})]}),n?e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},p.query),d=t.slice(0,1),m=l.slice(0,1),u=t.slice(1),x=l.slice(1),f=u.length+x.length;return e.jsxs("section",{className:"visibility-disclosure-panel","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[d.map(i),m.map(c)]}),f>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[f," more ",f===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[u.map(i),x.map(c)]})]}):null]})}function jb(t){const{projectName:s}=kd({from:"/projects/$projectName"}),a=pc()?.dashboard.projects.find(j=>j.project.name===s||j.project.id===s)?.project.name??null,r=Le({...Fm({client:ne}),enabled:!a}),l=a??r.data?.find(j=>j.name===s||j.id===s)?.name??null,i=gc(),c=fc(t.tab,yc(i)),[d,m]=o.useState(null),u=l!==null&&d===l,x=o.useCallback(()=>{l&&m(l)},[l]),{commandCenter:f,isLoading:p,overviewLoading:g,overviewError:y,isError:v,latestVisibilityRevision:C,competitorHistoryRevision:b,refetch:L}=vc(l,{overview:c==="overview"&&u}),k=!a&&r.isLoading||p;return!l&&!a&&r.isSuccess&&!p?e.jsx("div",{className:"page-container",children:e.jsxs(Ne,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(R,{asChild:!0,children:e.jsx(Ss,{to:"/",children:"Return to overview"})})]})}):!f&&(v||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),L()])},children:"Retry"})]}):!f||k?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(j=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},j))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(j=>e.jsx("div",{className:"skeleton-text-sm w-full"},j))})]})]}):e.jsx(ob,{model:f,refetch:L,latestVisibilityRevision:C,competitorHistoryRevision:b,overviewLoading:g,overviewError:y,overviewRequested:u,onRequestOverview:x,...t})}function nb({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=o.useRef(null),l=o.useRef(null),[i,c]=o.useState(null);o.useLayoutEffect(()=>{const u=r.current,x=l.current;if(!u||!x)return;const f=()=>{const g=u.getBoundingClientRect().width;if(!g)return;const y=Number.parseFloat(getComputedStyle(u).columnGap)||0,v=new Map([...x.querySelectorAll("[data-project-tab]")].map(j=>[j.dataset.projectTab,j.getBoundingClientRect().width])),C=j=>v.get(j)??0,b=j=>j.reduce((w,P)=>w+C(P),0)+Math.max(0,j.length-1)*y,L=[...t.map(j=>j.key),...s.length?["more"]:[],...n?[n.key]:[]];let k=t.map(j=>j.key),h=!1;if(b(L)>g){const j=t.find(q=>q.key===a),w=j?[j.key]:[];h=!!(n&&b([...w,"more",n.key])>g);const P=["more",...n&&!h?[n.key]:[]];for(const q of t)if(q.key!==j?.key){if(b([...w,q.key,...P])>g)break;w.push(q.key)}k=t.filter(q=>w.includes(q.key)).map(q=>q.key)}c(j=>j?.settingsInMore===h&&j.visibleKeys.join()===k.join()?j:{visibleKeys:k,settingsInMore:h})};if(f(),typeof ResizeObserver>"u")return window.addEventListener("resize",f),()=>window.removeEventListener("resize",f);const p=new ResizeObserver(f);return p.observe(u),p.observe(x),()=>p.disconnect()},[t,s,n,a]);const d=i?t.filter(u=>i.visibleKeys.includes(u.key)):t,m=[...t.filter(u=>!d.includes(u)),...s,...i?.settingsInMore&&n?[n]:[]];return e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",ref:r,children:[e.jsx("div",{className:"project-subnav-measure","aria-hidden":"true",children:e.jsxs("div",{className:"project-subnav-measure-row",ref:l,children:[[...t,...n?[n]:[]].map(u=>e.jsx("span",{className:"project-subnav-link","data-project-tab":u.key,children:u.label},u.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx(Jn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.map(u=>e.jsx(Ss,{to:u.href,search:x=>({...x,onboarding:void 0}),className:`project-subnav-link ${u.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":u.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:u.label})},u.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(ab,{items:m,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(Ss,{to:n.href,search:u=>({...u,onboarding:void 0}),className:`project-subnav-link ${a==="settings"?"project-subnav-link-active":""}`,"aria-current":a==="settings"?"page":void 0,children:n.label})]})]})}function ab({items:t,activeTab:s}){const[n,a]=o.useState(!1),r=o.useRef(null),l=o.useRef(null),i=o.useRef("first"),c=o.useId(),d=t.map(u=>u.key).join();if(o.useEffect(()=>{a(!1)},[d]),o.useEffect(()=>{if(!n)return;const u=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?u?.[u.length-1]:u?.[0])?.focus()},[n]),o.useEffect(()=>{if(!n)return;const u=f=>{r.current&&!r.current.contains(f.target)&&a(!1)},x=f=>{f.key==="Escape"&&(a(!1),l.current?.focus())};return document.addEventListener("pointerdown",u),document.addEventListener("keydown",x),()=>{document.removeEventListener("pointerdown",u),document.removeEventListener("keydown",x)}},[n]),t.length===0)return null;const m=t.some(u=>u.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:l,className:`project-subnav-link project-subnav-more-trigger ${m?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?c:void 0,onClick:()=>{i.current="first",a(u=>!u)},onKeyDown:u=>{u.key!=="ArrowDown"&&u.key!=="ArrowUp"||(u.preventDefault(),i.current=u.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(Jn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:c,"aria-label":"More project sections",onKeyDown:u=>{const x=[...u.currentTarget.querySelectorAll('[role="menuitem"]')],f=x.indexOf(document.activeElement),p=u.key==="Home"?0:u.key==="End"?x.length-1:u.key==="ArrowDown"?(f+1)%x.length:u.key==="ArrowUp"?(f-1+x.length)%x.length:null;p!==null&&(u.preventDefault(),x[p]?.focus())},onBlur:u=>{r.current?.contains(u.relatedTarget)||a(!1)},children:t.map(u=>e.jsx(Ss,{to:u.href,search:x=>({...x,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${u.key===s?"project-subnav-menu-item-active":""}`,"aria-current":u.key===s?"page":void 0,onClick:()=>a(!1),children:u.label},u.key))}):null]})}const rb=20,ib=5;function ob({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:l,overviewError:i,overviewRequested:c,onRequestOverview:d}){const m=Ad(),u=xs(),{account:x,canWrite:f,isAdmin:p}=Hs(),[g,y]=o.useState(null),v=o.useRef(null),C=pc(),b=s.project.name,L=C?.dashboard.projects.some(I=>I.project.name===b)??!1,k=Rd({strict:!1}),h=Vm(k),j=xx(h),w=Le({...zm({client:ne,path:{name:b}}),enabled:!re()&&!!b&&(f||t==="portfolio"||t==="overview"||t==="settings"||j),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),P=C?C.dashboard.settings.providerStatuses.filter(I=>I.state==="ready").map(I=>vo(I.name)):void 0,q=w.data?.answerVisibilityProviderReady,S=P,V=s.project.providers.map(vo),F=S?.some(I=>V.length===0||V.includes(I))===!0,D=V.length===0||V.includes(Qm),K=Le({...Hm({client:ne}),enabled:!re()&&f&&q===void 0&&D&&!F,staleTime:6e4,retry:!1}),H=D?K.isSuccess?typeof K.data.browserVersion=="string":K.isError?!1:void 0:!1,se=q??Wm({projectProviders:V,configuredApiProviders:S,cdpConfigured:H}),Q=o.useMemo(()=>yc(gc()),[]),M=fc(t,Q),J=o.useMemo(()=>s.competitors.map(I=>I.domain),[s.competitors]),E=o.useMemo(()=>Object.fromEntries(s.competitors.map(I=>[I.domain,I.aliases??[]])),[s.competitors]),W=o.useMemo(()=>Object.fromEntries(s.competitors.map(I=>[I.domain,I.autoAliases??[]])),[s.competitors]),T=o.useMemo(()=>Object.fromEntries(s.competitors.map(I=>[I.domain,[...I.aliases??[],...I.autoAliases??[]]])),[s.competitors]),[ee,_]=o.useState(!1),[ae,ie]=o.useState(!1),Re=Ym(),X=o.useCallback((I,je)=>{m({to:".",search:ye=>Jm(ye,I),replace:je?.replace===!0})},[m]),ue=k.queryWorkspace==="research"||M==="discovery"&&k.queryWorkspace===void 0?"research":"tracked",ve=kc(ue,Cc(x?.role,x?.role==="viewer"?uc():null)),Z=Le({...qi({client:ne,path:{name:b}}),enabled:!re()&&(M==="queries"||M==="discovery")&&ve==="tracked"}),he=k.manageQueries===!0,G=o.useCallback(()=>{m({to:".",replace:!0,search:I=>({...I,siteHealthRunId:void 0})})},[m]),[me,De]=o.useState(he),[ke,oe]=o.useState(""),[pe,we]=o.useState(!1),[Ke,Me]=o.useState(null),[O,U]=o.useState("30d"),[B,Te]=o.useState(void 0),[He,Be]=o.useState(""),[Ze,xe]=o.useState(!1),[jt,_e]=o.useState(null),[et,zt]=o.useState(!1),rt=Xm(k),[tt,pt]=o.useState(void 0),[Nt,_t]=o.useState(void 0),Ve=o.useCallback(I=>{pt(I.search),I.sort&&_t(I.sort),m({to:".",search:je=>({...je,...Zm(I)}),replace:!1})},[m]),[A,$e]=o.useState(!1),Pe=s?.project.displayName||s?.project.name||b,ze=eh(),wt=Le({...bo({client:ne,path:{name:b}}),enabled:M==="portfolio"&&!!b,staleTime:0,refetchOnMount:"always"}),it=Le({...th({client:ne,path:{name:b}}),enabled:!re()&&!!b&&(f||is()||M==="portfolio"||M==="overview"||M==="settings"),staleTime:0,refetchOnMount:"always"}),Fe=it.data?.active??null,te=it.data!==void 0,Ue=new Set(Fe&&Number(Fe.plan.schemaVersion)===2?Fe.plan.groups?.map(I=>I.stableKey)??[]:[]),Ce={...rt.scope==="group"&&!!rt.groupKey&&te&&!Ue.has(rt.groupKey)?{scope:"all",queryClass:rt.queryClass}:rt,...tt?{search:tt}:{}},gt=Fe===null?null:Number(Fe.plan.schemaVersion),Qt=Fe?.revision??0,Kt=te?`${b}:${Qt}`:null,Zt=o.useRef(null);o.useEffect(()=>{const I=Zt.current;Kt!==null&&(Zt.current=Kt),sh(I,Kt)&&(Ve({scope:"all",queryClass:"all"}),$e(!1))},[Kt,Ve]);const It={client:ne,path:{name:b},query:{scope:Ce.scope,...Ce.groupKey?{groupKey:Ce.groupKey}:{},queryClass:Ce.queryClass,...Ce.search?{search:Ce.search}:{},...Nt?{sort:Nt}:{},limit:50}},vt=Ql({...nh(It),enabled:!1,initialPageParam:It,getNextPageParam:(I,je)=>{if(!I.properties.nextCursor)return;const ye=je[0]?.measurement.displayedRunId;return{path:It.path,query:{...It.query,cursor:I.properties.nextCursor,...ye?{runId:ye}:{}}}},placeholderData:Ai,staleTime:0,refetchOnMount:"always"}),ps=vt.data?.pages[0]?.measurement.displayedRunId,dt=Le({...ah({client:ne,path:{name:b},query:{revision:Qt,...ps?{runId:ps}:{}}}),enabled:M==="overview"&&!!b&&Fe!==null&&gt===1,staleTime:0,refetchOnMount:"always"}),gs=it.data!==void 0,Fs=wt.data!==void 0,St=it.isPending&&!gs,Gs=it.isError&&!gs,Lt=wt.isPending&&!Fs,fs=wt.isError&&!Fs,es=dt.data!==void 0,ts=Tv({activePlanSchemaVersion:w.data?.activeSchemaVersion??gt,hasDraft:w.data?.draft!==null&&w.data?.draft!==void 0}),xt=ts.surface==="simple-overview",Ht=is()&&Fe?.plan.schemaVersion===2?Lv(Fe.plan):null,ss=w.data===void 0&&it.data===void 0&&(it.isLoading||w.isLoading);o.useEffect(()=>{M==="overview"&&xt&&!ss&&d()},[ss,xt,d,M]);const ns=px({tab:M,surface:ss?"unresolved":ts.surface,embedded:re(),scoped:j,queryWorkspace:ve,tracking:Z.isError?{state:"error"}:Z.data?{state:"ready",mode:Z.data.mode,scopeUnavailable:Ac(Z.data,h)}:{state:"pending"}}),$t=Qc(b,h,{enabled:ns.kind==="report-picker"}),ys=M==="overview"&&xt&&!ss,ot=vc(b,{evidence:ys}),At=ot.commandCenter?.visibilityEvidence??s.visibilityEvidence,vs=o.useMemo(()=>{const I=new Map(At.map(ye=>[Wn(ye.query),ye.queryClass??null])),je=rh(ih(s.project));return ye=>{const yt=I.get(Wn(ye));return yt!==void 0?yt:je?.classify(ye)??null}},[At,s.project]),z=o.useMemo(()=>[...new Set([...At.map(I=>I.query),...s.movementComparison.addedQueries,...s.movementComparison.removedQueries])],[At,s.movementComparison]),le=o.useMemo(()=>s.visibilitySweeps.map(I=>I.createdAt),[s.visibilitySweeps]),Ae=f&&!re()&&!Yt()&&M!=="overview",ce=Le({...bo({client:ne,path:{name:b}}),enabled:Ae,staleTime:Li,refetchOnWindowFocus:"always"}),ge=gt===2&&h.measurementScope==="group"?h.measurementScopeKey:void 0,Ge=gt===2&&h.measurementScope==="project",mt=o.useMemo(()=>{if(!(Fe?.plan.schemaVersion!==2||!ge))return Fe.plan.groups.find(I=>I.stableKey===ge)},[Fe,ge]),Rt={client:ne,path:{name:b},query:{window:O,queryClass:gt===2&&h.queryClass!=="unknown"?h.queryClass:"non-brand",...ge?{groupKey:ge}:{},...Ge?{scope:"all-markets"}:{}}},bs=M==="overview"&&!h.marketKey&&!!b&&(xt||te)&&!ss&&(xt||(h.measurementScope==="project"||gt===2&&h.measurementScope==="group")&&h.queryClass!=="unknown"&&(gt===2||h.queryClass!=="branded")),[$,Se]=o.useState(null);o.useEffect(()=>{bs||Se(null)},[bs]),o.useEffect(()=>{Se(null)},[b]);const lt=$===b,Pt=bs&&lt,qt=Le({...oh(Rt),enabled:Pt,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});lh(b,JSON.stringify([r,s.competitors.map(I=>`${I.domain}=${[...I.aliases??[],...I.autoAliases??[]].join("|")}`).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Qt,w.data?.draft?.etag??null]),Pt);const Qe=qt.isError?qt.data===void 0?"Could not load competitors over time. Your pinned competitors remain available.":"Could not refresh competitors over time. Showing the last available data.":void 0,ft=o.useMemo(()=>s.competitors.map(I=>({domain:I.domain,label:I.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:I.citationCount,answeredResults:I.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),Ws=o.useMemo(()=>{if(Fe?.plan.schemaVersion!==2)return ft;const I=ge?mt?.competitors??[]:Fe.plan.groups.flatMap(ye=>ye.competitors),je=new Map;for(const ye of I){const yt=ye.domain.trim().toLowerCase();!yt||je.has(yt)||je.set(yt,{domain:ye.domain,label:ye.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const ye of ft){const yt=ye.domain.trim().toLowerCase();!yt||je.has(yt)||je.set(yt,ye)}return[...je.values()]},[Fe,ge,ft,mt]),$a=gt===2?Ws:ft,os=Gt({...ch({client:ne}),meta:{skipGlobalErrorToast:!0}}),qa=w.data!==void 0?"success":w.isError?"error":"pending",Ft=o.useMemo(()=>{const I=vt.data?.pages;return I?!Uh(I):!1},[vt.data]),as=o.useMemo(()=>{const I=vt.data?.pages,je=I?.[0],ye=I?.at(-1);if(!(!je||!ye||Ft))return{...je,properties:{...je.properties,items:I.flatMap(yt=>yt.properties.items),nextCursor:ye.properties.nextCursor}}},[Ft,vt.data]),Tn=o.useMemo(()=>{if(Fe)return Fe.plan.schemaVersion===1?dt.data?Gv(Fe,dt.data):void 0:as?Bh({overview:as,activePlan:Fe,sort:Nt,report:dt.data,reportState:as.measurement.displayedRunId===void 0?"ready":dt.isFetching&&dt.data===void 0?"loading":dt.isError&&dt.data===void 0?"error":dt.data?"ready":"loading"}):void 0},[Fe,dt.data,dt.isError,dt.isFetching,as]),Ma=gt===2?Ft?"error":vt.isPending?"loading":vt.isError&&Tn===void 0?"error":"ready":dt.isPending&&!es?"loading":dt.isError&&!es?"error":"ready",Ys=(s?.recentRuns??[]).some(I=>I.kind===Qs["answer-visibility"]&&(I.status===Es.running||I.status===Es.queued)),js=Gl(b,!re()&&!Yt(),"manual").data,_s=Gl(b,!re(),"scheduled").data,Ln=js&&_s&&JSON.stringify(js)!==JSON.stringify(_s),mn=js?.refused===!0,hn=js&&!js.refused?Object.keys(js.providers):[],xn=s.queryCounts.total>0,pn=o.useMemo(()=>(s?.project.locations??[]).map(I=>I.label),[s?.project.locations]),$n=o.useMemo(()=>new Set(At.map(I=>I.location??"")),[At]),Ea=$n.has(""),sa=o.useMemo(()=>[...new Set(At.map(I=>I.query))].sort((I,je)=>I.localeCompare(je)),[At]),Cs=sa.length>0||s.queryCounts.total>0||(ce.data?.length??0)>0||Fe!==null,vr=f&&!Cs&&(it.data===void 0&&it.isPending||ce.isLoading||ys&&ot.evidenceLoading),Js=f&&(w.isError&&!w.isFetching||Ae&&ce.isError&&!ce.isFetching),gn=f&&!Js&&(vr||se===void 0||w.isFetching),qn=!gn&&!Js&&Cs&&se===!0,fn=f&&!gn&&!qn,yn=!re()&&M==="overview"&&fn&&!Cs,Mn=Le({...dh({client:ne,path:{name:b},query:{limit:rb}}),enabled:yn&&!!b,retry:!1}),na=Mn.isSuccess&&Mn.data.scans.some(I=>I.status==="completed"||I.status==="partial"),br=yn&&Mn.isSuccess&&!na,jr=yn&&na,vn=Le({...xc({client:ne,path:{name:b}}),enabled:!re()&&!Yt()&&!!b,retry:!1}).data?.find(I=>I.kind===Qs["answer-visibility"]),N=vn?.enabled&&vn.nextRunAt?uh(vn.nextRunAt,vn.timezone):null,Y=N?`Next AI sweep ${N}`:null,de=o.useMemo(()=>{const I=[...$n].filter(Boolean);return I.length>1?I:pn},[$n,pn]);o.useEffect(()=>{if(!ys||B===void 0||B===""||!b){_e(null),zt(!1);return}zt(!0),mh(b,B,20).then(I=>{_e(I),zt(!1)}).catch(()=>{_e(null),zt(!1)})},[B,b,ys]);const be=o.useMemo(()=>{if(!jt)return null;const I=new Map;for(const je of jt){for(const[ye,yt]of Object.entries(je.providerRuns??{}))I.set(`${je.query}::${ye}`,yt.map(Rs=>({runId:Rs.runId,citationState:Rs.citationState,createdAt:Rs.createdAt,answerMentioned:Rs.answerMentioned,visibilityState:Rs.visibilityState,visibilityTransition:Rs.visibilityTransition,mentionState:Rs.mentionState,mentionTransition:Rs.mentionTransition})));(!je.providerRuns||Object.keys(je.providerRuns).length===0)&&I.set(`${je.query}::`,je.runs.map(ye=>({runId:ye.runId,citationState:ye.citationState,createdAt:ye.createdAt,answerMentioned:ye.answerMentioned,visibilityState:ye.visibilityState,visibilityTransition:ye.visibilityTransition,mentionState:ye.mentionState,mentionTransition:ye.mentionTransition})))}return I},[jt]),nt=o.useMemo(()=>{const I=B!==void 0?At.filter(je=>B===""?!je.location:je.location===B):At;return be?I.map(je=>{const ye=be.get(`${je.query}::${je.provider}`)??be.get(`${je.query}::`);return ye?{...je,runHistory:ye}:je}):I},[At,B,be]);async function st(){if(!(g!==b||!f||re()||Yt()||ze.isPending||Ys||mn||!qn))try{await ze.mutateAsync({projectName:b,projectLabel:Pe,sourceAction:"project-run"}),y(null)}catch{}}function ht(){m({to:"/setup",search:{experience:"legacy",setupProject:b}})}function Mt(){m({to:"/projects/$projectName/technical-aeo",params:{projectName:b}})}async function ut(){ie(!0);try{await Sh(b),Ee({title:"Project deleted",detail:`${Pe} was removed.`,tone:"positive",dedupeKey:`project:delete:${b}`,dedupeMode:"drop"}),await m({to:"/"})}catch(I){console.error("Failed to delete project:",I)}finally{ie(!1)}}async function Ie(){const I=ke.split(`
7
- `).map(je=>je.trim()).filter(Boolean);if(I.length!==0){we(!0);try{await fh(b,I),oe("")}finally{we(!1)}}}async function ks(I){Me(I);try{await gh(b,[I])}catch(je){Ee({title:"Could not remove query",detail:je instanceof Error?je.message:`Failed to remove "${I}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{Me(null)}}async function Xs(I){const je=I.trim();if(!je)return!1;try{return await xh(b,[je]),!0}catch(ye){return Ee({title:"Could not add competitor",detail:ye instanceof Error?ye.message:`Failed to add ${je}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function En(I){const je=s.competitors.find(ye=>ye.domain===I);if(!je)return Ee({title:"Could not remove competitor",detail:`Could not find ${I} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await ph(b,je.id),!0}catch(ye){return Ee({title:"Could not remove competitor",detail:ye instanceof Error?ye.message:`Failed to remove ${je.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function Ns(I){const je=I.trim();if(!je||!ge||gt!==2||!f||re()||os.isPending)return!1;try{const ye=await os.mutateAsync({client:ne,path:{name:b},headers:{"Idempotency-Key":Jv()},body:{expectedActiveRevision:Qt,groupKey:ge,domain:je}});return Promise.allSettled([w.refetch()]),Ee({title:ye.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${je} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${ge}:${je}`,dedupeMode:"replace"}),!0}catch(ye){return Ee({title:"Could not add market competitor",detail:ye instanceof Error?ye.message:`Failed to add ${je} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function aa(I,je){const ye=await Nh(I,je);return u.setQueryData(wh({client:ne,path:{name:I}}),ye),Xv(u,ye),ye}const As=`/projects/${encodeURIComponent(s.project.name)}`,yd=[{key:"overview",label:"AI Visibility",href:As},{key:"search-console",label:"Search Engines",href:`${As}/search-console`},{key:"activity",label:"Activity",href:`${As}/activity`},{key:"technical-aeo",label:"Site Health",href:`${As}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${As}/conversions`},{key:"local",label:"Local Presence",href:`${As}/local`},{key:"queries",label:"Queries",href:`${As}/queries`},{key:"backlinks",label:"Backlinks",href:`${As}/backlinks`}],vd=[{key:"history",label:"Change History",href:`${As}/history`}],bd=yd.filter(I=>Pr(I.key,Q)),jd=vd.filter(I=>Pr(I.key,Q)),Nd=Pr("settings",Q)?{key:"settings",label:"Settings",href:`${As}/settings`}:null;function wd(I){const je=xt?I:e.jsx(Bg,{projectName:b,selection:h,showUnmeasuredFallback:!Fe&&!xn&&h.measurementScope==="project"&&h.queryClass==="all"&&!h.provider&&!h.model&&!h.location&&!h.from&&!h.to&&!h.revision&&!h.measurementRunId&&!h.queryKey&&!h.marketKey,onSelectionChange:X,onManageQueries:re()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:b},search:yt=>({...yt,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:re()?void 0:({id:yt,label:Rs})=>e.jsx(Ss,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:b,targetKey:yt},search:yh,"aria-label":`Property details for ${Rs}`,className:"inline-flex min-h-11 items-center text-sm text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:"Property details"}),trackingChangedAt:re()||Yt()?void 0:Fe?.createdAt,nextSweepDate:re()||Yt()||Ys?void 0:N??void 0,fallback:I});if(re())return je;let ye=vh(h,xt?"simple":"advanced",typeof k.sentimentEvaluationDefinitionId=="string"?k.sentimentEvaluationDefinitionId:void 0);return xt&&(ye.location=B===""?"none":B,ye=bh(ye,nt,He)),e.jsx(jh,{hasSourceEvidence:!xt||!!(ye.runId||ye.runIds?.length),evidenceReady:!xt||!(ot.isLoading||ot.evidenceLoading||ot.evidenceError),waitForResolvedRun:!xt,projectName:b,runOptions:s.visibilitySweeps.slice(0,ib).map(yt=>({id:yt.id,label:Xt(yt.finishedAt??yt.createdAt)})),selection:ye,children:je})}function Sd(){switch(ns.kind){case"report-picker":{if($t.error)return lc(cc($t.error))?e.jsx("p",{className:"text-[13px] text-secondary",children:Ga.savedScopeUnavailable}):null;const I=$t.data;if(!I)return e.jsx("div",{className:"skeleton-text h-11 w-56",role:"status","aria-label":"Loading measurement scope"});if(I.selection.availability.state!=="available"||I.scopeOptions.length<=1)return null;const je=li(I.scopeOptions,h)??I.selection.scope;return e.jsx(No,{labelVisibility:"sr-only",options:I.scopeOptions,selected:je,marketKey:h.marketKey,onSelect:(ye,yt)=>X({measurementScope:ye.kind,measurementScopeKey:ye.kind==="project"?void 0:ye.id,measurementMarketKey:yt})})}case"tracking-picker":{const I=Z.data?.scopeOptions??[],je=li(I,h);return je?e.jsx(No,{labelVisibility:"sr-only",options:I,selected:je,onSelect:ye=>X({measurementScope:ye.kind,measurementScopeKey:ye.kind==="project"?void 0:ye.id})}):null}case"scope-unavailable":return e.jsx("p",{className:"text-[13px] text-secondary",children:Ga.savedScopeUnavailable});case"project-wide":return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[13px] text-secondary",children:Ga.projectWide}),e.jsx(Oe,{text:Ga.projectWideHelp})]});case"none":return null}}const ao=M==="overview"&&!xt&&(h.from||h.to)?`${h.from?.slice(0,10)??"First measurement"} to ${h.to?.slice(0,10)??"Latest measurement"}`:null,ro=Sd(),io=bs?e.jsx(Tx,{window:O,landscape:qt.data,pinnedFallback:$a,competitorAliases:E,competitorAutoAliases:W,canWrite:f,isEmbed:re(),onWindowChange:U,onPin:ge&&f&&!re()?Ns:!Ge&&f&&!re()?Xs:void 0,onUnpin:ge||Ge||!f||re()?void 0:En,onAddCompetitor:ge&&f&&!re()?Ns:!Ge&&f&&!re()?Xs:void 0,error:Qe,onRetry:Pt?()=>{qt.refetch()}:void 0,isLoading:Pt&&qt.isPending&&qt.data===void 0,scopeLabel:ge?`${mt?.label??ge} group`:Ge?"All markets":"Project-wide",advancedPortfolio:!xt}):null,Nr=re()?null:e.jsx(e.Fragment,{children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>De(!me),children:me?"Done":"Manage queries"})}),oo=!re()&&me?e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[sa.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto rounded border border-default",children:sa.map(I=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:I,children:I}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs 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 ${I}`,title:`Stop tracking "${I}"`,disabled:Ke!==null,onClick:()=>{ks(I)},children:Ke===I?"Removing…":"Remove"})]},I))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:ke,onChange:I=>oe(I.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[ke.split(`
8
- `).filter(I=>I.trim()).length," to add"]}),e.jsx(Ye,{type:"button",size:"sm",disabled:!ke.trim()||pe,onClick:Je(Ie),children:pe?"Adding...":"Add queries"})]})]}):null;return e.jsxs("div",{className:"page-container",children:[re()?e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]})]}),e.jsx("div",{className:Yt()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:ao!==null?e.jsx("p",{className:"text-sm text-muted",children:ao}):null})]}):e.jsxs("div",{className:"project-context-row",children:[e.jsx("h1",{className:"project-context-title md:sr-only",children:s.project.displayName||s.project.name}),ro!==null?e.jsx("div",{className:"project-context-scope",children:ro}):null,s.project.canonicalDomain?e.jsx("span",{className:"project-context-domain",children:s.project.canonicalDomain}):null,Ht!==null?e.jsxs("span",{className:"project-mode-tag",children:[e.jsx("span",{className:"project-mode-tag-label",children:"Advanced"}),e.jsx("span",{className:"project-mode-tag-detail",children:Ht})]}):null,e.jsx("div",{className:"project-context-actions","data-project-actions":!0,children:Yt()?e.jsx(hh,{projectName:b,running:Ys,portfolio:!xt}):e.jsxs(e.Fragment,{children:[Y?e.jsx("p",{className:"text-sm text-secondary",children:Y}):null,br?e.jsx(Ye,{type:"button",onClick:Mt,children:"Map site"}):jr?e.jsx(Ye,{type:"button",onClick:Mt,children:"View Page Health"}):null,e.jsx(Ye,{type:"button",variant:"outline",disabled:ze.isPending||Ys||gn||mn&&!Js&&!fn,onClick:Js?()=>{Promise.all([w.refetch(),...Ae?[ce.refetch()]:[]])}:fn?ht:I=>{v.current=I.currentTarget,y(b)},children:ze.isPending?"Starting…":Ys?"AI sweep running…":gn?"Checking AI readiness…":Js?"Retry AI readiness":fn?"Set up AI Visibility":mn?"AI sweeps on hold":"Run AI sweep"})]})})]}),!re()&&!Yt()&&e.jsx(Yv,{open:g===b,projectLabel:Pe,onOpenChange:I=>y(I?b:null),onConfirm:Je(st),onClosed:()=>v.current?.focus(),disabled:ze.isPending||Ys||mn||!qn,leftOut:hn}),e.jsx(nb,{items:bd,overflowItems:jd,settingsItem:Nd,activeTab:M}),M==="portfolio"&&!re()?e.jsx(uv,{projectName:b,canEdit:f,queries:wt.data??[],isQueryLoading:Lt,isQueryError:fs,onRetryQueries:()=>{wt.refetch()},publishedPlan:Fe,onCreateQueries:async I=>(await Re.mutateAsync({projectName:b,queries:[...I]}),(await wt.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{m({to:"/projects/$projectName",params:{projectName:b},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([w.refetch(),it.refetch()]).finally(()=>{m({to:"/projects/$projectName",params:{projectName:b}})})}},b):M==="overview"?e.jsxs(e.Fragment,{children:[re()?null:e.jsxs(e.Fragment,{children:[_s?e.jsx(Kl,{admission:_s,canFix:f&&p,selection:Ln||!js?"scheduled":void 0}):null,js&&(Ln||!_s)?e.jsx(Kl,{admission:js,canFix:f&&p,selection:"manual"}):null]}),ss||xt&&!L&&(!c||l)?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):xt&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[Gs?e.jsxs("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-sm text-negative",children:[e.jsx("span",{children:"Could not check the advanced measurement setup. Existing project-wide results remain available."}),e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:()=>{it.refetch()},children:"Retry setup check"})]}):null,wd(e.jsx($v,{mode:ts,canEdit:f&&!re()&&!St&&!Gs,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(lf,{projectName:s.project.name,competitorDomains:J,competitorAliases:T,analyticsRevision:a,queryTexts:z,classifyQuery:vs,sweepTimes:le})}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsx("h2",{className:"av-card-title",children:"Where competitors are winning"}),xn?e.jsx("p",{className:"av-card-meta",children:"Latest sweep"}):null]}),xn?e.jsxs("div",{className:"competitive-summary",children:[e.jsx(bx,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:J},s.project.name),e.jsxs("div",{className:"competitive-gaps",children:[e.jsx("p",{className:"competitive-gaps-scope",children:"All queries"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(zl,{label:"Mention gaps",summary:s.mentionGaps,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-secondary",children:[" / ",s.queryCounts.total]}),e.jsx("span",{className:"sr-only",children:" queries, all queries"})]}),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."}),e.jsx(zl,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-secondary",children:[" / ",s.queryCounts.total]}),e.jsx("span",{className:"sr-only",children:" queries, all queries"})]}),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."})]})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Competitive mention and citation gaps appear after the first AI Visibility sweep."})]}),e.jsx("div",{className:"page-section-divider",children:e.jsx(vg,{projectName:s.project.name,classify:vs,hasCompetitors:J.length>0,providerScores:s.providerScores})}),e.jsxs(tb,{id:"evidence-section",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${B===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":B===void 0,onClick:()=>{Te(void 0)},children:"All locations"}),s.project.locations.map(I=>e.jsx("button",{className:`filter-chip ${B===I.label?"filter-chip-active":""}`,type:"button","aria-pressed":B===I.label,onClick:()=>{Te(I.label),xe(!1)},children:I.label},I.label)),Ea&&e.jsx("button",{className:`filter-chip ${B===""?"filter-chip-active":""}`,type:"button","aria-pressed":B==="",onClick:()=>{Te(""),xe(!1)},children:"No location"}),de.length>1&&B===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${Ze?"filter-chip-active":""}`,type:"button","aria-pressed":Ze,onClick:()=>xe(I=>!I),title:"Side-by-side location comparison",children:"Compare"})]}),ot.evidenceLoading||ot.evidenceError?e.jsxs(e.Fragment,{children:[Nr&&e.jsx(Oc,{actions:Nr}),oo,ot.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{ot.refetch()},children:"Retry"})]})]}):e.jsx(dp,{evidence:nt,compareLocations:Ze,providerSelection:He,onProviderSelectionChange:Be,addedQueries:s.movementComparison.addedQueries,actions:Nr,actionPanel:oo})]}),!re()&&e.jsx("div",{className:"page-section-divider",children:e.jsx(jg,{runs:s.recentRuns,collapsed:!0})})]}),report:Tn,reportState:Ma,onOpenSetup:re()?void 0:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:b}})},onRetryReport:()=>{gt===2?Promise.all([vt.refetch(),dt.refetch()]):dt.refetch()},onViewChange:I=>{Ve({scope:I.scope,...I.groupKey?{groupKey:I.groupKey}:{},queryClass:I.queryClass,...I.search?.trim()?{search:I.search.trim()}:{}})},onLoadMore:I=>{I===as?.properties.nextCursor&&vt.fetchNextPage()},onPropertyExpand:()=>{A&&dt.isError&&dt.refetch(),$e(!0)},onRetryEvidence:()=>{dt.refetch()},isViewLoading:vt.isPlaceholderData,isLoadingMore:vt.isFetchingNextPage,isLoadMoreError:vt.isFetchNextPageError,viewSearch:Ce.search??""},`${b}:${Qt}`)),!xt&&h.measurementScope==="project"?e.jsxs("details",{className:"visibility-disclosure",onToggle:I=>{I.currentTarget.open&&d()},children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Project signals"})}),!c||l?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading project signals…"}):i?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load project signals."}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(sb,{insights:s.insights,suggestedQueries:s.suggestedQueries,siteDomain:s.project.canonicalDomain||void 0,onManageQueries:re()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:b},search:I=>({...I,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},b):null,io!==null?e.jsxs("details",{className:`visibility-disclosure${xt?" page-section-divider":""}`,open:lt,onToggle:I=>Se(I.currentTarget.open?b:null),children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Competitor history"})}),e.jsx("div",{className:"visibility-disclosure-panel",children:io})]}):null]})]}):M==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(_v,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(I,je)=>{await aa(I,je)}}),e.jsx(Uv,{project:s.project,onSave:async I=>{await aa(s.project.name,I)}}),e.jsx(Vv,{project:s.project,onSave:async I=>{await aa(s.project.name,{siteAuditMaxPages:I})}},s.project.id),f&&!re()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),qa==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):qa==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:()=>{w.refetch()},children:"Retry"})]}):e.jsx(R,{type:"button",variant:"outline",onClick:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:b}})},children:fd(ts.setupAction)})]}):null,e.jsx(Qv,{projectName:s.project.name}),e.jsx(Wv,{projectName:s.project.name}),f&&!re()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),ee?e.jsxs(Ne,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(R,{type:"button",variant:"destructive",disabled:ae,onClick:Je(ut),children:ae?"Deleting...":"Yes, delete project"}),e.jsx(R,{type:"button",variant:"outline",disabled:ae,onClick:()=>_(!1),children:"Cancel"})]})]}):e.jsxs(Ye,{type:"button",variant:"outline",onClick:()=>_(!0),children:[e.jsx(Sc,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):M==="queries"||M==="discovery"?e.jsx(vf,{projectName:b,queryWorkspace:ue,onQueryWorkspaceChange:I=>X({queryWorkspace:I,trackingQueryId:void 0}),researchMode:k.researchMode==="test"?"test":"find",onResearchModeChange:I=>X({researchMode:I}),selection:h,onSelectionChange:X,trackingQueryId:typeof k.trackingQueryId=="string"?k.trackingQueryId:void 0,onTrackingQueryIdChange:I=>X({trackingQueryId:I})}):M==="technical-aeo"?e.jsx(Fh,{projectName:s.project.name,projectId:s.project.id,initialRunId:k.siteHealthRunId,onReleaseInitialRun:G}):M==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Py,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(py,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):M==="history"?e.jsx(Vf,{projectName:s.project.name}):M==="activity"?e.jsx(Cp,{projectName:s.project.name}):M==="backlinks"?e.jsx(mg,{projectName:s.project.name}):M==="local"?e.jsx(Up,{projectName:s.project.name,projectId:s.project.id}):M==="search-console"?e.jsx(eb,{projectName:s.project.name}):null]})}export{jb as ProjectPage,nb as ProjectSubnav,Yv as ProjectSweepConfirmation,Xv as patchProjectDashboardCache};