@canonry/canonry 7.44.0 → 7.45.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.
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +10 -0
- package/assets/assets/{AuditHistoryPanel-CvANw3ds.js → AuditHistoryPanel-CZOskgSK.js} +1 -1
- package/assets/assets/{BacklinksPage-C6x9ELjk.js → BacklinksPage-CgyR9Ydh.js} +1 -1
- package/assets/assets/{HistoryPage-r36HX1cC.js → HistoryPage-luN-L4CJ.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-ComoCzR4.js → MeasurementPropertyPage-B0vFWHFx.js} +1 -1
- package/assets/assets/{ProjectPage-CIeU-buk.js → ProjectPage-BkLOWkz9.js} +1 -1
- package/assets/assets/{RunsPage-DI6eJATZ.js → RunsPage-CeW09PIZ.js} +1 -1
- package/assets/assets/{SettingsPage-Bw7GdXxs.js → SettingsPage-C4jww6eS.js} +1 -1
- package/assets/assets/{SiteHealthSection-C-JaNKpS.js → SiteHealthSection-DXxY03vO.js} +3 -3
- package/assets/assets/{TrafficPage-Cnsp276v.js → TrafficPage-DvUYZXne.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-CBIaJk7e.js → TrafficSourceDetailPage-DG-6Vn9Z.js} +1 -1
- package/assets/assets/{extract-error-message-C_Owa0n9.js → extract-error-message-1VWodBea.js} +1 -1
- package/assets/assets/{index-ZS9sSTMS.js → index-rBPSQ6B7.js} +3 -3
- package/assets/assets/{react-sigma_core.esm.min-ugyh-ooq.js → react-sigma_core.esm.min-Cm1_Mhdd.js} +1 -1
- package/assets/assets/{v2-overview-adapter-BLSrVQ7K.js → v2-overview-adapter-DSOkIdKV.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-GZ2KIONF.js → chunk-3MGCNSUL.js} +21 -0
- package/dist/{chunk-5LY7EG4U.js → chunk-3T3JQB2J.js} +2 -2
- package/dist/{chunk-G47XJVAS.js → chunk-6HUFI2G5.js} +80 -12
- package/dist/{chunk-MPWBFKGK.js → chunk-73YOKKHS.js} +1 -1
- package/dist/{chunk-QQYQDTFZ.js → chunk-A2RC2Y24.js} +246 -45
- package/dist/{chunk-JVBI6VBT.js → chunk-D42JVABX.js} +2 -2
- package/dist/{chunk-45Z5RJZW.js → chunk-H4YKQAY7.js} +3 -3
- package/dist/{chunk-3JVF3ULD.js → chunk-JAQNHQGR.js} +1 -1
- package/dist/{chunk-SW54HXSZ.js → chunk-K3AEOEB7.js} +3 -3
- package/dist/{chunk-EJRV7RBZ.js → chunk-TH7WZBUX.js} +11 -9
- package/dist/{cli-catalog-PNJEQV5H.js → cli-catalog-6ABJHAAK.js} +3 -3
- package/dist/cli-commands-OLFYNI6A.js +15 -0
- package/dist/cli.js +10 -10
- package/dist/{demo-server-WRHR25HF.js → demo-server-ZNK2UDRJ.js} +4 -4
- package/dist/index.js +6 -6
- package/dist/{intelligence-service-QXXRUB2G.js → intelligence-service-MDXUBZPJ.js} +2 -2
- package/dist/mcp.js +4 -4
- package/package.json +8 -8
- package/dist/cli-commands-4UT2CRXX.js +0 -15
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as e,r as o,t as Td,u as $e,L as ks,h as bs,o as Kt,B as Ti,C as Jl,D as Ld,k as $d,l as qd}from"./vendor-tanstack-ZXXkndVj.js";import{T as ge,t as Md,a as Ed,s as Li,M as va,I as Fe,f as Je,R as Zn,m as Dd,B as A,b as Xl,c as Od,d as Fd,e as Gd,S as Zl,g as ec,u as $i,h as _d,n as Hn,C as Kd,i as tc,j as sc,k as qi,l as Ud,o as Bd,p as Vd,q as sn,r as nc,v as ac,w as je,x as or,y as ne,z as ie,A as os,D as Dt,E as Ye,F as zd,G as Qd,H as Hd,J as rc,K as Wd,L as Yd,N as Jd,O as kr,P as mo,Q as Xd,U as Zd,V as eu,W as tu,X as Ys,Y as Cn,Z as su,_ as nu,$ as En,a0 as Xt,a1 as au,a2 as ru,a3 as ho,a4 as ic,a5 as Bt,a6 as Mi,a7 as iu,a8 as ou,a9 as lu,aa as cu,ab as xo,ac as De,ad as du,ae as uu,af as Ar,ag as mu,ah as hu,ai as xu,aj as pu,ak as gu,al as fu,am as yu,an as bu,ao as oc,ap as Ds,aq as Cs,ar as vu,as as ju,at as Nu,au as wu,av as Su,aw as Cu,ax as ku,ay as Au,az as lc,aA as Ru,aB as cc,aC as ur,aD as Pu,aE as He,aF as Iu,aG as Tu,aH as Lu,aI as mr,aJ as $u,aK as qu,aL as Mu,aM as ii,aN as Eu,aO as Du,aP as Ou,aQ as dc,aR as oi,aS as Fu,aT as Ei,aU as Gu,aV as Wn,aW as Jt,aX as Ra,aY as uc,aZ as lr,a_ as li,a$ as _u,b0 as po,b1 as mc,b2 as ja,b3 as Ku,b4 as hc,b5 as ci,b6 as Uu,b7 as xc,b8 as yn,b9 as Di,ba as Rr,bb as Bu,bc as Vu,bd as zu,be as Qu,bf as Hu,bg as ga,bh as go,bi as Ga,bj as Pr,bk as Wu,bl as Yu,bm as fo,bn as Ir,bo as kn,bp as pc,bq as Oi,br as gc,bs as Ju,bt as Xu,bu as yo,bv as Zu,bw as em,bx as tm,by as sm,bz as nm,bA as am,bB as rm,bC as im,bD as om,bE as lm,bF as cm,bG as dm,bH as um,bI as mm,bJ as hm,bK as xm,bL as pm,bM as gm,bN as fm,bO as ym,bP as bm,bQ as vm,bR as jm,bS as Nm,bT as wm,bU as Sm,bV as Cm,bW as Ps,bX as km,bY as bo,bZ as Am,b_ as Rm,b$ as Pm,c0 as Im,c1 as Tm,c2 as fc,c3 as Lm,c4 as $m,c5 as vo,c6 as qm,c7 as $s,c8 as Mm,c9 as yc,ca as Tr,cb as Em,cc as Dm,cd as jo,ce as Om,cf as Fm,cg as Gm,ch as _m,ci as Km,cj as Um,ck as Bm,cl as bc,cm as Vm,cn as vc,co as jc,cp as Nc,cq as wc,cr as zm,cs as Qm,ct as Hm,cu as Wm,cv as Ym,cw as Jm,cx as Xm,cy as No,cz as Zm,cA as eh,cB as th,cC as sh,cD as nh,cE as ah,cF as rh,cG as ih,cH as wo,cI as oh,cJ as lh,cK as ch,cL as dh,cM as uh,cN as mh,cO as hh,cP as xh,cQ as ph,cR as gh,cS as fh,cT as yh,cU as Lr,cV as bh,cW as So,cX as vh,cY as jh,cZ as Nh,c_ as wh,c$ as Sh,d0 as Ch,d1 as kh,d2 as Ah,d3 as Rh,d4 as Ph,d5 as Ih,d6 as Th,d7 as Lh,d8 as Sc,d9 as $h,da as qh,db as Mh,dc as Eh,dd as Dh,de as Oh,df as _a,dg as Fh,dh as Gh,di as _h,dj as Co,dk as Kh}from"./index-ZS9sSTMS.js";import{u as rn,D as Hs,a as Es,b as Fi,M as cr,c as Vs,F as Uh,P as Cc,s as Bh,p as Vh,S as zh}from"./SiteHealthSection-C-JaNKpS.js";import{A as Gi,a as Qh,b as Hh,c as Wh,s as hs,i as bn,d as Yh,e as Jh,V as ko}from"./v2-overview-adapter-BLSrVQ7K.js";import{o as Ot,C as Na,f as An,a as fs,b as zt,c as It,d as is,e as ct,g as ys,h as ea,M as kc,i as Xh,j as Pa,p as Zh,k as di,l as ex,m as Ao}from"./ChartPrimitives-CZ4wVBJL.js";import{g as Ac,y as wa,U as tx,z as sx,L as nx,D as ax,l as rx,j as hr,I as ix,C as Yn,X as ox,e as lx,J as cx,P as dx,K as ux,N as Rc}from"./vendor-lucide-Y6jANGfG.js";import{u as mx,a as hx,b as xx,t as px,e as gx,c as Ct}from"./extract-error-message-C_Owa0n9.js";import{R as on,C as ln,a as Sa,X as cn,Y as dn,T as un,b as ui,L as xr,A as nn,d as Qs,e as fx}from"./vendor-recharts-D-cUuLZo.js";import{H as $r}from"./Hint-DICI5Jq9.js";import{A as yx}from"./AuditHistoryPanel-CvANw3ds.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const bx=1e6;function vx(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/bx);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Ka={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 Pc(t,s){return t!=="viewer"||s!==null}function Ic(t,s){return t==="research"&&!s?"tracked":t}function Tc(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 mi(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function jx(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function Nx(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 hi({state:t,label:s,className:n}){return e.jsx(ge,{tone:Ed(t),className:n,children:s??Md(t)})}const vn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Ro={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},wx={"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."},Sx="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Cx(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:Je(t.score,Zn.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 kx({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(Fe,{text:Sx})]}),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:Je(a.share)})]},a.label))})]})}function Ax({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",d=!i&&t.branded.snapshotsTotal>0,c=d?a:"non-brand",h=i?"pooled":c,u=c==="branded"?t.branded:t.breakdown,m=c==="branded"?t.breakdown:t.branded,f=Cx(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:m.snapshotsTotal>0}),g=Li(f.headline),y=h==="non-brand"?va[t.tone]:"text-secondary";function p(b){const C=vn.findIndex($=>$.value===c);let v=null;b.key==="ArrowRight"||b.key==="ArrowDown"?v=(C+1)%vn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?v=(C-1+vn.length)%vn.length:b.key==="Home"?v=0:b.key==="End"&&(v=vn.length-1),v!==null&&(b.preventDefault(),r(vn[v].value),b.currentTarget.querySelectorAll('[role="radio"]')[v]?.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(Fe,{text:wx[h]})]}),d?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:p,children:vn.map(b=>{const C=b.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":C,tabIndex:C?0:-1,onClick:()=>r(b.value),className:`segmented-option min-h-11 ${C?"segmented-option-active":""}`,children:b.label},b.value)})}):e.jsx("span",{className:"mention-share-class",children:Ro[h]})]}),f.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[g.figure,g.sign?e.jsx("span",{className:"text-faint",children:g.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:Ro[h]}),` · ${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(kx,{breakdown:u,projectLabel:s})]})}function Ia({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 fa({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(d){const c=t.findIndex(u=>u.value===s);let h=null;d.key==="ArrowRight"||d.key==="ArrowDown"?h=(c+1)%t.length:d.key==="ArrowLeft"||d.key==="ArrowUp"?h=(c-1+t.length)%t.length:d.key==="Home"?h=0:d.key==="End"&&(h=t.length-1),h!==null&&(d.preventDefault(),n(t[h].value),d.currentTarget.querySelectorAll('[role="radio"]')[h].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(d=>{const c=d.value===s,h=d.description?`${l}-${d.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":c,"aria-describedby":h,tabIndex:c?0:-1,onClick:()=>n(d.value),className:`segmented-option pointer-coarse:min-h-11 ${c?"segmented-option-active":""}`,children:d.label}),d.description?e.jsx("span",{id:h,className:"sr-only",children:d.description}):null]},d.value)})})}const Rx=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Px={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},Ix={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},Tx={"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."},Lx={"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"},Po="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.",xi=100;function $x(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function Lc(t){return t==="unavailable"?"Unavailable":"Not measured"}function pi(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 $c(t){const s=t.label.trim(),n=Od(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function qc({row:t,aliases:s=[],autoAliases:n=[]}){const a=$c(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:d},c)=>e.jsxs("span",{children:[c>0?", ":"",i,d?e.jsx("span",{className:"av-alias-auto",title:"Detected automatically from this project's stored answers",children:" (auto)"}):null]},`${d?"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 qx(t){const s=$c(t);return s?`${s} (${t.domain})`:t.domain}function Io(t,s){return s&&t>=xi?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function gi({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function d(){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(A,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{d()},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 Mx({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 Kn({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:Lc(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 To({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":Lc(s)});const{figure:a,sign:r}=Li(Je(t,Zn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Ex({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(qc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:pi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(Kn,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Kn,{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(Mx,{urls:l.sampleUrls}):null,r?e.jsx(gi,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function Dx({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,d]=o.useState(null);async function c(){const h=n.trim();if(!(!h||r)){l(!0),d(null);try{if(await t(h)===!1){d("Could not add competitor. Try again.");return}a("")}catch{d("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:h=>{h.preventDefault(),c()},"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:h=>a(h.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(A,{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 Ox({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},competitorAutoAliases:r={},canWrite:l,isEmbed:i,onWindowChange:d,onPin:c,onUnpin:h,onAddCompetitor:u,error:m,onRetry:f,isLoading:g=!1,scopeLabel:y,advancedPortfolio:p=!1}){const b=o.useId(),C=l&&!i,v=s?.pinned??n,$=s?.observed??[],R=s?.otherSources??[],x=s?.evidence,N=$x(s),w=s?.basis==="observed",P=w?$.filter(K=>K.shareOfVoice!==null):v,q=w?$.filter(K=>K.shareOfVoice===null):$,S=s?.filters.queryClass,G=s?.marketState?.draft?.pendingCompetitorDomains.length??0,X=s?.truncated===!0,T=x?.answeredResults??0,F=x?x.answeredResults+x.missingAnswerTextResults:0,ae=S==="non-brand"&&s?.project.shareOfVoice!=null?va[Dd(s.project.shareOfVoice)]:"text-primary",Q=K=>C?K.pinned?h?e.jsx(gi,{action:"unpin",domain:K.domain,mutation:h}):null:c?e.jsx(gi,{action:"pin",domain:K.domain,mutation:c}):null:null,B=P.some(K=>Q(K)!==null),D=[y,S?Ix[S]:null,Px[t],s?.basis?w?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),Y=[];if(s&&!w&&P.length===0&&Y.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&Y.push({key:"reason",text:`Mention share: ${Lx[s.reason]}`}),s&&q.length>0){const K=q.length;Y.push({key:"others",text:X&&K>=xi?`${xi} or more other competitors seen`:`${K} other ${Is(K,"competitor","competitors")} seen`})}G>0&&Y.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${G} ${Is(G,"competitor","competitors")}`});const E=[x&&x.missingAnswerTextResults>0?"Answer data incomplete":null,x&&x.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);E.length>0&&Y.push({key:"incomplete",text:E.join(" · "),className:va.caution});const W=[];if(s&&x){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:x.answeredResults})," ",Is(x.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:x.answeredResults})," ",Is(x.answeredResults,"answer","answers")]})),!s.reason&&N==="measured"&&s.project.shareOfVoice!==null&&W.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),P.map(se=>e.jsxs(Td.Fragment,{children:[", ",se.domain," ",e.jsx("strong",{children:se.mentionCount})]},se.domain))," ","of ",e.jsx("strong",{children:x.mentionCredits})," ",w?"brand mentions":"tracked-brand mentions"]})),W.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:x.sourceResults})]})),q.length===0&&W.push("Other competitors seen: none"),x.missingAnswerTextResults>0&&W.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:x.missingAnswerTextResults})," ",Is(x.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),x.incompleteSourceResults>0&&W.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:x.incompleteSourceResults})," ",Is(x.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const K=x.excludedProbeResults+x.excludedNonCompletedResults;K>0&&W.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:K})," ",Is(K,"answer","answers")," from spot checks or unfinished sweeps"]}))}const L=[...s?[{name:"You",row:s.project}]:[],...P.map(K=>({name:K.domain,row:K}))].filter(K=>K.row.sampleUrls.length>0);N==="measured"&&L.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:L.map(({name:K,row:se})=>e.jsxs("div",{children:[e.jsx("p",{children:K}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:se.sampleUrls.map(ce=>e.jsx("li",{className:"break-all",children:ce},ce))})]},se.domain))})]})),s&&q.length>0&&W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",Io(q.length,X)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Ex,{rows:q,state:N,named:T,cited:F,onPin:C?c:void 0})})]}));const ee=s?.observedNames??[];if(ee.length>0){const K=s?.observedNamesTotal??ee.length;W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",K>ee.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:ee.length})," of ",e.jsx("strong",{children:K})]}):e.jsx("strong",{children:ee.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:ee.map(se=>e.jsxs("li",{children:[se.name," · ",se.answerCount," ",Is(se.answerCount,"answer","answers")]},se.name))})]}))}return R.length>0&&W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",Io(R.length,X)]}),e.jsx("ul",{className:"av-subdetails-body",children:R.map(K=>e.jsxs("li",{children:[e.jsxs("span",{children:[qx(K)," · ",pi(K.surfaceClass)," · ",K.citationCount," ",Is(K.citationCount,"citation","citations")]}),K.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:K.sampleUrls.map(se=>e.jsx("li",{className:"break-all",children:se},se))}):null]},K.domain))})]})),e.jsxs("section",{"aria-labelledby":b,"aria-busy":g,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:b,className:"av-card-title",children:"Competitors over time"}),e.jsx(Fe,{text:S?`${Tx[S]} ${Po}`:Po})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:D}),e.jsx(fa,{label:"Competitors over time window",className:"flex-wrap",options:Rx,value:t,onChange:d})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[m?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:m}),f?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:f,children:"Retry competitors over time"}):null]}):null,g&&!s&&v.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"}),B?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(To,{percent:s.project.shareOfVoice,state:N,toneClass:ae})}),e.jsx("td",{children:e.jsx(Kn,{count:s.project.mentionCount,of:T,state:N,toneClass:ae})}),e.jsxs("td",{children:[e.jsx(Kn,{count:s.project.citationCount,of:F,state:N,toneClass:ae}),p&&N==="measured"?e.jsx("span",{className:"block text-[13px] text-secondary",children:Xl(s.project.domain,"cited")}):null]}),B?e.jsx("td",{className:"av-brand-actions"}):null]}):null,P.map(K=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(qc,{row:K,aliases:K.pinned?a[K.domain]:void 0,autoAliases:K.pinned?r[K.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:pi(K.surfaceClass)}),e.jsx("td",{children:e.jsx(To,{percent:K.shareOfVoice,state:N,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Kn,{count:K.mentionCount,of:T,state:N,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Kn,{count:K.citationCount,of:F,state:N,toneClass:"text-primary"})}),B?e.jsx("td",{className:"av-brand-actions",children:Q(K)}):null]},K.domain))]})]}):null,Y.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:Y.map(K=>e.jsx("p",{className:K.className,children:K.text},K.key))}):null]}),e.jsx(Ia,{items:W}),C&&u?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(Dx,{onAddCompetitor:u})}):null]})}function Lo({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"},d={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},c=a.length-1,h=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[c].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=`${a.length} ${a.length===1?"run":"runs"}`,f=a.map((g,y)=>{const p=new Date(g.createdAt).toLocaleDateString();return`${y===c?"Latest run, ":""}${p}: ${l[g.citationState]??g.citationState}${g.model?`, model ${g.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${m}. ${f}`,children:[a.length>1?e.jsx("span",{className:"text-[11px] text-secondary shrink-0","aria-hidden":"true",children:h}):null,e.jsx("div",{className:"flex shrink-0 items-center gap-[3px]",title:m,"aria-hidden":"true",children:a.map((g,y)=>{const p=!!(g.model&&y>0&&a[y-1]?.model&&a[y-1].model!==g.model),b=y===c;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${d[g.citationState]??"rounded-sm"} ${i[g.citationState]??"bg-mono-700"} ${p?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[g.citationState]??g.citationState,new Date(g.createdAt).toLocaleDateString(),g.model?`model ${g.model}`:null,p?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${g.runId}:${g.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function fi(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 Ta="__cited__",La="__mentioned__",Ws="__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 Ca(t,s=new Date){return Gd(t,s)}function $a(t,s=new Date){const n=Os(t);if(!n)return null;const a=Ca(n.start,s),r=Ca(n.end,s);return a===r?a:`${a} to ${r}`}function _i(t,s=new Date){const n=Os(t),a=$a(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Fx(t){const s=Os(t);return s?Fd(s.start):""}function ka(t){return t.trim().toLowerCase()}function Gx(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(`
|
|
1
|
+
import{j as e,r as o,t as Td,u as $e,L as ks,h as bs,o as Kt,B as Ti,C as Jl,D as Ld,k as $d,l as qd}from"./vendor-tanstack-ZXXkndVj.js";import{T as ge,t as Md,a as Ed,s as Li,M as va,I as Fe,f as Je,R as Zn,m as Dd,B as A,b as Xl,c as Od,d as Fd,e as Gd,S as Zl,g as ec,u as $i,h as _d,n as Hn,C as Kd,i as tc,j as sc,k as qi,l as Ud,o as Bd,p as Vd,q as sn,r as nc,v as ac,w as je,x as or,y as ne,z as ie,A as os,D as Dt,E as Ye,F as zd,G as Qd,H as Hd,J as rc,K as Wd,L as Yd,N as Jd,O as kr,P as mo,Q as Xd,U as Zd,V as eu,W as tu,X as Ys,Y as Cn,Z as su,_ as nu,$ as En,a0 as Xt,a1 as au,a2 as ru,a3 as ho,a4 as ic,a5 as Bt,a6 as Mi,a7 as iu,a8 as ou,a9 as lu,aa as cu,ab as xo,ac as De,ad as du,ae as uu,af as Ar,ag as mu,ah as hu,ai as xu,aj as pu,ak as gu,al as fu,am as yu,an as bu,ao as oc,ap as Ds,aq as Cs,ar as vu,as as ju,at as Nu,au as wu,av as Su,aw as Cu,ax as ku,ay as Au,az as lc,aA as Ru,aB as cc,aC as ur,aD as Pu,aE as He,aF as Iu,aG as Tu,aH as Lu,aI as mr,aJ as $u,aK as qu,aL as Mu,aM as ii,aN as Eu,aO as Du,aP as Ou,aQ as dc,aR as oi,aS as Fu,aT as Ei,aU as Gu,aV as Wn,aW as Jt,aX as Ra,aY as uc,aZ as lr,a_ as li,a$ as _u,b0 as po,b1 as mc,b2 as ja,b3 as Ku,b4 as hc,b5 as ci,b6 as Uu,b7 as xc,b8 as yn,b9 as Di,ba as Rr,bb as Bu,bc as Vu,bd as zu,be as Qu,bf as Hu,bg as ga,bh as go,bi as Ga,bj as Pr,bk as Wu,bl as Yu,bm as fo,bn as Ir,bo as kn,bp as pc,bq as Oi,br as gc,bs as Ju,bt as Xu,bu as yo,bv as Zu,bw as em,bx as tm,by as sm,bz as nm,bA as am,bB as rm,bC as im,bD as om,bE as lm,bF as cm,bG as dm,bH as um,bI as mm,bJ as hm,bK as xm,bL as pm,bM as gm,bN as fm,bO as ym,bP as bm,bQ as vm,bR as jm,bS as Nm,bT as wm,bU as Sm,bV as Cm,bW as Ps,bX as km,bY as bo,bZ as Am,b_ as Rm,b$ as Pm,c0 as Im,c1 as Tm,c2 as fc,c3 as Lm,c4 as $m,c5 as vo,c6 as qm,c7 as $s,c8 as Mm,c9 as yc,ca as Tr,cb as Em,cc as Dm,cd as jo,ce as Om,cf as Fm,cg as Gm,ch as _m,ci as Km,cj as Um,ck as Bm,cl as bc,cm as Vm,cn as vc,co as jc,cp as Nc,cq as wc,cr as zm,cs as Qm,ct as Hm,cu as Wm,cv as Ym,cw as Jm,cx as Xm,cy as No,cz as Zm,cA as eh,cB as th,cC as sh,cD as nh,cE as ah,cF as rh,cG as ih,cH as wo,cI as oh,cJ as lh,cK as ch,cL as dh,cM as uh,cN as mh,cO as hh,cP as xh,cQ as ph,cR as gh,cS as fh,cT as yh,cU as Lr,cV as bh,cW as So,cX as vh,cY as jh,cZ as Nh,c_ as wh,c$ as Sh,d0 as Ch,d1 as kh,d2 as Ah,d3 as Rh,d4 as Ph,d5 as Ih,d6 as Th,d7 as Lh,d8 as Sc,d9 as $h,da as qh,db as Mh,dc as Eh,dd as Dh,de as Oh,df as _a,dg as Fh,dh as Gh,di as _h,dj as Co,dk as Kh}from"./index-rBPSQ6B7.js";import{u as rn,D as Hs,a as Es,b as Fi,M as cr,c as Vs,F as Uh,P as Cc,s as Bh,p as Vh,S as zh}from"./SiteHealthSection-DXxY03vO.js";import{A as Gi,a as Qh,b as Hh,c as Wh,s as hs,i as bn,d as Yh,e as Jh,V as ko}from"./v2-overview-adapter-DSOkIdKV.js";import{o as Ot,C as Na,f as An,a as fs,b as zt,c as It,d as is,e as ct,g as ys,h as ea,M as kc,i as Xh,j as Pa,p as Zh,k as di,l as ex,m as Ao}from"./ChartPrimitives-CZ4wVBJL.js";import{g as Ac,y as wa,U as tx,z as sx,L as nx,D as ax,l as rx,j as hr,I as ix,C as Yn,X as ox,e as lx,J as cx,P as dx,K as ux,N as Rc}from"./vendor-lucide-Y6jANGfG.js";import{u as mx,a as hx,b as xx,t as px,e as gx,c as Ct}from"./extract-error-message-1VWodBea.js";import{R as on,C as ln,a as Sa,X as cn,Y as dn,T as un,b as ui,L as xr,A as nn,d as Qs,e as fx}from"./vendor-recharts-D-cUuLZo.js";import{H as $r}from"./Hint-DICI5Jq9.js";import{A as yx}from"./AuditHistoryPanel-CZOskgSK.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const bx=1e6;function vx(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/bx);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Ka={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 Pc(t,s){return t!=="viewer"||s!==null}function Ic(t,s){return t==="research"&&!s?"tracked":t}function Tc(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 mi(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function jx(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function Nx(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 hi({state:t,label:s,className:n}){return e.jsx(ge,{tone:Ed(t),className:n,children:s??Md(t)})}const vn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Ro={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},wx={"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."},Sx="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Cx(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:Je(t.score,Zn.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 kx({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(Fe,{text:Sx})]}),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:Je(a.share)})]},a.label))})]})}function Ax({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",d=!i&&t.branded.snapshotsTotal>0,c=d?a:"non-brand",h=i?"pooled":c,u=c==="branded"?t.branded:t.breakdown,m=c==="branded"?t.breakdown:t.branded,f=Cx(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:m.snapshotsTotal>0}),g=Li(f.headline),y=h==="non-brand"?va[t.tone]:"text-secondary";function p(b){const C=vn.findIndex($=>$.value===c);let v=null;b.key==="ArrowRight"||b.key==="ArrowDown"?v=(C+1)%vn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?v=(C-1+vn.length)%vn.length:b.key==="Home"?v=0:b.key==="End"&&(v=vn.length-1),v!==null&&(b.preventDefault(),r(vn[v].value),b.currentTarget.querySelectorAll('[role="radio"]')[v]?.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(Fe,{text:wx[h]})]}),d?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:p,children:vn.map(b=>{const C=b.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":C,tabIndex:C?0:-1,onClick:()=>r(b.value),className:`segmented-option min-h-11 ${C?"segmented-option-active":""}`,children:b.label},b.value)})}):e.jsx("span",{className:"mention-share-class",children:Ro[h]})]}),f.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[g.figure,g.sign?e.jsx("span",{className:"text-faint",children:g.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:Ro[h]}),` · ${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(kx,{breakdown:u,projectLabel:s})]})}function Ia({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 fa({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(d){const c=t.findIndex(u=>u.value===s);let h=null;d.key==="ArrowRight"||d.key==="ArrowDown"?h=(c+1)%t.length:d.key==="ArrowLeft"||d.key==="ArrowUp"?h=(c-1+t.length)%t.length:d.key==="Home"?h=0:d.key==="End"&&(h=t.length-1),h!==null&&(d.preventDefault(),n(t[h].value),d.currentTarget.querySelectorAll('[role="radio"]')[h].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(d=>{const c=d.value===s,h=d.description?`${l}-${d.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":c,"aria-describedby":h,tabIndex:c?0:-1,onClick:()=>n(d.value),className:`segmented-option pointer-coarse:min-h-11 ${c?"segmented-option-active":""}`,children:d.label}),d.description?e.jsx("span",{id:h,className:"sr-only",children:d.description}):null]},d.value)})})}const Rx=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Px={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},Ix={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},Tx={"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."},Lx={"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"},Po="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.",xi=100;function $x(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function Lc(t){return t==="unavailable"?"Unavailable":"Not measured"}function pi(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 $c(t){const s=t.label.trim(),n=Od(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function qc({row:t,aliases:s=[],autoAliases:n=[]}){const a=$c(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:d},c)=>e.jsxs("span",{children:[c>0?", ":"",i,d?e.jsx("span",{className:"av-alias-auto",title:"Detected automatically from this project's stored answers",children:" (auto)"}):null]},`${d?"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 qx(t){const s=$c(t);return s?`${s} (${t.domain})`:t.domain}function Io(t,s){return s&&t>=xi?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function gi({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function d(){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(A,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{d()},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 Mx({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 Kn({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:Lc(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 To({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":Lc(s)});const{figure:a,sign:r}=Li(Je(t,Zn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Ex({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(qc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:pi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(Kn,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Kn,{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(Mx,{urls:l.sampleUrls}):null,r?e.jsx(gi,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function Dx({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,d]=o.useState(null);async function c(){const h=n.trim();if(!(!h||r)){l(!0),d(null);try{if(await t(h)===!1){d("Could not add competitor. Try again.");return}a("")}catch{d("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:h=>{h.preventDefault(),c()},"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:h=>a(h.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(A,{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 Ox({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},competitorAutoAliases:r={},canWrite:l,isEmbed:i,onWindowChange:d,onPin:c,onUnpin:h,onAddCompetitor:u,error:m,onRetry:f,isLoading:g=!1,scopeLabel:y,advancedPortfolio:p=!1}){const b=o.useId(),C=l&&!i,v=s?.pinned??n,$=s?.observed??[],R=s?.otherSources??[],x=s?.evidence,N=$x(s),w=s?.basis==="observed",P=w?$.filter(K=>K.shareOfVoice!==null):v,q=w?$.filter(K=>K.shareOfVoice===null):$,S=s?.filters.queryClass,G=s?.marketState?.draft?.pendingCompetitorDomains.length??0,X=s?.truncated===!0,T=x?.answeredResults??0,F=x?x.answeredResults+x.missingAnswerTextResults:0,ae=S==="non-brand"&&s?.project.shareOfVoice!=null?va[Dd(s.project.shareOfVoice)]:"text-primary",Q=K=>C?K.pinned?h?e.jsx(gi,{action:"unpin",domain:K.domain,mutation:h}):null:c?e.jsx(gi,{action:"pin",domain:K.domain,mutation:c}):null:null,B=P.some(K=>Q(K)!==null),D=[y,S?Ix[S]:null,Px[t],s?.basis?w?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),Y=[];if(s&&!w&&P.length===0&&Y.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&Y.push({key:"reason",text:`Mention share: ${Lx[s.reason]}`}),s&&q.length>0){const K=q.length;Y.push({key:"others",text:X&&K>=xi?`${xi} or more other competitors seen`:`${K} other ${Is(K,"competitor","competitors")} seen`})}G>0&&Y.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${G} ${Is(G,"competitor","competitors")}`});const E=[x&&x.missingAnswerTextResults>0?"Answer data incomplete":null,x&&x.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);E.length>0&&Y.push({key:"incomplete",text:E.join(" · "),className:va.caution});const W=[];if(s&&x){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:x.answeredResults})," ",Is(x.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:x.answeredResults})," ",Is(x.answeredResults,"answer","answers")]})),!s.reason&&N==="measured"&&s.project.shareOfVoice!==null&&W.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),P.map(se=>e.jsxs(Td.Fragment,{children:[", ",se.domain," ",e.jsx("strong",{children:se.mentionCount})]},se.domain))," ","of ",e.jsx("strong",{children:x.mentionCredits})," ",w?"brand mentions":"tracked-brand mentions"]})),W.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:x.sourceResults})]})),q.length===0&&W.push("Other competitors seen: none"),x.missingAnswerTextResults>0&&W.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:x.missingAnswerTextResults})," ",Is(x.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),x.incompleteSourceResults>0&&W.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:x.incompleteSourceResults})," ",Is(x.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const K=x.excludedProbeResults+x.excludedNonCompletedResults;K>0&&W.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:K})," ",Is(K,"answer","answers")," from spot checks or unfinished sweeps"]}))}const L=[...s?[{name:"You",row:s.project}]:[],...P.map(K=>({name:K.domain,row:K}))].filter(K=>K.row.sampleUrls.length>0);N==="measured"&&L.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:L.map(({name:K,row:se})=>e.jsxs("div",{children:[e.jsx("p",{children:K}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:se.sampleUrls.map(ce=>e.jsx("li",{className:"break-all",children:ce},ce))})]},se.domain))})]})),s&&q.length>0&&W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",Io(q.length,X)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Ex,{rows:q,state:N,named:T,cited:F,onPin:C?c:void 0})})]}));const ee=s?.observedNames??[];if(ee.length>0){const K=s?.observedNamesTotal??ee.length;W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",K>ee.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:ee.length})," of ",e.jsx("strong",{children:K})]}):e.jsx("strong",{children:ee.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:ee.map(se=>e.jsxs("li",{children:[se.name," · ",se.answerCount," ",Is(se.answerCount,"answer","answers")]},se.name))})]}))}return R.length>0&&W.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",Io(R.length,X)]}),e.jsx("ul",{className:"av-subdetails-body",children:R.map(K=>e.jsxs("li",{children:[e.jsxs("span",{children:[qx(K)," · ",pi(K.surfaceClass)," · ",K.citationCount," ",Is(K.citationCount,"citation","citations")]}),K.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:K.sampleUrls.map(se=>e.jsx("li",{className:"break-all",children:se},se))}):null]},K.domain))})]})),e.jsxs("section",{"aria-labelledby":b,"aria-busy":g,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:b,className:"av-card-title",children:"Competitors over time"}),e.jsx(Fe,{text:S?`${Tx[S]} ${Po}`:Po})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:D}),e.jsx(fa,{label:"Competitors over time window",className:"flex-wrap",options:Rx,value:t,onChange:d})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[m?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:m}),f?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:f,children:"Retry competitors over time"}):null]}):null,g&&!s&&v.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"}),B?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(To,{percent:s.project.shareOfVoice,state:N,toneClass:ae})}),e.jsx("td",{children:e.jsx(Kn,{count:s.project.mentionCount,of:T,state:N,toneClass:ae})}),e.jsxs("td",{children:[e.jsx(Kn,{count:s.project.citationCount,of:F,state:N,toneClass:ae}),p&&N==="measured"?e.jsx("span",{className:"block text-[13px] text-secondary",children:Xl(s.project.domain,"cited")}):null]}),B?e.jsx("td",{className:"av-brand-actions"}):null]}):null,P.map(K=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(qc,{row:K,aliases:K.pinned?a[K.domain]:void 0,autoAliases:K.pinned?r[K.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:pi(K.surfaceClass)}),e.jsx("td",{children:e.jsx(To,{percent:K.shareOfVoice,state:N,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Kn,{count:K.mentionCount,of:T,state:N,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Kn,{count:K.citationCount,of:F,state:N,toneClass:"text-primary"})}),B?e.jsx("td",{className:"av-brand-actions",children:Q(K)}):null]},K.domain))]})]}):null,Y.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:Y.map(K=>e.jsx("p",{className:K.className,children:K.text},K.key))}):null]}),e.jsx(Ia,{items:W}),C&&u?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(Dx,{onAddCompetitor:u})}):null]})}function Lo({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"},d={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},c=a.length-1,h=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[c].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=`${a.length} ${a.length===1?"run":"runs"}`,f=a.map((g,y)=>{const p=new Date(g.createdAt).toLocaleDateString();return`${y===c?"Latest run, ":""}${p}: ${l[g.citationState]??g.citationState}${g.model?`, model ${g.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${m}. ${f}`,children:[a.length>1?e.jsx("span",{className:"text-[11px] text-secondary shrink-0","aria-hidden":"true",children:h}):null,e.jsx("div",{className:"flex shrink-0 items-center gap-[3px]",title:m,"aria-hidden":"true",children:a.map((g,y)=>{const p=!!(g.model&&y>0&&a[y-1]?.model&&a[y-1].model!==g.model),b=y===c;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${d[g.citationState]??"rounded-sm"} ${i[g.citationState]??"bg-mono-700"} ${p?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[g.citationState]??g.citationState,new Date(g.createdAt).toLocaleDateString(),g.model?`model ${g.model}`:null,p?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${g.runId}:${g.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function fi(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 Ta="__cited__",La="__mentioned__",Ws="__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 Ca(t,s=new Date){return Gd(t,s)}function $a(t,s=new Date){const n=Os(t);if(!n)return null;const a=Ca(n.start,s),r=Ca(n.end,s);return a===r?a:`${a} to ${r}`}function _i(t,s=new Date){const n=Os(t),a=$a(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Fx(t){const s=Os(t);return s?Fd(s.start):""}function ka(t){return t.trim().toLowerCase()}function Gx(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
2
|
`)}const _x={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function nt(t){const s=ka(t);return _x[s]??t.charAt(0).toUpperCase()+t.slice(1)}function yi(t){return Math.round(t*1e3)/10}function bi(t){return t.byProvider??{}}function Kx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?Ta:La,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(m=>({date:m.startDate,[c]:yi(m[h])})),series:[c],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(c=>Object.keys(bi(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},u=bi(c);for(const m of i){const f=u[m];h[m]=f?yi(f[l]):null}return h}),series:i,hasData:a,singleBucket:r}}function Mc(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Ux(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Bx(t){return t.servedModelAttribution??{}}function Vx(t){return t.modelServiceMismatch??{}}function zx(t){return t.modelPointerChanges??{}}function ya(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Aa(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 Qx(t){return ya([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function Hx(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 Wx(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:Hx(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Yx(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 Jx(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[Ws]:r?.rate==null?null:yi(r.rate)}}),n=s.map(a=>a[Ws]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Ws],hasData:n.length>0,singleBucket:n.length===1}}function Xx(t,s,n){return s==="mentionShare"?Jx(t):Kx(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 ep(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 tp(t,s,n){const a=n==="mentioned"?"mentionRate":"citationRate";for(let r=t.buckets.length-1;r>=0;r--){const l=bi(t.buckets[r])[s];if(l)return l[a]}return null}function Qe(t){return Date.parse(t)}function Ec(t,s){const n=Os(t);if(!n)return!1;const a=Qe(s);return a>=Qe(n.start)&&a<=Qe(n.end)}function Dc(t){return t.basketChanges??[]}function Oc(t,s){return s.filter(n=>Ec(t,n.at)).sort((n,a)=>Qe(n.at)-Qe(a.at))}function pr(t,s){return ka(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function sp(t){return Object.entries(t).filter(([s,n])=>!pr(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function np(t){return[...Dc(t)].sort((s,n)=>Qe(n.at)-Qe(s.at)).map(s=>({at:Ot(s.at),added:s.added,removed:s.removed}))}function ap(t,s){const n=[...t.events].sort((r,l)=>Qe(r.observedAt)-Qe(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)Qe(r.observedAt)<=Qe(s)&&(a=r.to);return a}function $o(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 rp(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],d=new Set(r.events.map(c=>c.observedAt));for(const c of r.events){const h=pr(a,c.to)?i.find(u=>u.observedAt===c.observedAt):void 0;n.push($o(a,c,h?{from:h.from,to:h.to}:null,!1))}for(const c of i)d.has(c.observedAt)||pr(a,ap(r,c.observedAt))&&n.push($o(a,c,null,!0))}return n.sort((a,r)=>Qe(r.at)-Qe(a.at)||a.provider.localeCompare(r.provider))}function ip({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&&Ec(t,f),i=s.filter(f=>l(f.at)),d=i.reduce((f,g)=>f+g.added.length,0),c=i.reduce((f,g)=>f+g.removed.length,0),h=n.filter(f=>l(f.at)).length,u=t?$a(t,a):null;if(u===null||d+c+h===0){const f=r.reduce((g,y)=>Qe(y)>Qe(g)?y:g);return`No changes since ${Ca(f,a)}`}const m=[u];return d>0&&m.push(`${d} ${d===1?"query":"queries"} added`),c>0&&m.push(`${c} ${c===1?"query":"queries"} removed`),h>0&&m.push(`${h} new ${h===1?"model":"models"}`),m.join(" · ")}function op(t,s,n,a=null){const r=Qe(t);if(!Number.isFinite(r))return null;const l=s.filter(h=>Qe(h)<r);if(l.length>0)return Ot(l.reduce((h,u)=>Qe(u)>Qe(h)?u:h));const i=n.map(h=>Os(h)).filter(h=>h!==null).sort((h,u)=>Qe(h.start)-Qe(u.start)),d=i.findIndex(h=>Qe(h.start)<=r&&r<=Qe(h.end));if(d===-1)return null;const c=i[d];return Qe(c.start)===r?d>0?i[d-1].end:a&&Qe(a)<r?Ot(a):null:c.sweepCount===2&&Qe(c.end)===r?c.start:null}function lp(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=Qe(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 Jn(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function cp(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function vi(t,s){const n=Qe(s.start),a=Qe(s.end);return s.sweepCount>2?cp(t,n,a):Jn(t,n)!==Jn(t,a)}function Fc(t,s,n,a){const r=Qe(s),l=Qe(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},d=new Set;for(const[m,f]of lp(t)){if(!a(f))continue;d.add(m);const g=Jn(f,r),y=Jn(f,l);g!==y?(y?i.added:i.removed).push(m):(g?i.removedAndAddedBack:i.addedAndRemovedAgain).push(m)}if(d.size===0)return null;const c=m=>[...m.added,...m.removed].some(f=>d.has(f)),h=t.filter(m=>Qe(m.at)>r&&Qe(m.at)<=l&&c(m)).sort((m,f)=>Qe(m.at)-Qe(f.at)),u=[...new Set(h.flatMap(m=>[...m.added,...m.removed]))].filter(m=>d.has(m));return{changes:h,keys:u,moves:i}}function dp(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,d=l?.end??a.endDate,c=Fc(s,i,d,h=>Jn(h,Qe(i))!==Jn(h,Qe(d))||r!==null&&vi(h,r)||l!==null&&vi(h,l));return!c&&n.queryCount===a.queryCount?null:{...c??{changes:[],keys:[],moves:{added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]}},firstCount:n.queryCount,latestCount:a.queryCount}}function Gc(t,s){const n=Os(t);if(!n)return null;const a=Fc(s,n.start,n.end,r=>vi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function qr(t){return`${t} ${t===1?"query":"queries"}`}function up(t){const s=[],n=a=>s.length===0?qr(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(`${qr(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${qr(t.addedAndRemovedAgain.length)} added and removed again`),ya(s)}function qo(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 Mo=320;function Eo(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Do(t){return t==="non-brand"?0:t==="branded"?1:2}function mp(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 hp(t){return t.phrase}function Oo(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 Fo(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 xp(t,s){return t.map(n=>_c(n,s))}function _c(t,s){return s==="citations"?t:{...t,citationState:Oo(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Oo(n,s)}))}}function Go(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",d=l==="cited"||l==="emerging";return r==="lost"||l!==null&&d&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!d&&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 pp(t){const s=fi(xp(t,"mentions")),n=fi(t);return[Go(s,"mentions"),Go(n,"citations")]}function gp({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 _o({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:pp(t).map(s=>e.jsx(gp,{signal:s},s.key))})}function Kc({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(Zl,{}),s]})}):null,t?e.jsx(ec,{queryClass:t,manage:!!s}):null]})}function fp({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[],actions:i,actionPanel:d}){const{openEvidence:c}=$i(),h=o.useId(),[u,m]=o.useState(new Set),f=_d(),[g,y]=o.useState("mentions"),[p,b]=o.useState(n),[C,v]=o.useState("all"),[$,R]=o.useState(""),x=a??$,N=E=>{R(E),r?.(E)},w=o.useMemo(()=>[...new Set([...t.map(E=>E.provider).filter(Boolean),...x?[x]:[]])].sort(),[t,x]),P=o.useMemo(()=>{const E=new Map;for(const W of t){if(x&&W.provider!==x)continue;const L=W.query,ee=W.queryClass??null,K=s?W.location??null:null,se=JSON.stringify([L,ee,K]),ce=E.get(se)??{key:se,phrase:L,queryClass:ee,location:K,items:[],rawItems:[]};ce.items.push(_c(W,g)),ce.rawItems.push(W),E.set(se,ce)}return[...E.values()].sort((W,L)=>Do(W.queryClass)-Do(L.queryClass))},[t,g,s,x]),q=o.useMemo(()=>P.filter(E=>C==="all"||(C==="unclassified"?E.queryClass===null:E.queryClass===C)),[P,C]),S=rn({rows:q,getSearchText:hp}),G=o.useMemo(()=>{const E=new Map;for(const W of S.filteredRows){const L=E.get(W.queryClass)??new Set;L.add(W.phrase),E.set(W.queryClass,L)}return E},[S.filteredRows]),X=o.useMemo(()=>new Set(l.map(Hn)),[l]),T=f?6:5,F=S.rows.map(E=>E.key),ae=F.length>0&&F.every(E=>u.has(E)),Q=E=>{m(W=>{const L=new Set(W);return L.has(E)?L.delete(E):L.add(E),L})},B=g==="mentions"?"mentioned":"cited",D=g==="mentions"?"Mention History":"Citation History",Y=g==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(Kc,{queryClass:C,actions:i}),d,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:`${h}-${E}`,type:"button",role:"tab","aria-controls":h,"aria-selected":g===E,tabIndex:g===E?0:-1,onClick:()=>y(E),onKeyDown:W=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(W.key))return;W.preventDefault();const L=W.key==="Home"?"mentions":W.key==="End"||E==="mentions"?"citations":"mentions";y(L),document.getElementById(`${h}-${L}`)?.focus()},children:E==="mentions"?"Mentions":"Citations"},E))}),e.jsx(Fe,{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:p==="detailed",onChange:E=>b(E.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(A,{type:"button",variant:"ghost",className:"min-h-11",disabled:F.length===0,onClick:()=>{m(E=>{const W=new Set(E);for(const L of F)ae?W.delete(L):W.add(L);return W})},children:ae?"Collapse page":"Expand page"})]})]}),t.length>0||x?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(Hs,{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:x,onChange:E=>{N(E.target.value),S.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),w.map(E=>e.jsx("option",{value:E,children:nt(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=>{v(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:h,role:"tabpanel","aria-labelledby":`${h}-${g}`,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(Fe,{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:D}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),mp(S.rows).map(E=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:T,children:[Eo(E.queryClass)," (",G.get(E.queryClass)?.size??0,")"]})}),E.rows.map(({key:W,phrase:L,queryClass:ee,location:K,items:se,rawItems:ce})=>{const Se=u.has(W),Z=F.indexOf(W),me=`${h}-query-${Z}`,Ce=X.has(Hn(L)),J=se.map(re=>re.citationState),he=J.includes("cited")?"cited":J.includes("emerging")?"emerging":J.includes("lost")?"lost":J.every(re=>re==="pending")?"pending":"not-cited",_=[...new Set(ce.map(re=>re.queryId).filter(re=>!!re))],pe=ce.map(re=>re.sourceSnapshotId).filter(re=>!!re),Me=fi(se),Pe=se.filter(re=>re.citationState===Kd.cited||re.citationState==="emerging").length;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>Q(W),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":L,"aria-describedby":me,"aria-expanded":Se,onClick:re=>{re.stopPropagation(),Q(W)},children:[e.jsx(Ac,{size:16,"aria-hidden":"true",className:Se?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:L}),e.jsxs("span",{id:me,className:"query-evidence-meta",children:[e.jsx("span",{children:Eo(ee)}),s&&e.jsx("span",{children:K??"No location"}),se.filter(re=>re.provider).map(re=>e.jsx("span",{children:nt(re.provider)},re.id))]})]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hi,{state:he,label:Fo(he,g),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":`${Pe} of ${se.length} engines ${Y}`,title:`${Pe} of ${se.length} engines ${Y}`,children:[Pe,"/",se.length]})]})}),f&&e.jsx("td",{children:e.jsx(tc,{queryId:_.length===1?_[0]:null,sourceSnapshotIds:_.length>1?[]:pe,queryClass:ee,location:s?K:void 0})}),e.jsx("td",{children:e.jsx(Lo,{history:Me,signal:g})}),e.jsx("td",{className:"evidence-change-cell",children:Ce?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(_o,{items:ce})}),e.jsx("td",{})]}),Se&&se.map((re,be)=>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:re.provider?nt(re.provider):"Awaiting engine"})}),e.jsx("td",{children:e.jsx(hi,{state:re.citationState,className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal",label:Fo(re.citationState,g)})}),f&&e.jsx("td",{children:e.jsx(sc,{queryId:re.queryId,sourceSnapshotIds:re.sourceSnapshotId?[re.sourceSnapshotId]:[],queryClass:re.queryClass,provider:re.provider,location:re.location??null})}),e.jsx("td",{children:e.jsx(Lo,{history:re.runHistory,signal:g})}),e.jsx("td",{className:"evidence-change-cell",children:Ce?null:e.jsx(_o,{items:[ce[be]??re]})}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",className:"min-h-11",type:"button",title:`View ${re.provider?nt(re.provider):"saved"} answer for ${re.query}`,onClick:Ne=>{Ne.stopPropagation(),c(re.id)},children:"View"})})]}),p==="detailed"&&e.jsx("tr",{className:"query-evidence-preview-row",children:e.jsx("td",{colSpan:T,children:e.jsx(bp,{item:re,mode:g,onViewFull:()=>c(re.id)},g)})})]},re.id))]},W)})]},E.queryClass??"unclassified"))]})}),S.totalRows===0&&(S.hasQuery||C!=="all"||x)?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Es,{page:S.page,pageSize:S.pageSize,visibleRows:S.rows.length,totalRows:S.totalRows,onPageChange:S.setPage,itemLabel:S.hasQuery||C!=="all"||x?"matches":"queries"})]}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",B==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function yp(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=Bd(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 ji(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function bp({item:t,mode:s,onViewFull:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1);if(s==="mentions")return e.jsx(Ko,{item:t,onViewFull:n});const d=t.evidenceUrls.length>0?t.evidenceUrls.map(c=>({uri:c,title:t.groundingSources.find(h=>h.uri===c)?.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":d.length>0?"Grounding sources":"Cited domains"}),d.length>0?e.jsx("ul",{className:"space-y-4",children:d.slice(0,l?void 0:6).map((c,h)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(qi,{url:c.uri,title:c.title}),ji(t,Ud(c.uri)??"")&&e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:"Competitor source"})]},`${h}-${c.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(c=>e.jsxs("li",{className:"[overflow-wrap:anywhere]",children:[c,ji(t,c)?" · competitor source":""]},c))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(d.length>6||d.length===0&&t.citedDomains.length>6)&&e.jsx(A,{type:"button",variant:"ghost",className:"min-h-11","aria-expanded":l,onClick:()=>i(c=>!c),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:c=>{c.preventDefault(),r(h=>!h)},children:"Answer text"}),a&&e.jsx(Ko,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function Ko({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}=t,d=o.useMemo(()=>yp({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 h=t.answerSnippet.length>Mo;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(Gi,{headingLevel:4,highlightGroups:d,previewLength:Mo,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,ji(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"]})]})]})]}),h&&e.jsx(A,{type:"button",variant:"ghost",className:"min-h-11",onClick:u=>{u.stopPropagation(),s()},children:"View full answer"})]})}function Ua({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 qa({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&&Vd("window"),n(i)},children:r?r(i):i},i))})}const Mr=ct[0],Er=ct[1],Uo=ct[2],Bo=ct[3],vp=["both","server","ga4"],Vo={fontSize:11,paddingTop:6},zo=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Qo=t=>typeof t=="number"?or(Math.round(t)):String(t),xs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function Dr(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 Or({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(Fe,{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 jp(t,s){return n=>{const{cx:a,cy:r,index:l,key:i}=n,d=l??-1;return!(t[d]!=null&&t[d-1]==null&&t[d+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 Np({projectName:t,sinceMinutes:s}){const[n,a]=o.useState(!0),[r,l]=o.useState(!0),[i,d]=o.useState("both"),c=mx(t,{sinceMinutes:s,granularity:"day",limit:1}),h=hx(t),m=$e({...nc({client:ne,path:{name:t}}),enabled:!!t,staleTime:sn}).data?.connected===!0,f=$e({...ac({client:ne,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&m,staleTime:sn}),g=o.useMemo(()=>c.data?.series?.points??[],[c.data]),y=o.useMemo(()=>{const P=f.data;return new Map((P?.days??[]).map(q=>[q.date,q.sessions]))},[f.data]),p=o.useMemo(()=>{const P=S=>S.measured!==!1;if(g.length===0||P(g[0]))return null;const q=g.findIndex(P)-1;return q<0?{from:g[0].bucket,to:g[g.length-1].bucket}:{from:g[0].bucket,to:g[q].bucket}},[g]),b=c.data?.series?.coverageStart??null,C=c.data?.series?.trends,v=o.useMemo(()=>{const P=Dr(C?.crawlerContentHits,g.length),q=Dr(C?.aiUserFetchHits,g.length),S=Dr(C?.aiReferralLandedHits,g.length);return g.map((G,X)=>({...G,crawlerContentHits:G.measured!==!1?xs(G.crawlerContentHits):null,aiUserFetchHits:G.measured!==!1?xs(G.aiUserFetchHits):null,aiReferralLandedHits:G.measured!==!1?xs(G.aiReferralLandedHits):null,ga4Visits:y.get(G.bucket)??null,crawlTrend:P[X],fetchTrend:q[X],visitTrend:S[X]}))},[g,y,C]),$=c.data?.totals,R=$&&{crawlers:xs($.crawlerContentHits),fetches:xs($.aiUserFetchHits),visits:xs($.aiReferralLandedHits)},x=o.useMemo(()=>g.reduce((P,q)=>({crawlers:P.crawlers+xs(q.crawlerContentHits),fetches:P.fetches+xs(q.aiUserFetchHits),visits:P.visits+xs(q.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[g]),N=R??x,w=N.crawlers>0||N.fetches>0||N.visits>0;if(c.isLoading)return e.jsx(je,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(c.isError)return e.jsxs(je,{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=h.data?.sources,q=P!==void 0&&P.length===0,S=!q&&b===null;return e.jsxs(je,{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(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Or,{label:"AI crawlers",value:or(N.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(Or,{label:"AI page fetches",value:or(N.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(Or,{label:"AI visitors",value:or(N.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."})]}),g.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:xs(g[g.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:xs(g[g.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:xs(g[g.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:y.get(g[g.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(Fe,{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:v,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Sa,{stroke:Na,vertical:!1}),e.jsx(cn,{dataKey:"bucket",tick:zt,stroke:fs,tickFormatter:An,minTickGap:28}),e.jsx(dn,{tick:zt,stroke:fs,width:48,allowDecimals:!1}),e.jsx(un,{contentStyle:is.contentStyle,labelStyle:is.labelStyle,itemStyle:is.itemStyle,labelFormatter:It,formatter:Qo}),p&&e.jsx(ui,{x1:p.from,x2:p.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(xr,{wrapperStyle:Vo,iconType:"plainline",iconSize:14,formatter:P=>zo.has(P)?"":P}),e.jsx(nn,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Mr,fill:Mr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(nn,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Er,fill:Er,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Qs,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Mr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Qs,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Er,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(Fe,{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(qa,{windows:vp,value:i,onChange:d,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:v,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Sa,{stroke:Na,vertical:!1}),e.jsx(cn,{dataKey:"bucket",tick:zt,stroke:fs,tickFormatter:An,minTickGap:28}),e.jsx(dn,{tick:zt,stroke:fs,width:48,allowDecimals:!1}),e.jsx(un,{contentStyle:is.contentStyle,labelStyle:is.labelStyle,itemStyle:is.itemStyle,labelFormatter:It,formatter:Qo}),p&&e.jsx(ui,{x1:p.from,x2:p.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(xr,{wrapperStyle:Vo,iconType:"plainline",iconSize:14,formatter:P=>zo.has(P)?"":P}),i!=="ga4"&&e.jsx(Qs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Uo,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Qs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Bo,strokeWidth:1.8,strokeDasharray:"5 3",dot:jp(v.map(P=>P.ga4Visits),Bo)}),r&&i!=="ga4"&&e.jsx(Qs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Uo,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const wp=6,Xn="__other__",zn="_socialTotal";function Sp(t,s=wp){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,m)=>m[1]!==u[1]?m[1]-u[1]:u[0].localeCompare(m[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),d=new Map;for(const u of t){let m=d.get(u.date);m||(m={date:u.date,[zn]:0},d.set(u.date,m));const f=l.has(u.source)?u.source:Xn;m[f]=(m[f]??0)+u.sessions,m[zn]=(m[zn]??0)+u.sessions}const c=[...d.values()].sort((u,m)=>String(u.date).localeCompare(String(m.date))),h=r.map(([u])=>u);return i>0&&h.push(Xn),{data:c,sources:h,otherCount:i}}function Qn(t){return t.replace(/\+/g," ")}function Uc(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ho="_totalSessions",Wo="_organicSessions";function Cp(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Ho]:i.sessions,[Wo]:i.organicSessions});for(const i of t.days){let d=n.get(i.date);d||(d={[Ho]:0,[Wo]:0},n.set(i.date,d));for(const c of i.bySource)d[c.source]=(d[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([i],[d])=>i.localeCompare(d)).map(([i,d])=>({date:i,...d})),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 kp=["7d","30d","90d"],Ap={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},tn=ct,Ni=ys.textDim,Bc=ys.textFaint,oa=25;function Rp(t){return Fi(t.landingPage)}const Pp=25,Ip=10,Fr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Ba(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function gr(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 Tp({projectName:t}){const{data:s,isLoading:n,isError:a}=xx(t);if(n)return e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(je,{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."," ",!ie()&&e.jsx(ks,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(je,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(ks,{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(je,{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(ge,{tone:px(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?gr(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(ks,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function Lp({projectName:t}){const[s,n]=o.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Tp,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(qa,{windows:kp,value:s,onChange:n,label:"Traffic time period"})}),e.jsx($p,{projectName:t,window:s}),e.jsx(Np,{projectName:t,sinceMinutes:Ap[s]})]})}function $p({projectName:t,window:s}){const n=bs(),a=s??"30d",[r,l]=o.useState(null),[i,d]=o.useState(null),[c,h]=o.useState(!0),[u,m]=o.useState(!1),[f,g]=o.useState(!1),[y,p]=o.useState(null),[b,C]=o.useState(null),[v,$]=o.useState("sessions"),[R,x]=o.useState("desc"),[N,w]=o.useState("sessions"),[P,q]=o.useState("desc"),[S,G]=o.useState("sessions"),[X,T]=o.useState("desc"),[F,ae]=o.useState("sessions"),[Q,B]=o.useState("desc"),[D,Y]=o.useState(Fr),[E,W]=o.useState([]),[L,ee]=o.useState([]),[K,se]=o.useState(!1);async function ce(te){h(!0),p(null);try{const Be=await n.fetchQuery({...nc({client:ne,path:{name:t}}),staleTime:sn});if(te.current)return;if(l(Be),!Be.connected){d(null),Y(Fr),W([]),ee([]),h(!1);return}const Ee=a==="all"?void 0:a,Ae=await n.fetchQuery({...zd({client:ne,path:{name:t},query:Ee?{window:Ee}:void 0}),staleTime:sn}),rt=Ae.windowStart||Ae.windowEnd?{...Ae.windowStart?{startDate:Ae.windowStart}:{},...Ae.windowEnd?{endDate:Ae.windowEnd}:{}}:void 0,[Zt,es,Qt]=await Promise.all([n.fetchQuery({...ac({client:ne,path:{name:t},query:Ee?{window:Ee}:void 0}),staleTime:sn}).catch(()=>Fr),n.fetchQuery({...Qd({client:ne,path:{name:t},query:Ee?{window:Ee}:void 0}),staleTime:sn}).catch(()=>[]),n.fetchQuery({...Hd({client:ne,path:{name:t},query:rt}),staleTime:sn}).catch(()=>[])]);if(te.current)return;d(Ae),Y(Zt),W(es),ee(Qt),h(!1)}catch(Be){if(te.current)return;p(Be instanceof Error?Be.message:"Failed to load GA4 data"),h(!1)}}o.useEffect(()=>{const te={current:!1};return ce(te),()=>{te.current=!0}},[t,a,n]);async function Se(){m(!0),p(null),C(null);try{const te=await rc(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 ce({current:!1})}catch(te){p(te instanceof Error?te.message:"Sync failed")}finally{m(!1)}}async function Z(){g(!0),p(null),C(null);try{await Wd(t),await Dt(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),d(null),C("GA4 disconnected")}catch(te){p(te instanceof Error?te.message:"Disconnect failed")}finally{g(!1)}}function me(te){_.setPage(1),v===te?x(Be=>Be==="desc"?"asc":"desc"):($(te),x("desc"))}function Ce(te){N===te?q(Be=>Be==="desc"?"asc":"desc"):(w(te),q("desc"))}function J(te){S===te?T(Be=>Be==="desc"?"asc":"desc"):(G(te),T("desc"))}const he=o.useMemo(()=>i?.topPages?[...i.topPages].sort((te,Be)=>{const Ee=te[v],Ae=Be[v];return typeof Ee=="string"&&typeof Ae=="string"?R==="asc"?Ee.localeCompare(Ae):Ae.localeCompare(Ee):R==="asc"?Ee-Ae:Ae-Ee}):[],[i?.topPages,v,R]),_=rn({rows:he,getSearchText:te=>Fi(te.landingPage),pageSize:Ip}),pe=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((te,Be)=>{const Ee=te[N],Ae=Be[N];return typeof Ee=="string"&&typeof Ae=="string"?P==="asc"?Ee.localeCompare(Ae):Ae.localeCompare(Ee):P==="asc"?Ee-Ae:Ae-Ee}):[],[i?.aiReferrals,N,P]),Me=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((te,Be)=>{const Ee=te[F],Ae=Be[F];return typeof Ee=="string"&&typeof Ae=="string"?Q==="asc"?Ee.localeCompare(Ae):Ae.localeCompare(Ee):Q==="asc"?Ee-Ae:Ae-Ee}):[],[i?.aiReferralLandingPages,F,Q]),Pe=rn({rows:Me,getSearchText:Rp,pageSize:Pp}),re=Pe.totalRows>0?`${Pe.totalRows.toLocaleString()} ${Pe.hasQuery?Pe.totalRows===1?"match":"matches":Pe.totalRows===1?"row":"rows"}`:Pe.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function be(te){Pe.setPage(1),F===te?B(Be=>Be==="desc"?"asc":"desc"):(ae(te),B("desc"))}const Ne=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((te,Be)=>{const Ee=te[S],Ae=Be[S];return typeof Ee=="string"&&typeof Ae=="string"?X==="asc"?Ee.localeCompare(Ae):Ae.localeCompare(Ee):X==="asc"?Ee-Ae:Ae-Ee}):[],[i?.socialReferrals,S,X]),{socialChartData:_e,socialChartSources:Oe,socialOtherCount:O}=o.useMemo(()=>{const te=Sp(L);return{socialChartData:te.data,socialChartSources:te.sources,socialOtherCount:te.otherCount}},[L]),{chartData:U,chartSources:V,dateRange:Le}=o.useMemo(()=>{const te=Cp(D,E);return{chartData:te.data,chartSources:te.sources,dateRange:te.dateRange}},[D,E]);if(c&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ie()||os()?e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Ep,{projectName:t,onConnected:()=>{(async()=>(await Dt(n,"ga"),await ce({current:!1})))()}});const ze=i?.organicSharePctDisplay??"0%",Ue=i?.channelBreakdown?.organic.sharePctDisplay??ze,dt=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,de=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Tt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",vt=i?.paidAiSessionsBySession??0,We=i?.paidAiSharePctBySessionDisplay??"0%",Xe=i?new Set(i.aiReferrals.map(te=>te.source.toLowerCase())).size:0,mt=pe[0]??null,Ze=i?.totalDirectSessions??0,jt=i?.directSharePctDisplay??"0%",at=i?.channelBreakdown?.direct.sessions??Ze,Ft=i?.channelBreakdown?.direct.sharePctDisplay??jt,Pt=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,k=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",xe=i?.socialSessions??0,Ke=i?.socialSharePctDisplay??"0%",Ie=i?.channelBreakdown?.social.sessions??xe,At=i?.channelBreakdown?.social.sharePctDisplay??Ke,ht=i?new Set(i.socialReferrals.map(te=>te.source.toLowerCase())).size:0,Ge=Ne[0]??null;return e.jsxs(e.Fragment,{children:[y&&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:y}),b&&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:b}),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})]})]})]}),!ie()&&!os()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ye(Se),children:[e.jsx(wa,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:f,onClick:Ye(Z),children:[e.jsx(tx,{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(Fe,{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(Gr,{value:Ba(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Gr,{value:Ba(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${ze} of total`,tone:"positive"}),e.jsx(Gr,{value:i.totalUsers===null?"—":Ba(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."}),!ie()&&!os()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ye(Se),children:[e.jsx(wa,{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(Fe,{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."})]})]}),Le&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Le.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Le.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),U.length>0&&e.jsxs(je,{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:V.length>0?"AI vs. total sessions":"All sessions (baseline)"}),V.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),V.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:zt,tickLine:!1,axisLine:{stroke:fs},tickFormatter:An}),e.jsx(dn,{tick:zt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(un,{...is,labelFormatter:It,formatter:(te,Be)=>{const Ee=typeof te=="number"?te.toLocaleString():String(te??0),Ae=String(Be??"");return Ae==="_totalSessions"?[Ee,"Total Sessions"]:Ae==="_organicSessions"?[Ee,"Organic Sessions"]:[Ee,Ae]}}),e.jsx(xr,{wrapperStyle:{fontSize:11,color:ys.text},formatter:te=>te==="_totalSessions"?"Total Sessions":te==="_organicSessions"?"Organic Sessions":te}),e.jsx(nn,{type:"monotone",dataKey:"_totalSessions",stroke:ys.textFaint,fill:ys.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),V.map((te,Be)=>e.jsx(nn,{type:"monotone",dataKey:te,stackId:"ai",stroke:tn[Be%tn.length],fill:tn[Be%tn.length],fillOpacity:.4,strokeWidth:1.5},te))]})})})]}),e.jsxs(je,{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(Ss,{label:"Organic",value:Ue,hint:`${dt.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(Ss,{label:"Social",value:At,hint:`${Ie.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(Ss,{label:"Direct",value:Ft,hint:`${at.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(Ss,{label:"Visitors from AI (at least)",value:Tt,hint:vt>0?`${de.toLocaleString()} sessions · ${vt.toLocaleString()} paid`:`${de.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(Ss,{label:"Other channels",value:k,hint:`${Pt.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."})]}),mt&&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:mt.source})," via ",mt.medium,", accounting for ",mt.sessions.toLocaleString()," sessions.",vt>0&&e.jsxs("span",{children:[" Paid AI: ",vt.toLocaleString()," sessions (",We,")."]})]})]}),e.jsxs(je,{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?`${Xe} 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:N,dir:P,onSort:Ce,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:N,dir:P,onSort:Ce,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:N,dir:P,onSort:Ce,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:pe.map(te=>e.jsx(Op,{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(je,{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:re})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:Pe.query,onChange:Pe.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Pe.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:F,dir:Q,onSort:be,align:"left"}),e.jsx(Et,{label:"Source",sortKey:"source",current:F,dir:Q,onSort:be,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:F,dir:Q,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:Pe.rows.map(te=>e.jsx(Fp,{row:te},`${te.landingPage}:${te.source}:${te.medium}:${te.sourceDimension}`))})]})}),e.jsx(Es,{page:Pe.page,pageSize:Pe.pageSize,visibleRows:Pe.rows.length,totalRows:Pe.totalRows,onPageChange:Pe.setPage,itemLabel:Pe.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:()=>Pe.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(Fe,{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(je,{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(Ss,{label:"Social Sessions",value:Ba(xe),hint:`${xe.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Ss,{label:"Share of Traffic",value:Ke,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Ss,{label:"Platforms",value:String(ht),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."})]}),Ge&&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:`${Ge.source} via ${Ge.medium}`,children:Uc(Qn(Ge.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Ge.medium,children:["via ",Qn(Ge.medium)," · ",Ge.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(Ss,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Ss,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Ss,{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."})]})]})]}),_e.length>0&&e.jsxs(je,{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 ",Oe.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:_e,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(cn,{dataKey:"date",tick:zt,tickLine:!1,axisLine:{stroke:fs},tickFormatter:An}),e.jsx(dn,{tick:zt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(un,{...is,labelFormatter:It,formatter:(te,Be)=>{const Ee=typeof te=="number"?te.toLocaleString():String(te??0),Ae=String(Be??"");if(Ae===zn)return[Ee,"Total Social"];if(Ae===Xn){const rt=`Other (${O} source${O===1?"":"s"})`;return[Ee,rt]}return[Ee,Qn(Ae)]}}),e.jsx(nn,{type:"monotone",dataKey:zn,stroke:Bc,fill:ys.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Oe.map((te,Be)=>{const Ae=te===Xn?Ni:tn[Be%tn.length];return e.jsx(nn,{type:"monotone",dataKey:te,stackId:"social",stroke:Ae,fill:Ae,fillOpacity:.4,strokeWidth:1.5},te)})]})})}),e.jsx(_p,{sources:Oe,otherCount:O})]}),e.jsxs(je,{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?Ne.length>oa&&!K?`Top ${oa} of ${Ne.length}`:`${Ne.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:X,onSort:J,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:S,dir:X,onSort:J,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:S,dir:X,onSort:J,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(K?Ne:Ne.slice(0,oa)).map(te=>e.jsx(Gp,{referral:te},`${te.source}:${te.medium}:${te.channelGroup}`))})]})}),Ne.length>oa&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>se(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:K?`Show top ${oa}`:`Show all ${Ne.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(Fe,{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(Hs,{value:_.query,onChange:_.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:v,dir:R,onSort:me,align:"left"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:v,dir:R,onSort:me,align:"right"}),e.jsx(Et,{label:"Organic",sortKey:"organicSessions",current:v,dir:R,onSort:me,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:_.rows.map(te=>e.jsx(Dp,{page:te},te.landingPage))})]})}),_.totalRows===0&&_.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Es,{page:_.page,pageSize:_.pageSize,visibleRows:_.rows.length,totalRows:_.totalRows,onPageChange:_.setPage,itemLabel:_.hasQuery?"matches":"pages"})]})]}),e.jsx(Mp,{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 ${gr(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}const qp=25,Vc="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 Yo(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 Jo(t){return t===null?Vc:t.toFixed(1)}function Xo(t){return t===null?Vc:Je(t)}function Mp({projectName:t}){const[s,n]=o.useState(Yd),[a,r]=o.useState("clicks"),[l,i]=o.useState("desc"),d=$e({...Jd({client:ne,path:{name:t},query:{window:s,limit:tu}}),staleTime:sn}),c=d.data,h=o.useMemo(()=>[...c?.rows??[]].sort((p,b)=>{const C=Yo(p,a),v=Yo(b,a);return C===null||v===null?C===v?0:C===null?1:-1:typeof C=="string"&&typeof v=="string"?l==="asc"?C.localeCompare(v):v.localeCompare(C):l==="asc"?C-v:v-C}),[c?.rows,a,l]),u=rn({rows:h,getSearchText:y=>Fi(kr(y.landingPage)),pageSize:qp});function m(y){u.setPage(1),a===y?i(p=>p==="desc"?"asc":"desc"):(r(y),i(y==="landingPage"?"asc":"desc"))}const f=c?.total??null,g=!ie()&&!os();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(Fe,{text:bt.tooltip})]}),c?.windowStart&&c.windowEnd&&e.jsxs("p",{className:"text-sm text-secondary mt-1",children:[mo(c.windowStart)," to ",mo(c.windowEnd),c.timeZone?` (${c.timeZone})`:""]})]}),e.jsx(qa,{windows:Xd,value:s,onChange:y=>{u.setPage(1),n(y)},label:bt.windowLabel})]}),d.isPending?e.jsx("p",{className:"text-sm text-secondary py-6 text-center",children:bt.loading}):d.isError||!c?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(A,{variant:"outline",size:"sm",onClick:()=>{d.refetch()},children:bt.retry})]}):e.jsxs(e.Fragment,{children:[(c.status==="error"||c.status==="unavailable"||c.subjectToThresholding)&&e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2","data-testid":"ga-search-landing-status",children:[c.status==="error"&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ge,{tone:"negative",children:bt.refreshFailedBadge}),c.error&&e.jsx(Fe,{text:c.error})]}),c.status==="unavailable"&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ge,{tone:"caution",children:bt.unavailableBadge}),c.error&&e.jsx(Fe,{text:c.error})]}),c.subjectToThresholding&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ge,{tone:"caution",children:bt.thresholdedBadge}),e.jsx(Fe,{text:bt.thresholded})]}),c.status!=="ready"&&f&&c.syncedAt&&e.jsxs("span",{className:"text-sm text-secondary",children:[bt.previousSnapshot," ",gr(c.syncedAt),"."]}),c.status==="unavailable"&&f&&e.jsx("p",{className:"w-full text-sm text-secondary",children:bt.unavailableAction})]}),f?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{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:m,align:"left"}),e.jsx(Et,{label:"Clicks",sortKey:"clicks",current:a,dir:l,onSort:m,align:"right"}),e.jsx(Et,{label:"Impressions",sortKey:"impressions",current:a,dir:l,onSort:m,align:"right"}),e.jsx(Et,{label:"CTR",sortKey:"ctr",current:a,dir:l,onSort:m,align:"right"}),e.jsx(Et,{label:"Avg. position",sortKey:"position",current:a,dir:l,onSort:m,align:"right"}),e.jsx(Et,{label:"Active users",sortKey:"activeUsers",current:a,dir:l,onSort:m,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:Xo(f.organicGoogleSearchClickThroughRate)}),e.jsx("td",{className:"py-1.5 text-right text-primary tabular-nums",children:Jo(f.organicGoogleSearchAveragePosition)}),e.jsx("td",{className:"py-1.5 text-right text-primary tabular-nums",children:f.activeUsers.toLocaleString()})]}),u.rows.map(y=>e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:kr(y.landingPage),children:kr(y.landingPage)}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:y.organicGoogleSearchClicks.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:y.organicGoogleSearchImpressions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:Xo(y.organicGoogleSearchClickThroughRate)}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:Jo(y.organicGoogleSearchAveragePosition)}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:y.activeUsers.toLocaleString()})]},y.landingPage))]})]})}),!Zd(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:c.totalRows>c.rows.length?bt.noFilterMatchInLoaded(c.rows.length):bt.noFilterMatch}),e.jsx(Es,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?"matches":"pages"}),(c.totalRows>c.rows.length||c.rowsCapped)&&e.jsxs("p",{className:"text-sm text-secondary mt-3",children:[c.totalRows>c.rows.length?`Showing the top ${c.rows.length.toLocaleString()} of ${c.totalRows.toLocaleString()} stored pages by clicks.`:"",c.totalRows>c.rows.length&&c.rowsCapped?" ":"",c.rowsCapped&&c.reportRowCount!==null?`GA4 reported ${c.reportRowCount.toLocaleString()} pages; the ${c.totalRows.toLocaleString()} with the most clicks are stored.`:""]}),c.syncedAt&&e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Synced ",gr(c.syncedAt)]})]}):e.jsx(je,{className:"p-5",children:c.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})]}):c.status==="error"?e.jsxs("div",{className:"text-sm text-secondary space-y-1",children:[e.jsx("p",{className:"text-neutral",children:bt.refreshFailed}),c.error&&e.jsx("p",{children:c.error})]}):e.jsxs("div",{className:"text-sm text-secondary space-y-1",children:[e.jsx("p",{className:"text-neutral",children:bt.neverSynced}),g&&e.jsx("p",{children:bt.neverSyncedAction})]})})]})]})]})}function Ep({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[r,l]=o.useState(null),[i,d]=o.useState(null),[c,h]=o.useState(!1),[u,m]=o.useState(null),f=o.useRef(null),g=o.useCallback(p=>{const b=p.target.files?.[0];if(!b)return;m(null),l(b.name);const C=new FileReader;C.onload=()=>{const v=C.result;try{const $=JSON.parse(v);if(!$.client_email||!$.private_key){m("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),d(null);return}d(v)}catch{m("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),d(null)}},C.onerror=()=>{m("Failed to read file."),d(null)},C.readAsText(b)},[]);async function y(){if(m(null),!n.trim()){m("Property ID is required.");return}if(!i){m("Please upload a service account key file.");return}h(!0);try{await eu(t,{propertyId:n.trim(),keyJson:i});try{await rc(t)}catch{}s()}catch(p){m(p instanceof Error?p.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(je,{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:p=>a(p.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:g,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(sx,{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(A,{variant:"default",size:"sm",disabled:c||!n.trim()||!i,onClick:Ye(y),children:c?"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 zc={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Gr({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 ${zc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Ss({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(Fe,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${zc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Dp({page:t}){const s=Je(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 Qc={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Hc={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 Op({referral:t}){const s=Je(t.share),n=Qc[t.sourceDimension]??t.sourceDimension,a=Hc[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 Fp({row:t}){const s=Qc[t.sourceDimension]??t.sourceDimension,n=Hc[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(cr,{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 Gp({referral:t}){const s=Je(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Qn(t.source),r=Qn(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 _p({sources:t,otherCount:s}){const n=[{key:zn,color:Bc,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Xn)n.push({key:Xn,color:Ni,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Qn(r);n.push({key:r,color:tn[a%tn.length]??Ni,label:Uc(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 Kp(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 Up="Search Console is not connected yet. Your Canonry team can set this up.",Bp=["7d","30d","90d","all"],Va=500,Zo=[{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:ea.caution,format:t=>Je(t)},{key:"position",label:"Avg position",color:ct[2],inverted:!0,format:t=>t.toFixed(1)}],Zs=25,Vp="canonry:google-oauth-complete";function zp(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],d=t.trailing[s];return i!==null&&d!==null&&i<=0&&d>0?`new in the last ${a}d`:i===null||i<=0?`no prior ${a}d to compare`:d===null?`no value in the last ${a}d`:"comparison unavailable"}return r===0?`→ no change vs prior ${a}d`:`${(n?r<0:r>0)?"↑":"↓"} ${Je(Math.abs(r))} vs prior ${a}d`}function Qp(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}`,d=`${r.startDate} to ${r.endDate}`,c=`Tile percentages compare these ${s} ${l} (${d}) with the ${s} ${l} before them (${i}).`;return n!=="split-window"?c:`${c} 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 el(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function tl(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 sl(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Hp({projectName:t,refreshNonce:s}){const n=bs(),{isAdmin:a}=Ys(),r=os(),[l,i]=o.useState(!1),[d,c]=o.useState([]),[h,u]=o.useState([]),[m,f]=o.useState([]),[g,y]=o.useState(null),[p,b]=o.useState([]),[C,v]=o.useState([]),[$,R]=o.useState(null),[x,N]=o.useState(""),[w,P]=o.useState(""),[q,S]=o.useState("30"),[G,X]=o.useState(!1),[T,F]=o.useState("30d"),[ae,Q]=o.useState(["clicks","impressions"]),[B,D]=o.useState(!0),[Y,E]=o.useState(null),[W,L]=o.useState(0),[ee,K]=o.useState({startDate:"",endDate:"",query:"",page:""}),[se,ce]=o.useState(0),[Se,Z]=o.useState(!1),[me,Ce]=o.useState(0),[J,he]=o.useState(!1),[_,pe]=o.useState(""),[Me,Pe]=o.useState(!0),[re,be]=o.useState(!1),[Ne,_e]=o.useState(!1),[Oe,O]=o.useState(!1),[U,V]=o.useState(!1),[Le,ze]=o.useState(!1),[Ue,dt]=o.useState(!1),[de,Tt]=o.useState(null),[vt,We]=o.useState(!1),[Xe,mt]=o.useState(!1),[Ze,jt]=o.useState(null),[at,Ft]=o.useState(null),[Pt,k]=o.useState([]),[xe,Ke]=o.useState(new Set),[Ie,At]=o.useState({}),[ht,Ge]=o.useState(new Set),[te,Be]=o.useState(""),[Ee,Ae]=o.useState(null),[rt,Zt]=o.useState(""),[es,Qt]=o.useState(!1),[St,ft]=o.useState(!1),[ls,it]=o.useState(!1),[vs,Fs]=o.useState(!1),[Nt,Gs]=o.useState("indexed"),[Lt,As]=o.useState(null),ts=!!(ee.query.trim()||ee.page.trim()||Lt),ss=Lt!==null,xt=o.useMemo(()=>{if(!Lt)return m;const{key:j,dir:H}=Lt;return[...m].sort((ue,we)=>{const st=j===Cn.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[j],tt=j===Cn.CTR?Number.isFinite(we.ctr)?we.ctr:0:we[j];return H==="asc"?st-tt:tt-st})},[m,Lt]),Ht=rn({rows:xt,pageSize:Vs}),ns=J?Ht.rows:xt,as=rn({rows:(Ze??[]).filter(j=>j.path.toLowerCase().includes(te.trim().toLowerCase())),pageSize:Vs}),[$t,js]=o.useState([]),[pt,yt]=o.useState(null),[Ns,_s]=o.useState(1),z=o.useMemo(()=>{if($t.length<2)return null;const j=$t[$t.length-1],H=$t[$t.length-2];return{indexed:j.indexed-H.indexed,notIndexed:j.notIndexed-H.notIndexed}},[$t]);o.useEffect(()=>{_s(1)},[de,Nt,pt]);const oe=o.useMemo(()=>pt?(de?.reasonGroups??[]).find(j=>j.reason===pt):void 0,[de,pt]),ke=o.useMemo(()=>de?Nt==="indexed"?de.indexed:Nt==="deindexed"?de.deindexed:Nt==="notIndexed"?pt?oe?.urls??[]:(de.reasonGroups??[]).length===0?de.notIndexed:[]:[]:[],[de,Nt,pt,oe]),le=Math.max(1,Math.ceil(ke.length/Zs)),Re=Math.min(Math.max(1,Ns),le),qe=(Re-1)*Zs,cs=o.useMemo(()=>de?.indexed.slice(qe,qe+Zs)??[],[de,qe]),wt=o.useMemo(()=>de?.notIndexed.slice(qe,qe+Zs)??[],[de,qe]),M=o.useMemo(()=>de?.deindexed.slice(qe,qe+Zs)??[],[de,qe]),ve=o.useMemo(()=>(oe?.urls??[]).slice(qe,qe+Zs),[oe,qe]),[et,Rt]=o.useState(!1),[qt,Ve]=o.useState(null),[gt,Ks]=o.useState(null),[Ma,rs]=o.useState(null),[ta,mn]=o.useState(null);function hn(j,H){const ue=gx(j),we=Kp(ue);we?(Ks(we),Ve(null)):(Ks(null),Ve(ue.message||H))}const Gt=d.find(j=>j.connectionType==="gsc"),Us=(Gt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),ds=Pt.length>0?Pt:(Ze??[]).map(j=>j.path),us=ds.filter(j=>Ze?.some(H=>H.path===j&&H.isSitemapsIndex)).length,xn=us===1?"Resubmit sitemap index":us>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ea=m.length>0||p.length>0||C.length>0,Js=su(),sa=nu();async function pn(j,H=!1){if(r){u([]);return}if(!j){u([]),N("");return}_e(!0);try{const{sites:ue}=await n.fetchQuery({...yu({client:ne,path:{name:t}}),staleTime:H?0:Bt});u(ue),N(j.propertyId??ue[0]?.siteUrl??""),Ks(null)}catch(ue){u([]),hn(ue,"Failed to load Search Console properties")}finally{_e(!1)}}async function Xs(j){V(!0);const H=j??se;try{const ue=ts?Va:Vs,we=ts?0:H,st={limit:String(ue)};ee.startDate&&(st.startDate=ee.startDate),ee.endDate&&(st.endDate=ee.endDate),ee.query&&(st.query=ee.query),ee.page&&(st.page=ee.page),we>0&&(st.offset=String(we)),T&&T!=="all"&&!ee.startDate&&(st.window=T);const tt=await n.fetchQuery({...ou({client:ne,path:{name:t},query:st}),staleTime:Bt}),ut=tt.rows;ts?(Z(!1),f(ut),Ce(ut.length),he(!0)):(Z(we+ut.length<tt.totalMatching),f(ut),Ce(0),he(!1))}catch(ue){f([]),Z(!1),Ce(0),Ve(ue instanceof Error?ue.message:"Failed to load GSC performance data")}finally{V(!1)}}async function gn(){try{const j={};ee.startDate&&(j.startDate=ee.startDate),ee.endDate&&(j.endDate=ee.endDate),T&&T!=="all"&&!ee.startDate&&(j.window=T);const H=await n.fetchQuery({...iu({client:ne,path:{name:t},query:j}),staleTime:Bt});y(H)}catch{y(null)}}async function Pn(j=!1){ze(!0);try{const H=_.trim()||void 0,ue={limit:"20"};H&&(ue.url=H);const[we,st]=await Promise.all([n.fetchQuery({...gu({client:ne,path:{name:t},query:ue}),staleTime:j?0:Bt}),n.fetchQuery({...fu({client:ne,path:{name:t}}),staleTime:j?0:Bt})]);b(we),v(st)}catch(H){b([]),v([]),Ve(H instanceof Error?H.message:"Failed to load GSC inspection history")}finally{ze(!1)}}async function In(j=!1){We(!0);try{const[H,ue]=await Promise.all([n.fetchQuery({...du({client:ne,path:{name:t}}),staleTime:j?0:Bt}),n.fetchQuery({...uu({client:ne,path:{name:t}}),staleTime:j?0:Bt}).catch(()=>[])]);Tt(H),js(ue)}catch(H){Tt(null),js([]),Ve(H instanceof Error?H.message:"Failed to load coverage data")}finally{We(!1)}}async function jr(j){Rt(!0),Ve(null);try{const H=await xo(t,{urls:j}),{succeeded:ue,failed:we,total:st}=H.summary;De({title:"Indexing requested",detail:we===0?`${ue} URL${ue!==1?"s":""} submitted for indexing.`:`${ue}/${st} submitted successfully, ${we} failed.`,tone:we===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(H){Ve(H instanceof Error?H.message:"Failed to request indexing")}finally{Rt(!1)}}async function io(){Rt(!0),Ve(null);try{const j=await xo(t,{urls:[],allUnindexed:!0}),{succeeded:H,failed:ue,total:we}=j.summary;De({title:"Indexing requested",detail:ue===0?`${H} unindexed URL${H!==1?"s":""} submitted for indexing.`:`${H}/${we} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(j){Ve(j instanceof Error?j.message:"Failed to request indexing")}finally{Rt(!1)}}async function Tn(){mt(!0),Ve(null);try{const j=await Ar(t);n.setQueryData(mu({client:ne,path:{name:t}}),j),jt(j.sitemaps),Ft(j.summary),k(j.preferredSubmissionUrls),Ke(new Set),At({}),j.sitemaps.length===0&&rs("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(j){Ve(j instanceof Error?j.message:"Failed to list sitemaps")}finally{mt(!1)}}async function Nr(j){const H=xe.has(j);if(Ke(ue=>{const we=new Set(ue);return H?we.delete(j):we.add(j),we}),!(H||Ie[j])){Ge(ue=>new Set(ue).add(j));try{const ue=await Ar(t,j);At(we=>({...we,[j]:ue.sitemaps}))}catch(ue){Ve(ue instanceof Error?ue.message:"Failed to load sitemap files")}finally{Ge(ue=>{const we=new Set(ue);return we.delete(j),we})}}}async function ms(j){if(!Us||j.length===0)return;const H=[...new Set(j)];ft(!0),Ve(null),Ae({completed:0,total:H.length});let ue=0,we=0,st=0,tt=null;try{for(let _t=0;_t<H.length;_t+=50){const ot=H.slice(_t,_t+50);try{const Te=await hu(t,ot);ue+=Te.summary.accepted,we+=Te.summary.failed,st+=ot.length,Ae({completed:st,total:H.length})}catch(Te){st+=ot.length;const ws=ot.length,Bs=H.length-st,Wt=Te instanceof Error?Te.message:"The batch request failed",Rs=`${ue} accepted, ${we} failed, ${ws} unconfirmed, ${Bs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;tt=`Sitemap submission stopped after a batch request failed. ${Rs} ${Wt}`,Ve(tt),De({title:"Sitemap resubmission partially completed",detail:Rs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const ut=H.length;De({title:we===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:we===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ue}/${ut} sitemap submissions; ${we} failed. Indexing is not guaranteed.`,tone:we===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Zt("")}catch(ut){Ve(ut instanceof Error?ut.message:"Failed to submit sitemap to Google")}finally{ft(!1),Ae(null),await Tn(),tt&&Ve(tt)}}async function Ln(){ft(!0);const j=Ze??[];try{const H=j.filter(we=>we.isSitemapsIndex),ue=[];for(let we=0;we<H.length;we+=4)(await Promise.all(H.slice(we,we+4).map(async tt=>{const ut=Ie[tt.path];if(ut)return ut;const _t=await Ar(t,tt.path);return At(ot=>({...ot,[tt.path]:_t.sitemaps})),_t.sitemaps}))).forEach((tt,ut)=>{ue.push(...tt.length>0?tt.map(_t=>_t.path):[H[we+ut].path])});await ms([...j.filter(we=>!we.isSitemapsIndex).map(we=>we.path),...ue])}catch(H){Ve(H instanceof Error?H.message:"Failed to load sitemap files"),ft(!1)}}async function $n(j){Qt(!0),Ve(null);try{await xu(t,"gsc",j),await Dt(n,"google"),c(H=>H.map(ue=>ue.connectionType==="gsc"?{...ue,sitemapUrl:j}:ue)),De({title:"Default sitemap updated",detail:j,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(H){Ve(H instanceof Error?H.message:"Failed to set the default sitemap")}finally{Qt(!1)}}async function fn(j){try{await sa.mutateAsync({projectName:t,projectLabel:t,opts:j?{sitemapUrl:j}:void 0})}catch{}}async function na(){try{const H=(await n.fetchQuery({...oc({client:ne,path:{name:t},query:{kind:Ds["gsc-sync"],limit:1}}),staleTime:Bt}))[0];mn(H?.status===Cs.failed&&H.error?`Last saved Search Console sync failed: ${vu(H.error)}`:null)}catch{mn("Saved Search Console sync status is unavailable.")}}async function qn(){Pe(!0),Ve(null);try{const[j,H]=await Promise.all([r||!a?Promise.resolve(null):ic().catch(()=>null),n.fetchQuery({...Mi({client:ne,path:{name:t}}),staleTime:Bt}).catch(()=>[])]);i(!!j?.google?.configured),c(H);const ue=H.find(we=>we.connectionType==="gsc");N(ue?.propertyId??""),await Promise.all([!r&&ue&&!ue.propertyId?pn(ue):Promise.resolve(),!r&&ue?na():Promise.resolve(),Xs(),gn(),Pn(),In()])}finally{Pe(!1)}}o.useEffect(()=>{u([]),it(!1),jt(null),Ft(null),k([]),mn(null),Ks(null),rs(null)},[t]),o.useEffect(()=>{qn()},[t,s,a]),o.useEffect(()=>{ce(0),E(null),K(j=>j.startDate||j.endDate?{...j,startDate:"",endDate:""}:j),L(j=>j+1),gn()},[T]);const aa=o.useRef(!1);o.useEffect(()=>{if(!aa.current){aa.current=!0;return}ce(0),Ht.setPage(1),Xs(0)},[W]);function ra(j){const H=Y===j?null:j;E(H),K(ue=>({...ue,startDate:H??"",endDate:H??""})),L(ue=>ue+1)}const Da=o.useRef(!1);o.useEffect(()=>{if(!Da.current){Da.current=!0;return}ce(0),Xs(0)},[ss]);async function wr(){if(!l){Ve("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}be(!0),Ve(null),rs(null);try{let j=function(Te){if(Te.source!==we||Te.origin!==st||!Te.data||typeof Te.data!="object")return;const ws=Te.data;ws.type!==Vp||ws.connectionType!=="gsc"||ot(!0)};const{authUrl:H,redirectUri:ue}=await cu(t,"gsc");if(!H.startsWith("https://accounts.google.com/")){Ve("Unexpected OAuth redirect URL. Please try again.");return}const we=window.open(H,"_blank","width=600,height=700");if(!we){window.location.assign(H);return}const st=ue?new URL(ue).origin:window.location.origin;let tt=!1,ut=null;const _t=()=>{ut!==null&&window.clearInterval(ut),window.removeEventListener("message",j)},ot=async Te=>{if(!tt){tt=!0,_t(),rs(Te?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Dt(n,"google"),await qn()}finally{rs(null)}}};window.addEventListener("message",j),rs("Finish the Google consent flow in the popup. This page will refresh automatically."),ut=window.setInterval(()=>{we.closed&&ot(!1)},1e3)}catch(j){Ve(j instanceof Error?j.message:"Failed to start OAuth flow")}finally{be(!1)}}async function Mn(){Ve(null),rs(null);try{await lu(t,"gsc"),await Dt(n,"google"),c(j=>j.filter(H=>H.connectionType!=="gsc")),u([]),N("")}catch(j){Ve(j instanceof Error?j.message:"Failed to disconnect")}}async function ia(){if(x){O(!0),Ve(null);try{await bu(t,"gsc",x),await Dt(n,"google"),c(j=>j.map(H=>H.connectionType==="gsc"?{...H,propertyId:x}:H)),De({title:"GSC property updated",detail:`${t} is now linked to ${x}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(j){Ve(j instanceof Error?j.message:"Failed to save GSC property")}finally{O(!1)}}}async function Oa(){Ve(null),rs(null);try{await Js.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(q,10)||void 0,full:G||void 0}}),await Dt(n,"gsc")}catch{}}async function Fa(){if(w.trim()){dt(!0),Ve(null),rs(null);try{const j=await pu(t,w.trim());await Dt(n,"gsc"),R(j),P(""),await Pn()}catch(j){Ve(j instanceof Error?j.message:"Failed to inspect URL")}finally{dt(!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"})]})}),ta&&e.jsx("p",{role:"status",className:"mb-3 text-sm text-caution",children:ta}),gt&&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:gt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:gt.message}),(En(gt.enableUrl)||En(gt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[En(gt.enableUrl)&&e.jsx("a",{href:En(gt.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 ↗"}),En(gt.indexingApiUrl)&&e.jsx("a",{href:En(gt.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:()=>Ks(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:()=>Ve(null),children:"×"})]}),Ma&&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:[Ma,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>rs(null),children:"×"})]}),Me?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Gt?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:Gt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",de?.lastInspectedAt?Xt(de.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ye(Mn),children:"Disconnect"})]}):a?e.jsxs(je,{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(ge,{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(A,{type:"button",variant:"outline",size:"sm",disabled:re,onClick:Ye(wr),children:re?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ks,{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(je,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:Up})}),(Gt||Ea)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(je,{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(Fe,{text:`${Qp(g?.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 ${Va.toLocaleString()} matching rows while the table shows ${Vs} per page.`})]}),g?.window?.startDate&&g.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[g.window.startDate," to ",g.window.endDate,(g.window.daysSinceLatestData??0)>0&&` · latest data ${g.window.daysSinceLatestData} day${g.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{windows:Bp,value:T,onChange:j=>{F(j),ce(0),Ht.setPage(1)},label:"Search Console time period",formatOption:j=>j==="all"?"All":j}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:U,onClick:()=>{ce(0),Ht.setPage(1),Xs(0),gn()},children:U?"Loading…":"Apply filters"})]})]}),g&&g.daily.length>0&&(()=>{const{totals:j,daily:H,trends:ue,periodComparison:we}=g,tt=Zo.filter(Te=>ae.includes(Te.key)).map(Te=>({dataKey:Te.key,label:Te.label,color:Te.color,axisId:Te.key,inverted:Te.inverted,formatValue:Te.format,trend:B?ue?.[Te.key]??null:null})),ut=Te=>j[Te]??null,_t=new Map(H.map(Te=>[Te.date,Te])),ot=H.length===0?[]:au(H[0].date,H[H.length-1].date).map(Te=>_t.get(Te)??{date:Te});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Zo.map(Te=>{const ws=ae.includes(Te.key),Bs=ut(Te.key),Wt=Bs===null;return e.jsxs("button",{type:"button","aria-pressed":ws,disabled:Wt,className:`rounded-md border px-3 py-2 text-left transition-colors ${ws?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Wt?"cursor-not-allowed opacity-50":""}`,onClick:()=>{Q(Rs=>Rs.includes(Te.key)?Rs.length===1?Rs:Rs.filter(Sr=>Sr!==Te.key):[...Rs,Te.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:ws?Te.color:"transparent",border:`1px solid ${Te.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Te.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Bs===null?"—":Te.format(Bs)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:zp(we,Te.key,Te.inverted)})]},Te.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:B,onChange:Te=>D(Te.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(kc,{data:ot,xKey:"date",series:tt,xTickFormatter:An,labelFormatter:It,onSelectX:ra,selectedX:Y})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:H.map(Te=>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":Y===Te.date,onClick:()=>ra(Te.date),children:[It(Te.date),": ",Te.clicks," clicks, ",Te.impressions," impressions"]},Te.date))}),Y&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",It(Y)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ra(Y),children:["Show all ",j.days," days"]})]}),j.position!==null&&(j.positionDays??j.days)<j.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",j.positionDays," of ",j.days," days. The rest have no property-level position recorded."]}),(j.position===null||j.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:j=>K(H=>({...H,startDate:j.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:j=>K(H=>({...H,endDate:j.target.value}))}),e.jsx(Hs,{value:ee.query,onChange:j=>K(H=>({...H,query:j})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Hs,{value:ee.page,onChange:j=>K(H=>({...H,page:j})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),m.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(Cn).map(j=>e.jsx("th",{className:"text-right","aria-sort":Lt?.key===j?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),As(H=>H?.key===j?H.dir==="desc"?{key:j,dir:"asc"}:null:{key:j,dir:"desc"})},children:[ru[j],Lt?.key===j?Lt.dir==="desc"?" ↓":" ↑":""]})},j))]})}),e.jsx("tbody",{children:ns.map((j,H)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:j.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:j.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(cr,{value:j.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:j.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.impressions.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Je(j.ctr)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.position.toFixed(1)})]},`${j.date}:${j.query}:${j.page}:${H}`))})]})}),e.jsx(Es,{page:J?Ht.page:Math.floor(se/Vs)+1,pageSize:Vs,visibleRows:ns.length,totalRows:J?me:void 0,hasNextPage:J?void 0:Se,disabled:U,itemLabel:J?"matches":"rows",onPageChange:j=>{if(J){Ht.setPage(j);return}const H=(j-1)*Vs;ce(H),Xs(H)}}),J&&me>=Va?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Va.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(je,{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(Fe,{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:[de&&de.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:et,onClick:()=>{io()},children:et?"Requesting…":`Request indexing (${de.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:vt,onClick:()=>{In(!0)},children:vt?"Loading…":"Reload saved coverage"})]})]}),de&&de.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const j=de.summary.indexedShare??0,H=de.summary.notIndexedShare??0,ue=54,we=2*Math.PI*ue,st=we*(1-j),tt=we*H,ut=we*j;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:ue,fill:"none",stroke:ys.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ue,fill:"none",stroke:ea.positiveDeep,strokeWidth:"14",strokeDasharray:we,strokeDashoffset:st,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),de.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ue,fill:"none",stroke:ys.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${we-tt}`,strokeDashoffset:-ut,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:Je(de.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:de.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:de.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(de.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(de.reasonGroups??[]).length," ",(de.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),de.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:de.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(j=>{const H=j==="indexed"?de.indexed.length:j==="notIndexed"?de.notIndexed.length:de.deindexed.length,ue=j==="indexed"?"Indexed":j==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Nt===j,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Nt===j?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Gs(j),yt(null)},children:[ue," (",H,")"]},j)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Nt==="indexed"&&de.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:cs.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.crawlTime?j.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:j.isMobileFriendly===!0?"Yes":j.isMobileFriendly===!1?"No":"—"})]},j.id))})]}),Nt==="notIndexed"&&!pt&&(de.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:(de.reasonGroups??[]).map(j=>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:()=>yt(j.reason),onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),yt(j.reason))},tabIndex:0,role:"button","aria-label":`View ${j.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:j.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.count})]},j.reason))})]}),Nt==="notIndexed"&&!pt&&(de.reasonGroups??[]).length===0&&de.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:wt.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.coverageState??"Unknown"})]},j.id))})]}),Nt==="notIndexed"&&pt&&(()=>{const j=(de.reasonGroups??[]).find(H=>H.reason===pt);return j?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:()=>yt(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:j.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[j.count," affected page",j.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:et,onClick:()=>{jr(j.urls.map(H=>H.url))},children:et?"Requesting…":`Request indexing (${j.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:ve.map(H=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:H.url}),e.jsx("td",{className:"text-secondary",children:H.crawlTime?H.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:et,onClick:()=>{jr([H.url])},title:"Request indexing",children:"Index"})})]},H.id))})]})]}):null})(),Nt==="deindexed"&&de.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:M.map((j,H)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.previousState}),e.jsx("td",{className:"text-secondary",children:j.currentState}),e.jsx("td",{className:"text-secondary",children:j.transitionDate.split("T")[0]})]},`${j.url}-${H}`))})]}),(Nt==="indexed"&&de.indexed.length===0||Nt==="notIndexed"&&!pt&&de.notIndexed.length===0||Nt==="deindexed"&&de.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Es,{page:Re,pageSize:Zs,visibleRows:Math.min(Zs,ke.length-qe),totalRows:ke.length,onPageChange:_s,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":vs,onClick:()=>Fs(j=>!j),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:vs?"Hide snapshots":$t.length>0?`View ${$t.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",de.summary.indexed.toLocaleString()," indexed, ",de.summary.notIndexed.toLocaleString()," not indexed.",z&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",z.indexed>=0?"+":"",z.indexed.toLocaleString()," indexed, ",z.notIndexed>=0?"+":"",z.notIndexed.toLocaleString()," not indexed."]})]}),vs&&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(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:j.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:j.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.notIndexed.toLocaleString()})]},j.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:vt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(je,{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(Fe,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Xe||!Gt?.propertyId,onClick:()=>{Tn()},children:Xe?"Loading…":Ze===null?"Load from Google":"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:rt,onChange:j=>Zt(j.target.value),onKeyDown:j=>j.key==="Enter"&&void ms([rt.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!Us||St||!rt.trim(),onClick:()=>{ms([rt.trim()])},children:St?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!Us||St||ds.length===0,onClick:()=>{ms(ds)},children:St?"Resubmitting…":xn}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!Us||St||!Ze?.length,onClick:()=>{Ln()},children:"Resubmit all files"}),at&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",at.indexes," index",at.indexes===1?"":"es",", ",at.files," file",at.files===1?"":"s"]}),Ee&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Ee.completed,"/",Ee.total]})]}),!Us&&Gt&&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:Ye(wr),children:"Reconnect"})]}),Ze===null&&e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"Load sitemaps from Google to view them and enable resubmission."}),Ze&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Ze.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:te,onChange:j=>{Be(j),as.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:as.rows.flatMap(j=>{const H=el(j),ue=tl(j),we=sl(j),st=Ie[j.path]??[],tt=xe.has(j.path),ut=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(cr,{value:j.path})}),e.jsx("td",{className:"text-secondary",children:j.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":tt,"aria-label":`${tt?"Collapse":"Expand"} files in ${j.path}`,onClick:()=>{Nr(j.path)},children:ht.has(j.path)?"Loading…":`${tt?"▾":"▸"} Index${Ie[j.path]?` (${st.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:we}),e.jsx("td",{className:"text-secondary",children:j.lastSubmitted?j.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:j.lastDownloaded?j.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:H.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ue||"—"}),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:!Us||St,onClick:()=>{ms([j.path])},children:j.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Gt?.sitemapUrl===j.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:es,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{$n(j.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:sa.isPending,onClick:()=>{fn(j.path)},children:"Inspect URLs"})]})})]},j.path),_t=j.isSitemapsIndex&&tt?st.map(ot=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(cr,{value:ot.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:sl(ot)}),e.jsx("td",{className:"text-secondary",children:ot.lastSubmitted?ot.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ot.lastDownloaded?ot.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:el(ot).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:tl(ot)||"—"}),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:!Us||St,onClick:()=>{ms([ot.path])},children:"Resubmit"}),Gt?.sitemapUrl===ot.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:es,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{$n(ot.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:sa.isPending,onClick:()=>{fn(ot.path)},children:"Inspect URLs"})]})})]},`${j.path}:${ot.path}`)):[];return[ut,..._t]})})]}),e.jsx(Es,{page:as.page,pageSize:Vs,visibleRows:as.rows.length,totalRows:as.totalRows,onPageChange:as.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(je,{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:j=>P(j.target.value),onKeyDown:j=>j.key==="Enter"&&void Fa()}),e.jsx(A,{type:"button",size:"sm",disabled:Ue||!Gt?.propertyId||!w.trim(),onClick:Ye(Fa),children:Ue?"Inspecting…":"Inspect URL"})]}),$&&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:$.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:$.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:ho($.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($.crawlTime)})]})]})]})]}),e.jsxs(je,{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(A,{type:"button",variant:"outline",size:"sm",disabled:Le,onClick:()=>{Pn(!0)},children:Le?"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:_,onChange:j=>pe(j.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Le,onClick:()=>{Pn(!0)},children:"Apply filter"})]}),p.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:p.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-neutral",children:j.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:ho(j.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Xt(j.inspectedAt)})]},j.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(je,{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(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:j.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Xt(j.transitionDate)})]},`${j.url}:${j.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Gt&&!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:()=>{ls||pn(Gt),it(j=>!j)},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 ${ls?"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"})]})}),ls&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(je,{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(Fe,{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:x,disabled:Ne||h.length===0,onChange:j=>N(j.target.value),children:h.length===0?e.jsx("option",{value:"",children:Ne?"Loading properties…":"No properties available"}):h.map(j=>e.jsxs("option",{value:j.siteUrl,children:[j.siteUrl," · ",j.permissionLevel]},j.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Ne,onClick:()=>{pn(Gt,!0)},children:Ne?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!x||Oe,onClick:Ye(ia),children:Oe?"Saving…":"Save property"})]})]})]}),e.jsxs(je,{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:j=>S(j.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:G,onChange:j=>X(j.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:Js.isPending||!Gt.propertyId,onClick:Ye(Oa),children:Js.isPending?"Queueing…":"Queue sync"}),!Gt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Wp=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Yp({projectName:t,projectId:s}){const n=bs(),[a,r]=o.useState(null),[l,i]=o.useState(null),[d,c]=o.useState(!1),h=$e(Mi({client:ne,path:{name:t}})),u=h.data?.find(Z=>Z.connectionType==="gbp"),m=!!u,f=a?{locationName:a}:void 0,g=$e({...ju({client:ne,path:{name:t}}),enabled:m}),y=$e({...Nu({client:ne,path:{name:t},query:f}),enabled:m}),p=$e({...wu({client:ne,path:{name:t},query:f}),enabled:m}),b=$e({...Su({client:ne,path:{name:t},query:f}),enabled:m}),C=$e({...Cu({client:ne,path:{name:t},query:f}),enabled:m}),v=$e({...ku({client:ne,path:{name:t},query:f}),enabled:m}),$=$e({queryKey:["gbp-section-insights",t],queryFn:()=>Au(t),enabled:m});function R(){Dt(n,"gbp")}const x=Kt({...Ru(),onSuccess:Z=>{lc({id:Z.runId,projectId:s,kind:Ds["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),De({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),N=o.useSyncExternalStore(cc,ur,ur),w=Object.values(N.runs).some(Z=>Z.kind===Ds["gbp-sync"]&&Z.projectId===s),P=x.isPending||w,q=Kt({...Pu(),onSuccess:()=>R()});if(o.useEffect(()=>{if(!a||!g.data)return;const Z=g.data.locations.filter(me=>me.selected);(Z.length<=1||!Z.some(me=>me.locationName===a))&&r(null)},[a,g.data]),o.useEffect(()=>{if(!l||!g.data)return;(a?[a]:g.data.locations.filter(me=>me.selected).map(me=>me.locationName)).includes(l)||i(null)},[l,g.data,a]),h.isLoading)return null;if(!u){const Z=[{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(je,{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:Z.map((me,Ce)=>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:Ce+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:me.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:me.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:me.note})]})]},me.title))})]})})}const S=y.data,G=g.data?.locations??[],X=G.filter(Z=>Z.selected),T=p.data?.keywords??[],F=b.data?.lodging??[],ae=C.data?.placeActions??[],Q=v.data?.places??[],B=G.length>0?G[0].accountName:u.domain,D=a?G.find(Z=>Z.locationName===a)?.displayName??null:null,Y=a?G.filter(Z=>Z.locationName===a):X,E=new Set(Y.map(Z=>Z.locationName)),W=F.filter(Z=>E.has(Z.locationName)),L=ae.filter(Z=>E.has(Z.locationName)),ee=Q.filter(Z=>E.has(Z.locationName)),K=new Set(X.map(Z=>Z.locationName)),se=a?T:T.filter(Z=>K.has(Z.locationName)),ce=!a&&X.length>1,Se=($.data??[]).filter(Z=>!Z.dismissed&&Wp.has(Z.type)&&(!D||Z.query===D||Z.query===a||Z.title.startsWith(D)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(je,{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(Fe,{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(ge,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(He,{type:"button",variant:"outline",size:"sm",disabled:P,onClick:()=>x.mutate({client:ne,path:{name:t},body:{}}),children:P?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[B?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:B})," · "]}):null,g.data?`${g.data.totalSelected} of ${g.data.totalDiscovered} locations tracked`:"Loading locations…"]}),X.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:Z=>r(Z.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"}),X.map(Z=>e.jsx("option",{value:Z.locationName,children:Z.displayName},Z.id))]})]}),X.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:[Se.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Se.map(Z=>e.jsx("div",{className:["insight-card",cg(Z.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:[Z.title,Z.recommendation?.reason&&e.jsx(Fe,{text:Z.recommendation.reason})]})},Z.id))]}),S&&e.jsx(hg,{performance:S.performance,freshness:S.freshness,timeseries:S.timeseries}),S?.profileCompleteness&&e.jsx(Jp,{summary:S.profileCompleteness}),Y.length>0&&e.jsx(Xp,{locations:Y,lodging:W,places:ee,placeActions:L,expandedLocation:l,onToggleExpanded:Z=>{i(me=>me===Z?null:Z)}}),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"}),p.data&&p.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[Je(p.data.thresholdedPct,Zn.percent)," privacy-thresholded"]})]}),se.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"}),ce&&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:se.slice(0,25).map(Z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:Z.keyword}),ce&&e.jsx("td",{className:"text-muted",children:G.find(me=>me.locationName===Z.locationName)?.displayName??Z.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:Z.valueCount!==null?Z.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",Z.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[Z.periodStart,"–",Z.periodEnd]})]},`${Z.locationName}:${Z.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:()=>c(Z=>!Z),"aria-expanded":d,children:[e.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"})," Manage locations (",G.length,")"]}),d&&e.jsx("div",{className:"mt-3",children:G.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"}),!ie()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:G.map(Z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:Z.displayName}),e.jsx("td",{className:"text-muted",children:Z.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ge,{tone:Z.selected?"positive":"neutral",children:Z.selected?"Tracked":"Not tracked"})}),!ie()&&e.jsx("td",{className:"text-right",children:e.jsx(He,{type:"button",variant:"outline",size:"sm",disabled:q.isPending,onClick:()=>q.mutate({client:ne,path:{name:t,locationName:Z.locationName},body:{selected:!Z.selected}}),children:Z.selected?"Untrack":"Track"})})]},Z.id))})]})})]})]})})}function Jp({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:la(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:la(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:la(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:la(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:la(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(Fe,{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 ${lg(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Xp({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(h=>[h.locationName,h])),d=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const u=c.get(h.locationName)??[];u.push(h),c.set(h.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(Fe,{text:ie()?"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(h=>{const u=i.get(h.locationName)??null,m=d.get(h.locationName)??null,f=c.get(h.locationName)??[],g=r===h.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:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ge,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ge,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Wc(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(eg,{location:h})}),e.jsx("td",{children:e.jsx(tg,{lodging:u})}),e.jsx("td",{children:e.jsx(ng,{place:m,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(rg,{actions:f})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>l(h.locationName),children:g?"Hide":"Details"})})]}),g&&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(og,{location:h,lodging:u,place:m,placeActions:f})})})]},h.id)})})]})})]})}function Zp(t){return[{label:"Description",tone:Sn(t.description)?"positive":"neutral",value:Sn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Sn(t.primaryPhone)?"positive":"neutral",value:Sn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Sn(t.websiteUri)?"positive":"neutral",value:Sn(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 eg({location:t}){const s=Zp(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ge,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function tg({lodging:t}){return e.jsx(Ki,{...sg(t)})}function sg(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 ng({place:t,mapsUri:s}){return e.jsx(Ki,{...ag(t,s)})}function ag(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 rg({actions:t}){return e.jsx(Ki,{...ig(t)})}function ig(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 Ki({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ge,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function og({location:t,lodging:s,place:n,placeActions:a}){const r=s?ug(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(_r,{title:"Owner profile · Business Information",children:[e.jsx(Yt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Yt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Yt,{label:"Description",value:Sn(t.description)?t.description:"Not returned"}),e.jsx(Yt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Yt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Yt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Yt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Yt,{label:"Open status",value:Wc(t.openStatus)}),e.jsx(Yt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(_r,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Yt,{label:"Last checked",value:nl(s.syncedAt)}),e.jsx(Yt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Yt,{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(_r,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Yt,{label:"Places tier",value:n.tier}),e.jsx(Yt,{label:"Last checked",value:nl(n.syncedAt)}),e.jsx(Yt,{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:[fr(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[fr(l.providerType),l.uri?` · ${dg(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function _r({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 Yt({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 la(t,s,n){return t===s?"positive":t===0?n:"caution"}function lg(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function cg(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Sn(t){return typeof t=="string"&&t.trim().length>0}function Wc(t){return t?fr(t):"Not returned"}function fr(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function dg(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function nl(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ug(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&mg(n)).map(([s])=>fr(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function mg(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function hg({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Iu.filter(y=>(a[y]??0)>0),l=Tu.filter(y=>(a[y]??0)>0),i=Object.keys(a).filter(y=>(a[y]??0)>0&&Lu(y)==="other").sort((y,p)=>(a[p]??0)-(a[y]??0)),d=Object.keys(a).filter(y=>(a[y]??0)===0).sort(),c=n.map(y=>{const p={date:y.date};for(const[b,C]of Object.entries(y.metrics))p[b]=C;return p}),h=n.find(y=>y.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,m=c.length>0,f=s.dataThroughDate?`Data through ${It(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,g=[...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})]}),!m||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(al,{data:c,metrics:r,kind:"line",firstPending:h,lastDate:u}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:g.map(y=>e.jsxs("span",{className:"text-sm text-secondary",children:[mr(y)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[y]??0).toLocaleString()})]},y))})]})]}),m&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(al,{data:c,metrics:l,kind:"area",firstPending:h,lastDate:u})]}),d.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",d.map(y=>mr(y)).join(", ")]})]})}function al({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(Sa,{stroke:Na,vertical:!1}),e.jsx(cn,{dataKey:"date",tick:zt,tickLine:!1,axisLine:{stroke:fs},tickFormatter:An,minTickGap:24}),e.jsx(dn,{tick:zt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(un,{...is,labelFormatter:It,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),mr(String(i??""))]}),e.jsx(xr,{wrapperStyle:{fontSize:11,color:ys.text},formatter:l=>mr(l)}),a&&r&&e.jsx(ui,{x1:a,x2:r,fill:ys.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:ys.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Qs,{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 xg(t){return Xh(Ot(String(t)))}function pg(t){return Pa(Ot(String(t)))}const za=Vs;function Dn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Kr(t){return t.toLocaleString()}function gg(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 fg(t){const s=t.filter(n=>n.kind===Ds["backlink-extract"]&&!dc(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function yg(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 bg({projectName:t}){const s=os(),[n,a]=o.useState(null),[r,l]=o.useState(null),[i,d]=o.useState([]),[c,h]=o.useState(null),[u,m]=o.useState(null),[f,g]=o.useState(null),[y,p]=o.useState(Date.now()),[b,C]=o.useState(0),[v,$]=o.useState(!0),[R,x]=o.useState(!1),[N,w]=o.useState(null),P=o.useCallback(async()=>{$(!0),w(null);try{const[D,Y,E,W,L]=await Promise.all([$u().catch(()=>null),qu(t,{excludeCrawlers:!0}).catch(()=>null),Mu(t,{limit:za,offset:b,excludeCrawlers:!0}).catch(K=>{if(K instanceof ii&&K.code==="NOT_FOUND")return null;throw K}),Eu(t).catch(()=>[]),Du(t).catch(()=>[])]);h(D),a(Y),l(E),d(W);const ee=fg(L);m(ee)}catch(D){w(D instanceof Error?D.message:"Failed to load backlinks")}finally{$(!1)}},[t,b]);o.useEffect(()=>{P()},[P]),o.useEffect(()=>{if(!u)return;const D=u.id;let Y=!1;const E=async()=>{try{const L=await oi(D);if(Y)return;dc(L.status)?(m(null),g(L),await P()):m(ee=>ee?.id===L.id?{...ee,...L}:ee)}catch{}},W=window.setInterval(()=>{E()},3e3);return()=>{Y=!0,window.clearInterval(W)}},[u,P]),o.useEffect(()=>{if(!u)return;const D=window.setInterval(()=>p(Date.now()),1e3);return()=>window.clearInterval(D)},[u]),o.useEffect(()=>{if(!f||f.status==="failed")return;const D=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(D)},[f]);async function q(){x(!0),w(null);try{const D=await Fu(t);m(D)}catch(D){D instanceof ii&&D.code==="MISSING_DEPENDENCY"?w("DuckDB is not installed. Visit the Backlinks admin page to install it."):w(D instanceof Error?D.message:"Failed to trigger extract")}finally{x(!1)}}const S=o.useMemo(()=>i.slice().sort((D,Y)=>D.queriedAt.localeCompare(Y.queriedAt)).map(D=>({date:D.queriedAt,linkingDomains:D.totalLinkingDomains})),[i]),G=r?.rows??[],X=r?.total??0,T=n?.excludedLinkingDomains??0,F=Math.floor(b/za)+1;return o.useEffect(()=>{b>0&&b>=X&&C(0)},[b,X]),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"})]})}),N&&e.jsx(je,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:N})}),u&&e.jsx(je,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(nx,{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(ge,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[yg(u.startedAt??null,u.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",y]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),f&&!u&&e.jsx(je,{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(ax,{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:Ou(f.error)}):f.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),ae()]});function ae(){return v?e.jsx(je,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):Q()}function Q(){const D=n!==null&&n.totalLinkingDomains>0,Y=f?.status==="failed",E=n!==null&&n.totalLinkingDomains===0&&!Y,W=c?.status==="ready",L=c?.status==="failed",ee=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return D?B(e.jsxs(e.Fragment,{children:[!ie()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:R||u!==null,onClick:Ye(q),children:[e.jsx(ix,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":R?"Queuing…":"Re-run extract"]}),e.jsx($r,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ie()&&!s&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Dn("/backlinks"),children:"Open admin"})})]})):e.jsx(je,{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(rx,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!c&&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."}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dn("/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 (",c.status,c.phaseDetail?` — ${c.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Dn("/backlinks"),children:"View sync status"})})})]}),L&&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:c.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dn("/backlinks"),children:"Go to Backlinks admin"})})})]}),W&&!ee&&!E&&!Y&&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:c.release})," is ready. Run an extract for this project."]}),!ie()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:R||u!==null,onClick:Ye(q),children:[e.jsx(hr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":R?"Queuing…":"Run extract"]}),e.jsx($r,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Y&&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."}),!ie()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dn("/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."]}),!ie()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:R||u!==null,onClick:Ye(q),children:[e.jsx(hr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":R?"Queuing…":"Re-run extract"]}),e.jsxs($r,{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 B(D){if(!n)return null;const Y="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:Kr(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:Kr(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:Je(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 ",gg(n.queriedAt),T>0&&e.jsxs(e.Fragment,{children:[" · ",T," excluded domain",T===1?"":"s"]})]}),S.length>=2&&e.jsxs(je,{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:zt,stroke:fs,tickFormatter:xg}),e.jsx(dn,{tick:zt,stroke:fs,allowDecimals:!1}),e.jsx(un,{contentStyle:is.contentStyle,labelStyle:is.labelStyle,itemStyle:is.itemStyle,labelFormatter:pg}),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(je,{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:Y})]})}),e.jsxs("tbody",{children:[G.map(L=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:L.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Kr(L.numHosts)})]},L.linkingDomain)),G.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:T>0&&X===0?`Every referring domain in this ${W} was a crawler/proxy host (${T} hidden).`:`No referring domains in this ${W}.`})})]})]})}),e.jsx(Es,{page:F,pageSize:za,visibleRows:G.length,totalRows:X,onPageChange:L=>C((L-1)*za)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:D})]})}}const vg=["non-brand","branded","unclassified"],rl={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function jg(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function Ng(t,s){const n=[...new Set(t.byQuery.flatMap(i=>i.providers.map(d=>d.provider)))].sort(),a=new Map,r=i=>{const d=s(i)??"unclassified";let c=a.get(d);return c||(c={key:d,queries:0,unanswered:0,engines:n.map(h=>({provider:h,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},a.set(d,c)),c},l=new Map;for(const i of t.byQuery){const d=r(i.query);if(i.providers.length===0){d.unanswered++;continue}d.queries++;for(const u of i.providers){l.set(`${i.queryId}::${u.provider}`,i.query);const m=d.engines.find(f=>f.provider===u.provider);m.answered++,u.mentioned&&m.mentioned++,u.cited&&m.cited++,d.answers++}const c=i.providers.some(u=>u.cited),h=i.providers.some(u=>u.mentioned);c&&h?d.citedAndNamed++:c?d.citedNotNamed++:h?d.namedNotCited++:d.neither++}for(const i of t.competitorGaps){const d=l.get(`${i.queryId}::${i.provider}`);if(d===void 0)continue;const c=r(d);c.competitorCited++,c.competitorGaps.push({query:d,provider:i.provider,competitors:i.citingCompetitors})}return vg.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function wg(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 Sg={engine:"engine no longer configured",query:"query no longer tracked"},il={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},Cg="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 On(t,s,n){return t===1?s:n}function kg({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=o.useId(),[l,i]=o.useState("non-brand"),d=$e({...Gu({client:ne,path:{name:t}}),staleTime:Ei}),c=d.data??null,h=c?.status==="ready"?Ng(c,s):[],u=h.find(p=>p.key===l)??h.at(0);let m;d.isError?m=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(d.error)]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{d.refetch()},children:"Retry"})]}):c?c.status==="no-data"?m=e.jsx("p",{className:"text-sm text-secondary",children:c.reason==="no-queries"?"Add queries to start tracking AI citations.":Jt()?Wn:"Engine results appear after the first AI Visibility sweep."}):u||(m=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):m=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const f=[];if(u&&c?.status==="ready"){const p=On(u.queries,"query","queries");f.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",p]})),f.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",p]})),f.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",p]})),f.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",p]}));for(const $ of u.engines)$.answered<u.queries&&f.push(e.jsxs(e.Fragment,{children:[nt($.provider),": answered ",e.jsxs("strong",{children:[$.answered," of ",u.queries]})," ",p]}));u.unanswered>0&&f.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",On(u.unanswered,"query","queries")]}));const{providersCiting:b,providersMentioning:C,providersConfigured:v}=c.summary;f.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[b," of ",v]})," ",On(v,"engine","engines"),", named by ",e.jsxs("strong",{children:[C," of ",v]})]}));for(const $ of a)f.push(e.jsxs(e.Fragment,{children:[nt($.provider),$.model?` (${$.model})`:""," citation rate:"," ",e.jsx("strong",{children:Je($.score,Zn.percent)}),", ",e.jsxs("strong",{children:[$.cited," of ",$.total]})," ",On($.total,"answer","answers"),", all queries"]}));for(const $ of u.competitorGaps)f.push(`"${$.query}" (${nt($.provider)}): ${$.competitors.join(", ")} cited instead of you`);for(const $ of wg(c))f.push(`"${$.query}" (${nt($.provider)}): ${$.competitors.join(", ")} cited instead of you, not counted (${Sg[$.reason]})`)}const g=c?.status==="ready"?c.summary.latestRunAt:null,y=(p,b)=>u?.key==="non-brand"?va[jg(p,b)]:"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(Fe,{text:Cg})]}),g||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[g?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",Ra(g)]}):null,h.length>1?e.jsx(fa,{label:"Query type",className:"flex-wrap",options:h.map(p=>({value:p.key,label:rl[p.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:rl[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:m??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${il[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",On(u.queries,"query","queries")]}),u.engines.map(p=>e.jsx("th",{scope:"col",children:nt(p.provider)},p.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(p=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(p.mentioned,p.answered)}`,children:p.mentioned})},p.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(p=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(p.cited,p.answered)}`,children:p.cited})},p.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," ",On(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",il[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(Ia,{items:f})]})}const Ag={[Cs.queued]:{word:"queued",tone:"text-secondary"},[Cs.running]:{word:"running",tone:"text-info-300"},[Cs.completed]:{word:"completed",tone:"text-secondary"},[Cs.partial]:{word:"partial",tone:"text-caution-400"},[Cs.failed]:{word:"failed",tone:"text-negative-400"},[Cs.cancelled]:{word:"cancelled",tone:"text-secondary"}};function Rg({runs:t,collapsed:s=!1}){const n=o.useId(),{openRun:a}=$i(),r=new Set(t.map(d=>d.location??"")).size>1,l=t.some(d=>d.kind!==Ds["answer-visibility"]),i=t.map(d=>`${d.startedAt}: ${d.summary}.${d.statusDetail?` ${d.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(Yn,{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(d=>{const c=Ag[d.status],h=d.status===Cs.partial||d.status===Cs.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(d.id),"aria-label":`View the ${d.startedAt} sweep`,children:d.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:d.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:d.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:d.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:d.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${c.tone}`,children:c.word}),h&&d.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:d.statusDetail}):null]})]},d.id)})})]})}),e.jsx(Ia,{items:i})]})})}const Pg=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],ol="Measured answers",Ig="Close answers",qs={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},Tg={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},gs={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."},ca={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."},Lg="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.",yr="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 $g(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Yc(t){return t.reason==="identity-ambiguous"?xc.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function Rn({value:t,signal:s}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:Yc(t)});const n=Di(t,s);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Je(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 ll({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 Ur(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case Rr["previous-unavailable"]:return{text:gs.previousUnavailable,tone:"text-secondary"};case Rr["current-unavailable"]:case Rr["not-applicable"]:return null}const{direction:a,magnitude:r}=mc(n.delta);switch(a){case"up":return{text:gs.up(r),tone:"text-positive"};case"down":return{text:gs.down(r),tone:"text-negative"};case"none":return{text:gs.none,tone:"text-secondary"}}}function cl(t,s){const n=Ot(t);return s!==null&&Ao(n)===Ao(Ot(s))?di(n):Pa(n)}function qg(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 Mg(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?cl(t.previousRun.createdAt,s):null;switch(t.reason){case yn["no-selected-run"]:return null;case yn["no-previous-run"]:return gs.noPreviousRun;case yn["definition-changed"]:return gs.definitionChanged(n);case yn["model-changed"]:return gs.modelChanged(n);case yn["legacy-unknown"]:return gs.legacyUnknown;case yn["partial-run"]:return gs.partialRun;case yn["scoped-run"]:return gs.scopedRun}}return gs.comparedWith(cl(t.previousRun.createdAt,s))}function Eg(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 Br({label:t,help:s,value:n,signal:a,unit:r,classNoun:l,change:i}){const d=e.jsx("span",{className:"sr-only",children:` · ${l}`}),c=Di(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(Fe,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[Yc(n),d]}):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:Je(n.rate)}),d,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}`}),c?e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:c}):null]})]})}const Dg={otherQueries:"Other queries"},Qa={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 Og(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(" · ")||Dg.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}const ba={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 Fg({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?ba.savedCite(a.citedAnswers,a.answers,a.citedTargetKeys.map(r).join(", ")):ba.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:ba.partlySaved(a.answers)}):null,e.jsx("span",{className:"text-sm text-secondary",children:l})]})}function dl({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(lx,{size:16,"aria-hidden":"true"}):e.jsx(cx,{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(Rn,{value:t,signal:s}),l?e.jsx(Fg,{row:l,targetLabels:r??new Map,showCount:t.rate===null}):null]}),l?e.jsx(Fe,{text:ba.help}):t.reason==="evidence-incomplete"?e.jsx(Fe,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function ul({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 Gg({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],d=m=>JSON.stringify([...m.targetKeys].sort()),c=t.rows.every(m=>d(m)===d(i)),h=t.rows.every(m=>m.location===i.location),u=m=>m===null?"No location requested":`Requested search location: ${m}`;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(tc,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(m=>m.sourceSnapshotIds??[]),queryClass:s==="unknown"?null:s,location:h?i.location:void 0})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[n&&c?e.jsx(ul,{targetKeys:i.targetKeys,labels:a}):null,h?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(m=>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:nt(m.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:m.model??"Model not recorded"}),n&&!c?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(ul,{targetKeys:m.targetKeys,labels:a})}):null,h?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(m.location)}),e.jsx(sc,{showLabel:!0,showSubjects:n,queryId:m.queryId,sourceSnapshotIds:m.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:m.provider,model:m.model,location:m.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(dl,{value:m.mentionCoverage,signal:"mentioned",singleAnswer:m.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(dl,{value:m.citationCoverage,signal:"cited",singleAnswer:m.answerCount===1,row:m,targetLabels:a})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(A,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${m.query} · ${m.provider}`,onClick:f=>l(m,f.currentTarget),children:[m.answerCount===1?"View answer":"View answers",e.jsx(Ac,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([m.provider,m.model,m.location])))]})}const _g="Cited counts only answers whose sources could be checked.",ml=[{key:"mentioned",label:"Mentioned",color:ct[1],dashed:!1},{key:"cited",label:"Cited",color:ea.positive,dashed:!0}],hl="var(--chart-tooltip-bg)";function Kg({population:t}){const s=o.useId(),[n,a]=o.useState({mentioned:!0,cited:!0}),r=ml.filter(f=>n[f.key]).map(f=>f.key),l=f=>a(g=>{const y={...g,[f]:!g[f]};return y.mentioned||y.cited?y:g});let i=0;const d=t.trend.map((f,g)=>(g>0&&f.continuity.state!=="comparable"&&(i+=1),{createdAt:Date.parse(f.createdAt),[`mentioned-${i}`]:f.mentionCoverage.rate,[`cited-${i}`]:f.citationCoverage.rate})),c=Array.from({length:i+1},(f,g)=>g),h=new Set(t.trend.slice(1).map(f=>f.continuity.state)),u=[...d.length===1?["First measurement. A trend appears after another comparable run."]:[],...h.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...h.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...h.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)?[_g]:[]];if(d.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const m=t.trend.some(f=>f.mentionCoverage.rate!==null||f.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[m?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"}),ml.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?hl: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:d,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Sa,{stroke:Na,vertical:!1}),e.jsx(cn,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:zt,tickLine:!1,axisLine:{stroke:fs},tickFormatter:f=>new Date(Number(f)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(dn,{domain:[0,1],tick:zt,tickLine:!1,axisLine:!1,width:48,tickFormatter:f=>Je(Number(f))}),e.jsx(un,{...is,formatter:f=>typeof f=="number"?Je(f):"Not measured",labelFormatter:f=>new Date(Number(f)).toLocaleDateString()}),c.map(f=>e.jsxs(o.Fragment,{children:[n.mentioned?e.jsx(Qs,{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(Qs,{type:"linear",dataKey:`cited-${f}`,name:"Cited",stroke:ea.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:hl,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:m?"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(Rn,{value:f.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Rn,{value:f.citationCoverage,signal:"cited"})}),e.jsx("td",{children:f.continuity.state.replaceAll("-"," ")})]},f.runId))})]})})]})}function wi(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function Ui(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,l=t.populations.find(h=>h.queryClass===r);if(l)return l;const i=wi(a,s)??wi(t,s),d=t.populations.find(h=>h.queryClass===i?.queryClass);if(d)return d;const c=["non-brand","branded","unknown"].map(h=>t.populations.find(u=>u.queryClass===h));return c.find(h=>h&&(h.summary.queryCount>0||h.trend.some(u=>u.queryCount>0)))??c.find(h=>h!==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(" ")},Ug={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Bg="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 Vg(t,s){return t&&s?kt.dateRange(t.slice(0,4)===s.slice(0,4)?ex(t):It(t),It(s)):t?kt.dateFrom(It(t)):s?kt.dateThrough(It(s)):null}function zg(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=Vg(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(Pa(Ot(r.createdAt))):kt.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Ha(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function Qg({report:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,trackingChangedAt:l,nextSweepDate:i,reportIsPlaceholder:d=!1}){const[c,h]=o.useState(!1),u=o.useRef(null),m=o.useId(),f=`${m}-filters`,{filterOptions:g,selection:y}=t,p=y.measurement,b=Ui(t,s.queryKey,s.answer),C=s.queryClass==="all"?b.queryClass:s.queryClass,v=zg(s,t),$=s.measurementScope==="property"?s.measurementScopeKey:void 0,R=$?r?.({id:$,label:mi(t.scopeOptions,s)?.label??$}):null,x=s.provider??"",N=s.model??"",w=s.location??"",P=s.measurementRunId??"",q=!d&&p.awaitingSweep&&p.measuredRevision!==null&&!y.run.explicit&&s.measurementRunId===void 0&&s.revision===void 0&&s.to===void 0,S=()=>u.current?.focus(),G=(T,F,ae,Q,B)=>e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${m}-${F}`,className:"text-sm font-medium text-heading",children:T}),B?e.jsx(Fe,{text:B}):null]}),e.jsx("select",{id:`${m}-${F}`,className:yr,value:ae,onChange:D=>n({[F]:D.target.value||void 0,measurementQueryKey:void 0}),children:Q.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))})]}),X=(T,F,ae,Q)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${m}-${F}`,className:"mb-1 block text-sm font-medium text-heading",children:T}),e.jsx("input",{id:`${m}-${F}`,type:"date",className:yr,value:ae?.slice(0,10)??"",onChange:B=>n({[F]:B.target.value?`${B.target.value}${Q}`: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:Bg,value:C,onChange:T=>n({queryClass:T.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(ge,{tone:p.state==="measured"?"positive":"neutral",children:p.state==="measured"?"Complete":p.state==="partial"?"Partial":"Not measured"}),p.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:Pa(Ot(p.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(A,{ref:u,type:"button",variant:"outline",className:"min-h-11","aria-expanded":c,"aria-controls":f,onClick:()=>h(T=>!T),children:kt.filters(v.length)}),v.map(T=>e.jsxs(A,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":kt.removeFilter(T.label),onClick:()=>{n(T.patch),S()},children:[e.jsx("span",{className:"min-w-0 truncate",children:T.label}),e.jsx(ox,{size:16,className:"shrink-0","aria-hidden":"true"})]},T.key)),R,a?e.jsx(A,{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:!c,className:"border-b border-default",onKeyDown:T=>{T.key==="Escape"&&(T.target instanceof HTMLElement&&T.target.getAttribute("aria-expanded")==="true"||(h(!1),S()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[G("Answer engine","measurementProvider",x,Ha([{value:"",label:"All engines"},...g.providers.map(T=>({value:T,label:T}))],x,x)),G("Requested search location","measurementLocation",w,Ha([{value:"",label:"All requested locations"},...g.locations.flatMap(T=>T.kind==="exact"?[{value:T.value,label:T.value}]:T.kind==="none"?[{value:"none",label:kt.noLocation}]:[])],w,w==="none"?kt.noLocation:w)),G("AI model","measurementModel",N,Ha([{value:"",label:"All models"},...Array.from(new Set(g.models.filter(T=>!s.provider||T.provider===s.provider).map(T=>T.model))).map(T=>({value:T,label:T}))],N,N),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),X("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),X("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),G("Results from","measurementRunId",P,Ha([{value:"",label:"Latest saved sweep"},...[...b.trend].reverse().map(T=>({value:T.runId,label:new Date(T.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(A,{type:"button",variant:"ghost",className:"min-h-11",disabled:v.length===0,onClick:()=>{n({...Ug}),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?di(Ot(l)):null,p.completedAt?di(Ot(p.completedAt)):null,i??null)}):null]})}function Hg({report:t,isRefreshing:s=!1,onSelectionChange:n,onPage:a,onSearch:r,search:l="",queryKey:i,answerSelection:d,evidenceReport:c,isEvidenceLoading:h=!1,evidenceError:u,onRetryEvidence:m,onEvidencePage:f}){const g=o.useRef(null),y=o.useRef(void 0),p=o.useRef(null),b=Ui(t,i,d,c),C=c??t,v=C.populations.filter(S=>[...S.queries.items,...S.evidence.items].some(G=>G.queryKey===i)),$=d?[d.queryClass]:(v.length?v:h?[]:[b]).map(S=>S.queryClass),R=i?JSON.stringify([d??i,$]):void 0;o.useEffect(()=>{if(!R){s||(y.current=void 0);return}if(y.current===R)return;const S=g.current?.querySelectorAll(`[aria-label="${ol}"]`);if(S?.length){for(const G of S){const X=G.closest("details[data-query-results]");X&&(X.open=!0)}S[0].focus({preventScroll:!0}),S[0].scrollIntoView?.({block:"start"}),y.current=R}},[R,s]);const{selection:x}=t,N=$g(x.scope),w=new Map(t.scopeOptions.filter(S=>S.kind==="property").map(S=>[S.id,S.label])),P=S=>{const G=C.populations.find(X=>X.queryClass===S.queryClass)?.evidence;return{items:G?.items.filter(X=>X.queryKey===i&&(!d||X.provider===d.provider&&X.model===d.model&&X.location===d.location&&(d.runId===null||X.runId===d.runId)))??[],nextCursor:G?.nextCursor}},q=()=>{y.current=void 0;const S=p.current;S!==null&&S.row.queryKey===i&&(!d||S.row.provider===d.provider&&S.row.model===d.model&&S.row.location===d.location)&&S?.element.isConnected?S.element.focus():g.current?.querySelector(`details[data-query-results="${b.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:g,className:"visibility-report","aria-label":"AI visibility results",children:[x.provenance.kind==="legacy-simple"&&x.queryClass!=="unknown"&&x.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(A,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[b].map(S=>{const G=Og(S.queries.items,x.scope.kind==="property"&&!x.market&&S.queryClass==="non-brand"?new Map(t.scopeOptions.filter(B=>B.kind==="market").map(B=>[B.id,B.label])):void 0),X=P(S),T=X.items[0]?.query??S.queries.items.find(B=>B.queryKey===i)?.query,F=x.mode==="advanced"&&x.scope.kind!=="property",ae=Tg[S.queryClass],Q=Mg(S.comparison,qg(x,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(Fe,{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:Eg(S.summary,Q)}),e.jsx(Fe,{text:gs.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":F?3:2,"aria-label":`${qs[S.queryClass]} headline results`,children:[e.jsx(Br,{label:F?"Answers mentioning a property":"Mentioned answers",help:x.mode==="advanced"?ca.advancedMention:ca.simpleMention,value:S.summary.mentionCoverage,signal:"mentioned",unit:"answers",classNoun:ae,change:Ur(S.comparison,"mentionCoverage")}),e.jsx(Br,{label:F?"Answers citing a property":"Cited answers",help:x.mode==="advanced"?ca.advancedCitation:ca.simpleCitation,value:S.summary.citationCoverage,signal:"cited",unit:"answers",classNoun:ae,change:Ur(S.comparison,"citationCoverage")}),F?e.jsx(Br,{label:"Properties mentioned",help:ca.propertyReach,value:S.summary.propertyReach,signal:"mentioned",unit:"properties",classNoun:ae,change:Ur(S.comparison,"propertyReach")}):null]}),e.jsx(ec,{queryClass:x.queryClass,manage:!0}),e.jsx(Kg,{population:S}),F&&(S.breakdown.groups.length>0||S.breakdown.properties.length>0)?e.jsx(Wg,{population:S,scope:x.scope,scopeOptions:t.scopeOptions,marketKey:x.market?.id,onSelectionChange:n},`${x.scope.kind}:${x.scope.id}`):null,x.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(([B,D])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:S.summary.outcomes[B]}),e.jsx("span",{className:"text-sm text-secondary",children:D})]},B))}),S.summary.notMeasuredUnchecked?e.jsx("p",{className:"text-sm text-secondary",children:ba.outcomes(S.summary.notMeasuredUnchecked)}):null]}),e.jsx(Fe,{text:Lg})]})]}):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"," · ",N]})]}),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:`${yr} max-w-sm`,value:l,onChange:B=>r(B.target.value)}):null,e.jsx(Fe,{text:x.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"})})]})}),G.map((B,D)=>e.jsx(Gg,{group:B,queryClass:S.queryClass,marketHeading:B.marketLabel!==G[D-1]?.marketLabel?B.marketLabel:void 0,advanced:x.mode==="advanced",targetLabels:w,onViewAnswers:(Y,E)=>{p.current={row:Y,element:E},n({measurementQueryKey:Y.queryKey,measurementAnswer:JSON.stringify({queryKey:Y.queryKey,queryClass:S.queryClass,provider:Y.provider,model:Y.model,location:Y.location,runId:x.run.id,revision:x.revision})})}},B.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:[G.length," ",G.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(A,{variant:"outline",onClick:()=>a(S.queries.nextCursor),children:"Next queries"}):null,i&&$.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":ol,"aria-busy":h,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:T??"Answers"}),e.jsx(A,{variant:"ghost",className:"min-h-11",onClick:q,children:Ig})]}),h?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]}),m?e.jsx(A,{variant:"outline",onClick:m,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[X.items.map(B=>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:B.provider}),B.model?e.jsx("span",{className:"text-[13px] text-secondary",children:B.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:B.location===null?kt.noLocation:kt.location(B.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(B.createdAt).toLocaleDateString()}),e.jsx(ge,{tone:"neutral",children:B.mentioned===null?B.mentionUnavailableReason==="identity-ambiguous"?xc.ambiguous:"Mention not checked":B.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ge,{tone:"neutral",children:B.cited===null?"Citation not checked":B.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Gi,{headingLevel:4,copyable:!!B.answerText?.trim(),children:B.answerText??"Answer text unavailable."})}),B.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:[Qh," (",B.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:B.sources.map(D=>e.jsx("li",{className:"min-w-0",children:e.jsx(qi,{url:D})},D))})]}):null]},B.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(A,{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(B=>e.jsxs("tr",{children:[e.jsx("td",{children:B.domain}),e.jsx("td",{children:e.jsx(Rn,{value:B.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Rn,{value:B.citationCoverage,signal:"cited"})})]},B.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(B=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:B.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[B.answerCount," ",B.answerCount===1?"answer":"answers"]})]},B.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},S.queryClass)})]})}function Wg({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(m=>m.kind==="group").map(m=>[m.id,m])),i=[...l.values()].some(m=>m.parentGroupIds?.length),d=t.breakdown.groups.filter(m=>{const f=l.get(m.id)?.parentGroupIds??[];return s.kind==="project"?f.length===0:s.kind==="group"&&i?f.includes(s.id):!0}),[c,h]=o.useState(()=>s.kind==="project"&&d.length>0?"groups":"properties"),u=rn({rows:c==="groups"?d:t.breakdown.properties,getSearchText:m=>m.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(m=>e.jsx(A,{variant:c===m?"secondary":"ghost",onClick:()=>{h(m),u.setPage(1)},children:m==="groups"?"Groups":"Properties"},m))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:m=>u.setQuery(m.target.value),className:`${yr} 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:c==="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(m=>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:c==="groups"?"group":"property",measurementScopeKey:m.id,measurementMarketKey:a}),children:m.label})}),e.jsx("td",{children:m.queryCount}),e.jsxs("td",{children:[e.jsx(Rn,{value:m.mentionCoverage,signal:"mentioned"}),e.jsx(ll,{value:m.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(Rn,{value:m.citationCoverage,signal:"cited"}),e.jsx(ll,{value:m.citationCoverage})]})]},m.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",c," match this search."]}):null,e.jsx(Es,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function Jc(t,s,{enabled:n}){return $e({...lr({client:ne,path:{name:t},query:li(s)}),enabled:n,staleTime:uc,retry:!1,placeholderData:Ti})}function Xc(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function Yg({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=o.useState(),[d,c]=o.useState(""),[h,u]=o.useState(),m=bs(),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]),g=$e({...lr({client:ne,path:{name:t},query:{...li(s),cursor:l,search:d||void 0}}),staleTime:uc,retry:!1,placeholderData:Ti}),y={...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??g.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??g.data?.selection.revision??s.revision,limit:50},p=JSON.stringify(y),b=$e({...lr({client:ne,path:{name:t},query:{...y,cursor:h?.selection===p?h.cursor:void 0}}),enabled:!!s.queryKey&&!!g.data&&!g.isPlaceholderData,retry:!1});if(o.useEffect(()=>{if(s.queryClass!=="all"||!g.data||g.isPlaceholderData||g.isFetching||g.isError||g.data.selection.availability.state==="unsupported"||g.data.populations.length===0||s.queryKey&&!s.answer&&!wi(g.data,s.queryKey)&&!b.data)return;const C=Ui(g.data,s.queryKey,s.answer,b.data);if(!l&&!d){const{queryKey:v}=lr({client:ne,path:{name:t},query:li({...s,queryClass:C.queryClass})});m.setQueryData(v,{...g.data,selection:{...g.data.selection,queryClass:C.queryClass},populations:[C]},{updatedAt:g.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,g.data,g.dataUpdatedAt,g.isPlaceholderData,g.isFetching,g.isError,b.data,n,m,t,f,l,d]),g.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:a});if(g.data&&Xc(g.data,r))return e.jsx(e.Fragment,{children:a});if(g.error){const C=hc(ci(g.error)),v=C?.reason===Uu["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:v?Qa.retiredMarket:C?Qa.retiredScope:ja(g.error)}),v?e.jsx(A,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:Qa.showAllMarkets}):C?e.jsx(A,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:Qa.showWholeSite}):e.jsx(A,{variant:"outline",onClick:()=>{i(void 0),g.refetch()},children:"Retry"})]})}return g.data?e.jsx("div",{"aria-busy":g.isFetching,children:e.jsx(Hg,{report:g.data,isRefreshing:g.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:b.data,isEvidenceLoading:b.isFetching||!!s.queryKey&&b.isPending,evidenceError:b.error?ja(b.error):void 0,onRetryEvidence:()=>{b.refetch()},onEvidencePage:b.isFetching?void 0:C=>u({selection:p,cursor:C}),search:d,onSearch:C=>{c(C),i(void 0)},onPage:g.isFetching?void 0:i,onSelectionChange:C=>{(!("measurementQueryKey"in C)||Object.keys(C).some(v=>v!=="measurementQueryKey"&&v!=="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 Jg({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,trackingChangedAt:l,nextSweepDate:i,fallback:d,showUnmeasuredFallback:c=!1}){const h=Jc(t,s,{enabled:!0}),u=h.error?void 0:h.data,m=!h.isPlaceholderData&&u?.selection.availability.state==="available"?u.selection.run.id:null;Ku(m,null);const f=!!(u&&u.selection.availability.state==="available"&&!Xc(u,c));return e.jsxs(e.Fragment,{children:[f?e.jsx(Qg,{report:u,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,trackingChangedAt:l,nextSweepDate:i,reportIsPlaceholder:h.isPlaceholderData}):null,!f&&(u||h.error)?e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx(Zl,{})}):null,e.jsx(Yg,{projectName:t,selection:s,onSelectionChange:n,fallback:d,showUnmeasuredFallback:c},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Xg=[{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."}],Bi=ct[2],ef=ct[4],tf="var(--chart-tooltip-bg)",sf={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function Zc({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function nf(t){return t.direction==="none"?"no change over the period":`${Zc(t)} over the period`}function af(t){return t===Ta||t===La||t===Ws}function ed(t){return t===Ta?"Cited":t===La?"Mentioned":t===Ws?"Mention share":nt(t)}function ma(t,s){return t===Ta?ea.positive:t===La?ct[1]:t===Ws?Bi:Zh(ka(t),s)}function Vi(t){return t==="non-brand"?"non-brand answers":"all answers"}function Si(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function zi(t,s){return t==="mentionShare"?`Mention share in ${Vi(s)}`:Si(t)}function rf(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 td(t){return t==="cited"?"citationRate":"mentionRate"}function Qi(t,s){return s==="cited"?t.cited:t.mentionedCount}function sd(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 of(t,s){if(s==="mentionShare"){const{projectMentionSnapshots:n,competitorMentionSnapshots:a}=t.mentionShare;return`${n} of ${n+a} tracked-brand mentions`}return`${Qi(t,s)} of ${t.total} answers`}function lf(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function nd(t){const s=Mc(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>ka(n).localeCompare(ka(a))).map(([n,a])=>`${nt(n)}: ${Aa(a)}`)}function ad(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function xl(t){return`${t} ${t===1?"query":"queries"}`}function Hi(t){const{added:s,removed:n}=t;return[...s.length>0?[`${xl(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:xl(n.length)} removed`]:[]].join(", ")}function rd(t,s){const n=Os(t),a=$a(t),r=Gc(t,s);if(!n||!a||!r)return null;const l=up(r.moves),i=ad(n.start,n.end),d=c=>Ra(c,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:d(n.start)})," sweep and the ",e.jsx("strong",{children:d(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 cf(t,s,n){const a=rd(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?", ":"",Hi(r)," ",e.jsx("strong",{children:Ca(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 pl(t){return t.replace(/ /g," ")}function br({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:Aa(t)})}function df(t,s){return t.reroute?"Same preset, answered with a different model.":pr(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${Aa(t.served.to)} (was ${Aa(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function uf({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:d,sweepTimes:c}){const h=t.at(-1),u=x=>Ca(x),m=new Map;for(const[x,N]of r){const w=n.find(P=>P.provider===x&&!P.reroute&&P.to.status==="known"&&N.modelIds.includes(P.to.model));w&&m.set(x,w)}const f=[];s.length>0&&f.push({key:"queries",label:"Queries",rows:s.map(x=>({key:`queries-${x.at}`,at:x.at,onOrBefore:!1,from:null,to:e.jsx("span",{className:"text-strong",children:Hi(x)}),toHelp:null}))});const g=[...new Set(n.map(x=>x.provider))].sort((x,N)=>nt(x).localeCompare(nt(N)));for(const x of g){const w=a[x]?.latestServedModelIds??null,P=n.filter(q=>q.provider===x);f.push({key:x,label:nt(x),rows:P.map((q,S)=>{const G=m.get(x)===q?r.get(x).text:null,X=[df(q,S===0?w:null),G].filter(Boolean).join(" ");return{key:`${x}-${q.at}-${q.reroute?"served":"set"}`,at:q.at,onOrBefore:q.onOrBefore,from:e.jsx(br,{state:q.from,from:!0}),to:e.jsx(br,{state:q.to}),toHelp:X||null}})})}const y=f.reduce((x,N)=>x+N.rows.length,0),p=[];for(const x of s)x.added.length>0&&p.push(e.jsxs(e.Fragment,{children:["Added ",e.jsx("strong",{children:u(x.at)}),": ",x.added.map(d).join(", ")]})),x.removed.length>0&&p.push(e.jsxs(e.Fragment,{children:["Removed ",e.jsx("strong",{children:u(x.at)}),": ",x.removed.map(d).join(", ")]}));const b=h?$a(h):null;for(const[x,N]of Object.entries(h?Mc(h)??{}:{}).sort(([w],[P])=>w.localeCompare(P)))N.status==="mixed"&&b&&p.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:b})," point mixes ",nt(x)," models: ",Qx(N)]}));const C=new Map;for(const x of n.filter(N=>N.onOrBefore)){const N=x.anchorAt?u(x.anchorAt):"";C.set(N,[...new Set([...C.get(N)??[],nt(x.provider)])])}for(const[x,N]of C)p.push(x?e.jsxs(e.Fragment,{children:["Changed before this date range, after the ",e.jsx("strong",{children:x})," sweep: ",ya(N)]}):`Changed before this date range: ${ya(N)}`);for(const x of l)p.push(`${nt(x.provider)}: most recent ${x.shown} of ${x.total} changes`);for(const x of i)p.push(`${nt(x)}: may be missing older changes`);for(const[x,N]of r)m.has(x)||p.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[nt(x),": no model updates on record",e.jsx(Fe,{text:N.text})]}));if(y===0&&p.length===0)return null;for(const[x,N]of Object.entries(a).sort(([w],[P])=>nt(w).localeCompare(nt(P)))){const w=N.latestServedModelIds??[],P=w.length>0?w.join(", "):Aa(N.latestObservation.state);p.push(e.jsxs(e.Fragment,{children:[nt(x)," last answered with ",e.jsx("strong",{children:P})," on ",e.jsx("strong",{children:u(Ot(N.latestObservation.observedAt))})]}))}const v=f.flatMap(x=>x.rows.map(N=>N.at));let $="First sweep on the new model or query set.";if(v.length>0){const x=u(v.reduce((G,X)=>Date.parse(X)>Date.parse(G)?X:G)),N=[...new Set(v.filter(G=>u(G)===x))].sort(),w=N.map(G=>Ra(G,G));$+=` ${x} = the ${ya(w)} ${w.length===1?"sweep":"sweeps"}.`;const P=n.flatMap(G=>G.anchorAt?[G.anchorAt]:[]),q=P.length>0?P.reduce((G,X)=>Date.parse(X)>Date.parse(G)?X:G):null,S=op(N[0],c,t,q);S&&($+=` Sweep before: ${u(S)}.`)}const R=ip({latest:h,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:R}),e.jsxs("span",{className:"av-wc-toggle",children:[e.jsxs("span",{className:"av-wc-when-closed",children:[y>0?`Show all ${y}`:"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:y>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(Fe,{text:$})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),f.map(x=>e.jsx("tbody",{children:x.rows.map((N,w)=>e.jsxs("tr",{children:[w===0?e.jsx("th",{scope:"row",className:"av-engine",children:x.label}):e.jsx("td",{className:"av-engine",children:e.jsx("span",{className:"sr-only",children:x.label})}),e.jsx("td",{className:"av-date",children:N.onOrBefore?`on or before ${pl(u(N.at))}`:pl(u(N.at))}),N.from===null?null:e.jsx("td",{children:N.from}),e.jsx("td",{colSpan:N.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[N.to,N.toHelp?e.jsx(Fe,{text:N.toHelp}):null]})})]},N.key))},x.key))]})}),e.jsx(Ia,{items:p})]}):e.jsx("ul",{className:"av-details-list",children:p.map((x,N)=>e.jsx("li",{children:x},N))})})]})}function mf({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:nt(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(br,{state:n.configured})," · answered ",e.jsx(br,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function hf({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const d=lf(l,s);if(!d)return null;const c=Os(d),h=c!==null&&ad(c.start,c.end)?c.start:null,u=Oc(d,i),m=nd(d),f=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:_i(d)}),u.map(p=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[Hi(p)," ",Ra(p.at,h)]},p.at))]}),g=m.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:m.map((p,b)=>e.jsxs(o.Fragment,{children:[b>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:p})]},b))});if(a==="mentionShare"){const p=d.mentionShare.projectMentionSnapshots,b=d.mentionShare.competitorMentionSnapshots,C=p+b;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:Bi},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:zi("mentionShare",d.mentionShare.scope)}),e.jsx("span",{className:"trend-tooltip-value",children:Je(d.mentionShare.rate)})]}),e.jsx("p",{className:"trend-tooltip-detail",children:C>0?`You ${p} of ${C} tracked-brand mentions. Competitors ${b}.`:"No tracked-brand mentions in this point"}),g]})}const y=r==="byProvider"?(n??[]).filter(p=>p.dataKey!==void 0):[{dataKey:a==="cited"?Ta:La}];return e.jsxs("div",{className:"trend-tooltip",children:[f,y.map((p,b)=>{const C=String(p.dataKey??p.name??""),v=r==="byProvider"?sd(d,C,a):null,$=v?.count??Qi(d,a),R=v?.total??d.total,x=v?v.rate:d[td(a)],N=p.color??ma(C,b);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:N},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:ed(C)}),e.jsx("span",{className:"trend-tooltip-value",children:Je(x)}),e.jsxs("span",{className:"trend-tooltip-count",children:[$," of ",R]})]})},`${C}-${b}`)}),g]})}function xf({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:[zi(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 c=l.mentionShare.projectMentionSnapshots,h=l.mentionShare.competitorMentionSnapshots,u=c+h,m=Vi(l.mentionShare.scope);i=u>0?`${Je(l.mentionShare.rate)} mention share in ${m}, ${c} of ${u} tracked-brand mentions were you`:`mention share undefined in ${m}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(c=>{const h=sd(l,c,s);return h?`${nt(c)} ${Je(h.rate)} ${Si(s).toLowerCase()}, ${h.count} of ${h.total} answers`:`${nt(c)} no data`}).join("; "):i=`${Je(l[td(s)])} ${Si(s).toLowerCase()}, ${Qi(l,s)} of ${l.total} answers`;const d=nd(l);return d.length>0&&(i+=`; models: ${d.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:_i(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function pf({projectName:t,competitorDomains:s=[],competitorAliases:n,analyticsRevision:a="none",queryTexts:r=[],classifyQuery:l,sweepTimes:i=[]}){const[d,c]=o.useState("all"),[h,u]=o.useState("mentioned"),[m,f]=o.useState("byProvider"),g=o.useId(),y=o.useMemo(()=>Gx(s,n),[s,n]),p=$e({queryKey:["analytics-metrics",t,d,y,a],queryFn:()=>_u(t,d),staleTime:Ei}),b=p.data??null,C=p.error,v=h==="mentionShare"?"overall":m,$=o.useMemo(()=>b?Xx(b,h,v):null,[b,h,v]),R=b?Ux(b):null,x=o.useMemo(()=>Wx(R??{}),[R]),N=o.useMemo(()=>Yx(R??{}),[R]),w=o.useMemo(()=>Object.entries(R??{}).filter(([,be])=>be.anchorUnavailable).map(([be])=>be).sort(),[R]),P=o.useMemo(()=>b?Bx(b):{},[b]),q=o.useMemo(()=>b?sp(Vx(b)):[],[b]),S=o.useMemo(()=>b?Dc(b):[],[b]),G=o.useMemo(()=>b?np(b):[],[b]),X=o.useMemo(()=>rp(R??{},P),[R,P]),T=o.useMemo(()=>b?zx(b):{},[b]),F=o.useMemo(()=>po(T,{engineName:nt}),[T]),ae=o.useMemo(()=>{const be=new Map;for(const[Ne,_e]of Object.entries(T).sort(([Oe],[O])=>Oe.localeCompare(O))){const Oe=po({[Ne]:_e},{engineName:nt});Oe?.kind==="no-known-change"&&be.set(Ne,{text:`${Oe.text} ${Oe.detail}`,modelIds:_e.modelIds??[]})}return be},[T]),Q=o.useMemo(()=>{const be=new Map(r.map(Ne=>[Hn(Ne),Ne]));return Ne=>be.get(Hn(Ne))??Ne},[r]),B=h!=="mentionShare"&&v==="byProvider",D=b?.buckets??[],Y=D[D.length-1]?.mentionShare.scope??b?.mentionShareScope??"pooled",E=zi(h,Y),W=B?ys.textDim:h==="cited"?ea.positive:h==="mentionShare"?Bi:ct[1],L=o.useMemo(()=>{const be=new Map(D.map(Ne=>[Ne.startDate,Fx(Ne)]));return Ne=>be.get(String(Ne))??""},[D]),ee=h==="mentionShare"?D.filter(be=>typeof be.mentionShare.rate=="number"&&Number.isFinite(be.mentionShare.rate)):D,K=ee.at(-1),ce=(b?Zx(b,h):[]).at(-1)??null,Se=b?ep(b,h):null,Z=dp(ee,S),me=qo(Z,h,Y,l),Ce=ce!==null&&Se!==null?mc(Se.delta):null,J=Ce!==null&&!me,he=s.length,_=[];if(K&&Se!==null&&Z&&!me&&_.push(cf(Z,K,S)),K&&ee.length===1){const be=rd(K,S);be&&!qo(Gc(K,S),h,Y,l)&&_.push(be)}if(Ce!==null&&ee[0]){const be=$a(ee[0]);be&&_.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:be})," point"]}))}B&&ce!==null&&_.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:Je(ce)})," pools all answers; not an average of engines"]}));const pe=[...new Set([...x.buckets.map(be=>be.bucketStartDate),...D.filter(be=>Oc(be,S).length>0).map(be=>be.startDate)])].sort(),Me=ce!==null&&K&&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:Je(ce)}),Ce!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${J?"text-muted":sf[Ce.direction]}`,children:[Zc(Ce),J?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",of(K,h)]})]}),Pe=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(fa,{options:Zg,value:h,onChange:u,label:"Metric",className:"visibility-trend-metric-control"}),h!=="mentionShare"&&e.jsx(fa,{options:Xg,value:m,onChange:f,label:"Series"}),e.jsx(fa,{options:Pg,value:d,onChange:c,label:"Time window",className:"sm:ml-auto"})]});let re;if(C)re=e.jsx("p",{className:"text-sm text-negative-400",children:ja(C)});else if(p.isLoading&&!b)re=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(h==="mentionShare"&&he===0)re=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!b||!$)re=null;else{const{rows:be,series:Ne,hasData:_e}=$;if(!_e)re=e.jsx("p",{className:"text-sm text-secondary",children:h==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${Vi(Y)} in this window yet.`:Jt()?Wn:"Run a sweep to start tracking citations and mentions over time."});else if(B&&Ne.length===0)re=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 Oe=`${E} rate across ${be.length} ${be.length===1?"sweep":"sweeps"}. Latest ${Je(ce)}${Ce!==null?`, ${nf(Ce)}${J?", not the same queries":""}`:""}.`;re=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:Oe}),e.jsx(xf,{buckets:D,metric:h,mode:v,series:Ne,mentionShareScope:Y}),B&&Ne.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:Ne.map((O,U)=>{const V=tp(b,O,h);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:ma(O,U)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:ed(O)}),V!==null&&e.jsx("span",{className:"trend-legend-value",children:Je(V)})]},O)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${E} trend chart over ${be.length} ${be.length===1?"point":"points"}`,children:e.jsx(on,{width:"100%",height:"100%",children:e.jsxs(ln,{data:be,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(Sa,{stroke:Na,vertical:!1}),e.jsx(cn,{dataKey:"date",tick:zt,tickLine:!1,axisLine:{stroke:fs},tickFormatter:L,minTickGap:24}),e.jsx(dn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:O=>Je(O,Zn.percent),tick:zt,tickLine:!1,axisLine:!1,width:40}),e.jsx(un,{cursor:{stroke:fs,strokeWidth:1},content:e.jsx(hf,{metric:h,mode:v,buckets:D,basketChanges:S})}),pe.map(O=>e.jsx(fx,{x:O,stroke:ef,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${O}`)),Ne.map((O,U)=>e.jsx(Qs,{type:"monotone",dataKey:O,name:O,stroke:ma(O,U),strokeDasharray:O===Ws?"5 4":void 0,strokeWidth:af(O)?2.5:2,dot:O===Ws?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:ma(O,U),strokeWidth:1.5}:{r:2.5,fill:ma(O,U),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:tf},connectNulls:O!==Ws,isAnimationActive:!1},O))]})})}),pe.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":g,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:g,className:"av-card-title",children:"AI answers over time"}),e.jsx(Fe,{text:rf(Y)})]}),K?e.jsx("p",{className:"av-card-meta",children:_i(K)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[F?.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:F.text}),Me,Pe,re]}),e.jsx(Ia,{items:_})]}),b&&!C?e.jsxs(e.Fragment,{children:[e.jsx(uf,{buckets:D,queryChanges:G,modelRows:X,served:P,pointerNotices:ae,truncated:N,incompleteHistory:w,queryName:Q,sweepTimes:i}),e.jsx(mf,{substitutions:q})]}):null]})}const gl=new Set([ga.queued,ga.running]),Vt={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 fl({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:d,templates:c=[],viewerResearchConfig:h=null}){const u=bs(),{account:m,canWrite:f}=Ys(),g=m?.role==="viewer"&&h!==null,y=!f,p=os(),[b,C]=o.useState(""),[v,$]=o.useState(""),[R,x]=o.useState(null),[N,w]=o.useState([]),P=o.useRef(null),q=o.useRef(!1),[S,G]=o.useState(0),X=$e({...Bu({client:ne,path:{name:t}}),staleTime:6e4}),T=$e({...Vu({client:ne}),enabled:!y&&!p,staleTime:6e4}),F={client:ne,path:{name:t},query:{limit:20}},ae=Jl({...zu(F),initialData:void 0,initialPageParam:F,getNextPageParam:_=>_.nextCursor?{path:F.path,query:{...F.query,cursor:_.nextCursor}}:void 0,refetchInterval:_=>_.state.data?.pages.some(pe=>pe.runs.some(Me=>gl.has(Me.status)))?3e3:!1}),Q=ae.isError&&!ae.isFetchNextPageError,B=ae.data?.pages.at(-1),D=Q?[]:[...new Map((ae.data?.pages.flatMap(_=>_.runs)??[]).map(_=>[_.id,_])).values()],Y=B?.access?.canRun??(f||g),E=B?.access?B.access.dailyRunLimit:g?h.viewerDailyRunLimit:null;o.useEffect(()=>{!R&&D[0]&&x(D[0].id)},[D,R]);const W=D.find(_=>_.id===R)??null,L=$e({...Qu({client:ne,path:{name:t,runId:R??""}}),enabled:!Q&&!!R,refetchInterval:W&&gl.has(W.status)?3e3:!1}),ee=Q||L.isError?null:L.data??null,K=X.data?.locations??[],se=o.useMemo(()=>{if(y)return(B?.providers??[]).map(pe=>({...pe,catalog:pe}));const _=new Map((T.data?.providerCatalog??[]).map(pe=>[pe.name,pe]));return(T.data?.providers??[]).filter(pe=>pe.configured&&_.get(pe.name)?.mode==="api").map(pe=>({...pe,catalog:{..._.get(pe.name),defaultModel:pe.model||_.get(pe.name).defaultModel}}))},[y,B?.providers,T.data]),ce=!(y?ae.isPending:T.isPending)&&se.length===0,Se=se.find(_=>_.name===b)??null;o.useEffect(()=>{if(!b&&X.data&&!X.isError&&!T.isError){const _=X.data.providers.find(pe=>se.some(Me=>Me.name===pe));C(_??se[0]?.name??"")}},[b,se,X.data,X.isError,T.isError]);const Z=Se?.catalog.modelConfigurable??!1,me=y?Se?.catalog.defaultModel:(Se?X.data?.providerModels[Se.name]:"")||Se?.catalog.defaultModel,Ce=(Z?v.trim():"")||me,J=Se?[...new Map([{id:Se.catalog.defaultModel,displayName:Se.catalog.defaultModel},...v.trim()?[{id:v.trim(),displayName:v.trim()}]:[],...Se.catalog.knownModels].map(_=>[_.id,_])).values()]:[],he=Kt({...Hu(),onSuccess:async _=>{P.current=null,G(pe=>pe+1),w(_.runs),x(_.runs[0]?.id??null),await Cf(u),De({title:"Research batch saved",detail:`${_.runs.length} ${_.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${_.runs.map(pe=>pe.id).join(":")}`,dedupeMode:"replace"})},onError:_=>{De({title:"Could not start research",detail:_ instanceof Error?_.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:[p?e.jsx(je,{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(gf,{projectName:t,canWrite:f,researchAllowed:Y&&!Q,limitedAccess:y,isEmbed:ie(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:d,templates:c,locations:K,defaultLocation:X.data?.defaultLocation??null,providerOptions:se,provider:b,onProviderChange:_=>{C(_),$("")},resolvedModel:Ce,visibilityModel:me,configurableModel:Z,model:v,onModelChange:$,modelOptions:J,settingsReady:y?!ae.isPending&&!Q:!T.isPending&&!T.isError&&!T.isFetching,projectReady:!X.isPending&&!X.isError&&!X.isFetching,isPending:he.isPending,errorMessage:he.isError?"The request could not be confirmed.":void 0,onSubmit:(_,pe)=>{!Y||Q||ie()||q.current||(P.current?.fingerprint!==pe&&(P.current={fingerprint:pe,key:crypto.randomUUID()}),q.current=!0,he.mutate({client:ne,path:{name:t},body:{..._,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."]}),!y&&T.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(A,{variant:"outline",onClick:()=>{T.refetch()},children:"Retry providers"})]}):null,X.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(A,{variant:"outline",onClick:()=>{X.refetch()},children:"Retry locations"})]}):null,!(y?Q:T.isError)&&ce&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:y?"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."}),N.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",N.map((_,pe)=>e.jsxs("span",{children:[pe>0?", ":"",e.jsxs("a",{href:`#research-run-${_.id}`,className:"text-link underline",onClick:()=>x(_.id),children:[_.scope?.label??"Whole site",_.location?`, ${_.location.label}`:", No location"]})]},_.id))]})]}),e.jsxs(je,{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:Vt.historyTitle})}),ae.isFetching&&e.jsx(ge,{tone:"neutral",children:"Loading"})]}),Q?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(A,{variant:"outline",onClick:()=>{ae.refetch()},children:"Retry history"})]}):ae.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):D.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Vt.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:D.map(_=>e.jsxs("tr",{className:R===_.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:()=>x(_.id),children:Nf(_.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:_.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:_.requestedModel??_.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:_.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:_.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[_.completedQueries+_.failedQueries,"/",_.totalQueries]}),e.jsx("td",{children:e.jsx(ge,{tone:id(_.status),children:_.status})})]},_.id))})]})}),ae.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Vt.historyMoreError}),ae.hasNextPage&&e.jsx(A,{className:"mt-3",variant:"outline",disabled:ae.isFetching,onClick:()=>{ae.fetchNextPage()},children:ae.isFetchingNextPage?Vt.historyLoading:Vt.historyMore})]})]}),!Q&&L.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(A,{variant:"outline",onClick:()=>{L.refetch()},children:"Retry results"})]}):Q?null:e.jsx(vf,{detail:ee,isLoading:L.isFetching,onReviewForTracking:p?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",Un="__none__";function gf(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=bs(),[d,c]=o.useState("once"),[h,u]=o.useState(""),[m,f]=o.useState(""),[g,y]=o.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[p,b]=o.useState(null),[C,v]=o.useState([]),[$,R]=o.useState(""),[x,N]=o.useState({}),[w,P]=o.useState(null),[q,S]=o.useState([]),[G,X]=o.useState(null),[T,F]=o.useState(!1),[ae,Q]=o.useState(!1),[B,D]=o.useState(""),[Y,E]=o.useState(""),W=o.useRef(null),L=o.useRef(!1),ee=o.useRef(null),K=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";o.useEffect(()=>{y(K),P(null)},[K]);const se=t.scopeOptions.filter(k=>k.kind==="market"||k.kind==="property"),ce=d==="markets"?"market":"property",Se=se.filter(k=>k.kind===ce),Z=k=>({kind:k.kind,key:k.id,label:k.label,planRevision:l??t.initialScope?.planRevision??0}),me=k=>k===Un?null:n.find(xe=>xe.label===k),Ce=p??t.defaultLocation??Un,J=se.find(k=>`${k.kind}:${k.id}`===g),he=J?Z(J):null,_=d==="once"?[{scope:he,location:me(Ce)}]:d==="locations"?C.map(k=>({scope:null,location:me(k)})):C.map(k=>Se.find(xe=>`${xe.kind}:${xe.id}`===k)).map(k=>k?{scope:Z(k),location:me(x[`${k.kind}:${k.id}`]??Un)}:null),pe=[...new Map([...q,...t.templates].map(k=>[k.id,k])).values()],Me=w?pe.find(k=>k.id===w.id):null,Pe=w!==null&&Me?.version!==w.version,re=d==="once"?h:m,be=re.split(/\r?\n/).filter(k=>k.trim()),Ne=go(be),_e=[...new Set([...m.matchAll(/\{([^{}]+)\}/g)].map(k=>k[1]))],Oe=/[{}]/.test(m.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),O=[];be.length||O.push(d==="once"?"Enter at least one query.":"Enter at least one query pattern."),be.some(k=>k.length>4e3)&&O.push("Keep each query under 4,001 characters."),d!=="once"&&Oe&&O.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),_.length||O.push(d==="locations"?"Select at least one location.":"Select at least one destination."),_.some(k=>!k||k.location===void 0)&&O.push("A selected destination or location is no longer available. Update your selection.");const U=d==="once"&&g!=="project"||d==="markets"||d==="properties";U&&(t.scopePending||t.scopeError||!l||_.some(k=>!k?.scope))&&O.push("Load the current published markets and properties before running scoped research.");const V=(d==="once"?Ne.length:be.length)*_.length;if(_.length>Ga&&O.push(`Select at most ${Ga} destinations.`),V>Ir&&O.push(`${V} queries selected. Reduce the selection to ${Ir} or fewer.`),Pe&&O.push("This saved pattern changed. Select its current version from Saved patterns."),d!=="once"&&!Oe){for(const k of _)if(!(!k||k.location===void 0))try{Pr(w??{pattern:m,variables:_e},k.scope,k.location)}catch{O.push(`Choose a location for {location}, or use only variables available for ${d==="markets"?"markets":d==="properties"?"properties":"locations"}.`);break}}const Le=JSON.stringify({mode:d,source:re,contexts:_,provider:a,resolvedModel:r,template:w,...U?{planRevision:l}:{}}),ze=G!==null&&G.signature!==Le,Ue=d==="once"?Ne.map((k,xe)=>({id:String(xe),query:k,scope:he,location:_[0]?.location??null})):G?.rows??[],dt=bf(Ue),de=[];d!=="once"&&G&&(ze&&de.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Ue.some(k=>!k.query.trim()||k.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(k.query))&&de.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Ue.some(k=>k.location&&!n.some(xe=>JSON.stringify(xe)===JSON.stringify(k.location)))&&de.push("A preview location changed. Regenerate the preview."),dt.some(k=>go(k.queries).length!==k.queries.length)&&de.push("Remove duplicate queries within each destination and location."),dt.length>Ga&&de.push(`The preview exceeds ${Ga} runs.`));const Tt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!O.length&&!de.length&&(d==="once"||G!==null),vt=()=>({runs:dt.map(k=>({queries:k.queries,provider:a,model:r,location:k.location,...k.scope?{scope:{kind:k.scope.kind,key:k.scope.key,expectedPlanRevision:k.scope.planRevision}}:{},...k.template?{template:k.template}:{}}))}),We=()=>{if(F(!0),O.length)return;const k=_.flatMap((xe,Ke)=>be.map((Ie,At)=>({id:`${Ke}:${At}`,scope:xe.scope,location:xe.location,...w?{template:{templateId:w.id,templateVersion:w.version,bindingLocation:xe.location}}:{},query:Pr({pattern:Ie,variables:[...new Set([...Ie.matchAll(/\{([^{}]+)\}/g)].map(ht=>ht[1]))]},xe.scope,xe.location).output})));X({signature:Le,rows:k})},Xe=k=>{c(k),v([]),P(null),R(""),F(!1)},mt=k=>{if(E(""),d==="once")try{u(Pr(k,he,me(Ce)).output)}catch{E("Select a matching market, property, or location before using this pattern.");return}else f(k.pattern);P(k)},Ze=k=>{const xe=ee.current,Ke=xe?.selectionStart??m.length,Ie=xe?.selectionEnd??Ke;f(`${m.slice(0,Ke)}{${k}}${m.slice(Ie)}`),P(null),requestAnimationFrame(()=>{xe?.focus(),xe?.setSelectionRange(Ke+k.length+2,Ke+k.length+2)})},jt=Kt({...Yu(),onSuccess:async k=>{const xe={id:k.id,version:k.updatedAt,label:k.name,pattern:k.pattern,variables:k.variables};S(Ke=>[...Ke.filter(Ie=>Ie.id!==k.id),xe]),P(xe),Q(!1),D(""),E(""),W.current=null,await i.invalidateQueries({queryKey:Wu({client:ne,path:{name:s}})}),De({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:()=>{L.current=!1}}),at=()=>{if(!t.canWrite||t.isEmbed||L.current)return;const k=d==="once"?h:m,xe=d==="once"?[]:_e;if(!B.trim()||!k.trim()||k.length>4e3||d!=="once"&&Oe){E("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const Ke={name:B.trim(),pattern:k,variables:xe},Ie=JSON.stringify(Ke);W.current?.fingerprint!==Ie&&(W.current={fingerprint:Ie,id:crypto.randomUUID()}),L.current=!0,jt.mutate({client:ne,path:{name:s,templateId:W.current.id},body:Ke})},Ft=[...new Set([...T||re.trim()?O:[],...de])],Pt=pe.filter(k=>{const xe=d==="once"?fo(he,me(Ce)):fo(d==="markets"?{kind:"market",label:"Market"}:d==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return k.variables.every(Ke=>xe[Ke]!==void 0)});return e.jsxs(je,{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||jt.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:d,disabled:t.isPending,onChange:k=>Xe(k.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!se.some(k=>k.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!se.some(k=>k.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),d==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(se.length>0||g!=="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:g,onChange:k=>{y(k.target.value),P(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),g!=="project"&&!J&&e.jsx("option",{value:g,disabled:!0,children:"Selected destination unavailable"}),se.map(k=>e.jsxs("option",{value:`${k.kind}:${k.id}`,children:[k.label," (",k.kind,")"]},`${k.kind}:${k.id}`))]})]}),e.jsx(Ci,{label:"Answer engine location",value:Ce,locations:n,onChange:k=>{b(k),P(null)}})]}),d!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:d==="locations"?"Select locations":`Select ${d}`}),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 ${d}`,value:$,onChange:k=>R(k.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(d==="locations"?n.map(k=>({key:k.label,label:k.label})):Se.map(k=>({key:`${k.kind}:${k.id}`,label:k.label}))).filter(k=>k.label.toLocaleLowerCase().includes($.toLocaleLowerCase())).map(k=>{const xe=C.includes(k.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:xe,onChange:()=>v(Ke=>xe?Ke.filter(Ie=>Ie!==k.key):[...Ke,k.key])}),k.label]}),xe&&d!=="locations"&&e.jsx(Ci,{label:`Answer engine location for ${k.label}`,value:x[k.key]??Un,locations:n,onChange:Ke=>N(Ie=>({...Ie,[k.key]:Ke}))})]},k.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(A,{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:d==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:d==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${d==="markets"?"market":d==="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:re,placeholder:d==="once"?Vt.queryPlaceholder:d==="markets"?"Best apartments in {market}":d==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:k=>{d==="once"?u(k.target.value):(f(k.target.value),P(null))}}),d!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(A,{size:"sm",variant:"outline",onClick:()=>Ze(d==="markets"?"market":d==="properties"?"property":"location"),children:["Insert ",d==="markets"?"market":d==="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:[V," / ",Ir," queries",d==="once"?"":` across ${_.length} destinations`]})]}),d!=="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."}),Pt.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:Pt.map(k=>e.jsx(A,{size:"sm",variant:"outline",onClick:()=>mt(k),children:k.label},k.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(A,{size:"sm",variant:"outline",onClick:()=>Q(!ae),children:ae?"Cancel save":"Save as a pattern"}),ae&&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:B,maxLength:120,onChange:k=>D(k.target.value)})]}),e.jsx(A,{size:"sm",disabled:jt.isPending||!B.trim()||!re.trim(),onClick:at,children:jt.isPending?"Saving…":"Save pattern"})]})]}),Y&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:Y})]})]}),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:k=>t.onProviderChange(k.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(k=>e.jsx("option",{value:k.name,children:k.displayName??k.name},k.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:k=>t.onModelChange(k.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(k=>e.jsx("option",{value:k.id,children:k.displayName},k.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:k=>t.onModelChange(k.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(k=>e.jsx("option",{value:k.id,children:k.displayName},k.id))})]})]})]}),Ft.length>0&&e.jsx(yf,{errors:Ft}),d!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:We,children:[e.jsx(wa,{size:14}),G?Vt.refreshPreview:"Preview queries"]}),G&&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:[Ue.length," query executions in ",dt.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(ff,{rows:Ue,locations:n,onChange:(k,xe)=>X(Ke=>Ke&&{...Ke,rows:Ke.rows.map(Ie=>Ie.id===k?{...Ie,...xe}:Ie)})})]})]}),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(A,{size:"sm",disabled:!Tt,onClick:()=>{if(Tt){const k=vt();t.onSubmit(k,JSON.stringify({projectName:s,...k}))}},children:[e.jsx(hr,{size:14}),t.isPending?"Starting…":Vt.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[d==="once"?`${Ne.length} queries`:`${Ue.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function Ci({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:Un,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function ff({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(Ci,{label:`Location for query ${r+1}`,value:a.location?.label??Un,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function yf({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 bf(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 vf({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(je,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":Vt.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 ${wf(t.id)}`:Vt.resultsEmpty})]}),t&&e.jsx(ge,{tone:id(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:Vt.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,d])=>`${i}: ${d}`).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:Vt.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Vt.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(ge,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Vt.brandedQuery:i.queryClass==="non-brand"?Vt.discoveryQuery:Vt.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(ge,{tone:Sf(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ge,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===kn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===kn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(ge,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===kn.failed?"negative":"caution",children:i.citationState===null?i.status===kn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(jf,{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 jf({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})]}),!ie()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(He,{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(Gi,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===kn.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(qi,{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 Nf(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 wf(t){return t.length>8?t.slice(0,8):t}function id(t){return t===ga.completed?"positive":t===ga.partial?"caution":t===ga.failed?"negative":"neutral"}function Sf(t){return t===kn.completed?"positive":t===kn.failed?"negative":"neutral"}async function Cf(t){await Dt(t,"researchRuns")}const ki=new Set(["queued","seeding","probing"]);function kf({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c,publishGuard:h}){const{account:u}=Ys(),[m,f]=o.useState("tracked"),[g,y]=o.useState("find"),[p,b]=o.useState(null),C=u?.role==="viewer"?pc():null,v=Pc(u?.role,C),R=Ic(s??m,v),x=a??g,N=q=>{s===void 0&&f(q),n?.(q)},w=q=>{a===void 0&&y(q),r?.(q)},P=(q,S)=>{const G={...l,measurementScope:S?.kind??"project",measurementScopeKey:S?.key};b({...q,trackingSelection:G}),S!==void 0&&i?.({measurementScope:G.measurementScope,measurementScopeKey:G.measurementScopeKey}),N("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(vr,{active:R==="tracked",label:"Tracked",onClick:()=>N("tracked")}),v?e.jsx(vr,{active:R==="research",label:"Research",onClick:()=>N("research")}):null]}),e.jsx("div",{className:"mt-4",children:R==="tracked"?e.jsx(Qf,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c,pendingTrackingSource:p,onPendingTrackingSourceHandled:()=>b(null),publishGuard:h}):e.jsx(Af,{projectName:t,selection:l,mode:x,onModeChange:w,onReviewSavedSource:P,onSelectionChange:i,viewerResearchConfig:C})})]})}function vr({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 Af({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=Ys(),d=!i||n==="test",c=$e({...Oi({client:ne,path:{name:t}}),enabled:d,staleTime:6e4}),h=$e({...gc({client:ne,path:{name:t}}),enabled:d,staleTime:6e4}),u=o.useMemo(()=>{const g=c.data;if(!g)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const y=new Map(g.targets.map(b=>[b.stableKey,[]]));for(const b of g.groups)for(const C of b.targetKeys)y.get(C)?.push(b.stableKey);const p=new Map(g.markets.map(b=>[b.stableKey,new Set]));for(const b of g.markets)for(const C of b.usageEdges)for(const v of y.get(C.targetKey)??[])p.get(b.stableKey)?.add(v);return[{id:"project",label:"Whole site",kind:"project",targetCount:g.targets.length},...g.groups.map(b=>({id:b.stableKey,label:b.label,kind:"group",targetCount:b.targetKeys.length,...b.parentGroupKey?{parentGroupIds:[b.parentGroupKey]}:{}})),...g.markets.map(b=>{const C=[...p.get(b.stableKey)??[]];return{id:b.stableKey,label:b.label,kind:"market",targetCount:0,...C.length?{parentGroupIds:C}:{}}}),...g.targets.map(b=>({id:b.stableKey,label:b.label,kind:"property",targetCount:1,...y.get(b.stableKey)?.length?{parentGroupIds:y.get(b.stableKey)}:{}}))]},[c.data]),m=o.useMemo(()=>(h.data?.templates??[]).map(g=>({id:g.id,version:g.updatedAt,label:g.name,pattern:g.pattern,variables:g.variables})),[h.data]),f={projectName:t,scopeOptions:u,planRevision:c.data?.active?.revision??null,selectedScope:(()=>{const g=u.find(p=>p.kind===s.measurementScope&&p.id===s.measurementScopeKey),y=c.data?.active?.revision;return g&&y&&(g.kind==="market"||g.kind==="property")?{kind:g.kind,key:g.id,label:g.label,planRevision:y,expectedPlanRevision:y}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:y??0,expectedPlanRevision:y??0}:null})(),scopePending:c.isPending||c.isFetching,scopeError:c.isError,onRetryScope:()=>{c.refetch()},templates:m};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(vr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(vr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(Hf,{projectName:t,onReviewDiscoveryProbe:g=>r({source:"discovery",discoveryProbeId:g})}):e.jsx(fl,{...f,onReviewForTracking:({researchRunQueryId:g,scope:y})=>r({source:"research",researchRunQueryId:g},y??null)})})]}):e.jsx(fl,{...f,viewerResearchConfig:l})}function Rf({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:d,preview:c,isPreviewing:h,isCommitting:u,onPreview:m,onCommit:f,publishGuard:g}){const[y,p]=o.useState(null),[b,C]=o.useState(()=>dr(s)),[v,$]=o.useState(null),R=o.useRef(null),x=o.useRef(null),N=Tc(t,s),w=o.useMemo(()=>Lf(t.tracked,s,t.mode),[s,t.mode,t.tracked]),P=rn({rows:w,getSearchText:Q=>`${Q.queryText} ${Q.provenance?.source??"legacy"} ${Q.assignments.map(B=>B.queryClass??"unknown").join(" ")}`});o.useEffect(()=>{if(N)return;if(!a){x.current=null;return}const Q=`${a}:${Qr(s)}`;if(x.current===Q)return;const B=t.tracked.find(D=>D.queryId===a);B&&(x.current=Q,p({kind:"edit",row:B,audience:t.mode==="advanced"?Vr(s):void 0,scopeLabel:zr(s,t)}),C(yl(B,s)),$(null))},[s,a,N,t]),o.useEffect(()=>{if(N||!l)return;const Q=dr(l.trackingSelection??s);p({kind:"add"}),C(l.source==="research"?{...Q,source:"research",researchRunQueryId:l.researchRunQueryId}:{...Q,source:"discovery",discoveryProbeId:l.discoveryProbeId}),$(null),i()},[i,l,s,N]),o.useEffect(()=>{N&&(p(null),$(null),a!==void 0&&r?.(void 0))},[r,a,N]),o.useEffect(()=>{if(!y||y.kind==="remove")return;const Q=R.current;Q&&(Q.scrollIntoView?.({block:"start"}),Q.focus({preventScroll:!0}))},[y]);function q(Q="manual"){p({kind:"add"}),C({...dr(s),source:Q}),$(null),r?.(void 0)}function S(Q){x.current=`${Q.queryId}:${Qr(s)}`,p({kind:"edit",row:Q,audience:t.mode==="advanced"?Vr(s):void 0,scopeLabel:zr(s,t)}),C(yl(Q,s)),$(null),r?.(Q.queryId)}function G(Q){x.current=`${Q.queryId}:${Qr(s)}`,p({kind:"remove",row:Q,audience:t.mode==="advanced"?Vr(s):void 0,scopeLabel:zr(s,t)}),$(null),r?.(Q.queryId)}function X(){p(null),$(null),r?.(void 0)}const T=y?Pf(y,b,t):null,F=y!==null&&y.kind==="add"&&t.mode==="advanced"&&!Wi(b),ae=T!==null&&(!F||b.contexts.length>0)&&!h;return N?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(A,{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($f,{selection:s,onSelectionChange:n}):null,e.jsx(Hs,{value:P.query,onChange:P.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!ie()&&e.jsxs(He,{type:"button",size:"sm",onClick:()=>q(),children:[e.jsx(dx,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[P.totalRows.toLocaleString("en-US")," saved query ",P.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."}),P.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:P.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:P.rows.map(Q=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:Q.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(Mf,{row:Q,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Df,{row:Q})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:qf(Q)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Of,{row:Q,outsidePlan:t.mode==="advanced"&&Q.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!ie()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(He,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${Q.queryText}`,onClick:()=>S(Q),children:[e.jsx(ux,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(He,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${Q.queryText}`,onClick:()=>G(Q),children:[e.jsx(Rc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},Q.queryId))})]})}),e.jsx(Es,{page:P.page,pageSize:P.pageSize,visibleRows:P.rows.length,totalRows:P.totalRows,itemLabel:"queries",onPageChange:P.setPage})]}),y&&!ie()&&e.jsx(Ff,{workspace:t,templates:d,action:y,draft:b,onDraftChange:Q=>{C(Q),$(null)},onClose:X,canReview:ae,isPreviewing:h,editorHeadingRef:R,onReview:()=>{T&&($(T),m(T))}}),c&&v&&y&&e.jsx(Uf,{preview:c,workspace:t,isCommitting:u,sweepActive:g?.sweepActive??!1,onConfirm:()=>{f({...v,expectedWorkspaceVersion:c.workspaceVersion,previewToken:c.previewToken,reviewedAt:c.reviewedAt})}})]})}function dr(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 yl(t,s){return{...dr(s),text:t.queryText,queryClass:"keep"}}function Pf(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=If(s);if(!r||Ai(s)||a&&!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const l=a?Tf(s,n):void 0;return{additions:[{input:r,...l?{audience:l}:{},...a&&!Wi(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...a&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function If(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 Tf(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 Wi(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function Ai(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Vr(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 zr(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 Yi(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 Lf(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=>Yi(r,s)))}function $f({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 Qr(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function qf(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 od(t,s,n){const a=new Map(s.targets.map(p=>[p.stableKey,p.label])),r=new Map(s.groups.map(p=>[p.stableKey,p.label])),l=new Map(s.markets.map(p=>[p.stableKey,p.label])),i=new Set(t.assignments.map(p=>p.targetKey));if(i.size===0)return"Whole site";const d=n?t.assignments.filter(p=>Yi(p,n)):t.assignments,c=new Set(d.map(p=>p.targetKey));if(n?.measurementScope==="group"){const p=c.size,b=Math.max(0,i.size-p);return[`${p} ${p===1?"property":"properties"} in this group`,...b?[`Shared with ${b} other ${b===1?"property":"properties"}`]:[]].join(" · ")}const h=new Set,u=new Set;for(const p of d)p.groupKeys.forEach(b=>h.add(b)),p.marketKeys.forEach(b=>u.add(b));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"}`]:c.size===1?[a.get([...c][0])??[...c][0]]:[`${c.size} properties`],g=h.size===1?r.get([...h][0])??[...h][0]:null,y=u.size===1?l.get([...u][0])??[...u][0]:null;return g&&y&&g===y?f.push(`${g} (group and market)`):(g?f.push(`Group: ${g}`):h.size>1&&f.push(`${h.size} groups`),y?f.push(`Market: ${y}`):u.size>1&&f.push(`${u.size} markets`)),f.join(" · ")}function Mf({row:t,workspace:s,selection:n}){const a=Ef(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:od(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 Ef(t,s,n){const a=new Map(s.targets.map(c=>[c.stableKey,c.label])),r=new Map(s.groups.map(c=>[c.stableKey,c.label])),l=new Map(s.markets.map(c=>[c.stableKey,c.label])),d=t.assignments.filter(c=>Yi(c,n)).map(c=>{const h=a.get(c.targetKey)??c.targetKey??"Whole site",u=n.measurementScope==="group"&&n.measurementScopeKey?c.groupKeys.filter(f=>f===n.measurementScopeKey).map(f=>r.get(f)??f):c.groupKeys.map(f=>r.get(f)??f),m=n.measurementScope==="market"&&n.measurementScopeKey?c.marketKeys.filter(f=>f===n.measurementScopeKey).map(f=>l.get(f)??f):c.marketKeys.map(f=>l.get(f)??f);return[h,u.length?`Groups: ${u.join(", ")}`:null,m.length?`Markets: ${m.join(", ")}`:null].filter(f=>f!==null).join(" · ")});return[...new Set(d)].length?[...new Set(d)]:["Whole site"]}function Df({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(ge,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function Of({row:t,outsidePlan:s=!1}){return s?e.jsx(ge,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(ge,{tone:"positive",children:"Measured"}):e.jsx(ge,{tone:"caution",children:"Awaiting sweep"})}function Ff({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:d,editorHeadingRef:c,onReview:h}){const u=s.length>0;return n.kind==="remove"?e.jsxs(je,{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(Hr,{canReview:i,isPreviewing:d,onCancel:l,onReview:h})]}):n.kind==="edit"?e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Edit query"}),e.jsx(A,{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:m=>r({...a,text:m.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:m=>r({...a,queryClass:m.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(Hr,{canReview:i,isPreviewing:d,onCancel:l,onReview:h})]}):e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Add query"}),e.jsx(A,{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:m=>r({...a,text:m.target.value})})]}):null,a.source==="template"?e.jsx(Gf,{templates:s,advanced:t.mode==="advanced",draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(bl,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(m=>({id:m.researchRunQueryId,label:m.queryText,detail:m.researchRunId})),onChange:m=>r({...a,researchRunQueryId:m})}):null,a.source==="discovery"?e.jsx(bl,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(m=>({id:m.discoveryProbeId,label:m.queryText,detail:m.discoverySessionId})),onChange:m=>r({...a,discoveryProbeId:m})}):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:m=>r({...a,source:m.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(Kf,{workspace:t,draft:a,onDraftChange:r}):null]}),t.mode==="advanced"&&!Wi(a)?e.jsx("div",{className:"mt-4",children:e.jsx(_f,{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:m=>r({...a,queryClass:m.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(Hr,{canReview:i,isPreviewing:d,onCancel:l,onReview:h})]})}function Gf({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":Ai(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]}),Ai(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 bl({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 Ji(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function ha(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 ld(t){return[...new Map(t.map(s=>[ha(s),s])).values()]}function Xi(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 _f({workspace:t,draft:s,onDraftChange:n}){const a=o.useMemo(()=>ld([...t.defaultContexts.map(Ji),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?ha(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(c=>ha(c)===l.target.value),d=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:d})},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:ha(l),children:Xi(l)},ha(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 Kf({workspace:t,draft:s,onDraftChange:n}){const{canWrite:a}=Ys(),[r,l]=o.useState(""),[i,d]=o.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),c=o.useMemo(()=>[...t.targets.map(y=>({kind:"target",key:y.stableKey,label:y.label,detail:"Property"})),...t.groups.map(y=>({kind:"group",key:y.stableKey,label:y.label,detail:"Group"})),...t.markets.map(y=>({kind:"market",key:y.stableKey,label:y.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),h=r.trim().toLocaleLowerCase(),u=h?c.filter(y=>`${y.label} ${y.detail}`.toLocaleLowerCase().includes(h)):c,m=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function f(y,p,b){const C=y==="target"?"targetKeys":y==="group"?"groupKeys":"marketKeys",v=s[C];n({...s,wholeSite:!1,[C]:b?[...v,p]:v.filter($=>$!==p)})}function g(y,p){return(y==="target"?s.targetKeys:y==="group"?s.groupKeys:s.marketKeys).includes(p)}if(!i){const y=t.targets.find(p=>p.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: ",y?.label??s.targetKeys[0]]}),e.jsx(A,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>d(!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:y=>{n({...s,wholeSite:y.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Every location (",t.targets.length,")"]}):null,!s.wholeSite&&!m?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(Hs,{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(y=>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":`${y.label}, ${y.detail}`,checked:g(y.kind,y.key),onChange:p=>f(y.kind,y.key,p.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:y.label}),e.jsx("span",{className:"text-xs text-muted",children:y.detail})]},`${y.kind}:${y.key}`))})]})}function Hr({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(He,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(A,{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 Uf({preview:t,workspace:s,isCommitting:n,sweepActive:a,onConfirm:r}){const l=o.useRef(null);o.useEffect(()=>{const h=l.current;h&&(typeof h.scrollIntoView=="function"&&h.scrollIntoView({block:"start"}),h.focus({preventScroll:!0}))},[t]);const i=!t.diff.noOp,d=i?t.mode==="advanced"?"After you publish, AI Visibility keeps showing the last sweep until the next sweep. Location pages and competitor results show no numbers until then. Past answers are kept.":"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged.",c=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(h=>h.rows.length>0);return e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:l,tabIndex:-1,children:i?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:Bf(t)}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:d})]}),e.jsx(ge,{tone:i?"caution":"neutral",children:i?"Ready to confirm":"No-op"})]}),c.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:c.map(h=>e.jsx(vl,{label:h.label,rows:h.rows,workspace:s,tracked:t.tracked},h.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(vl,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(He,{type:"button",size:"sm",disabled:!i||n||a,onClick:r,children:n?"Confirming…":"Confirm changes"}),i&&a?e.jsx("p",{role:"status",className:"text-sm leading-5 text-caution",children:"A sweep is queued or running. Publish after it finishes."}):null]})]})}function Bf(t){const{added:s}=t.diff,n=new Set(t.tracked.map(c=>c.queryId)),a=t.diff.removed.filter(c=>!n.has(c.queryId)),{addedProviderCalls:r,removedProviderCalls:l,nextSweepProviderCalls:i}=t.workload,d=c=>c.toLocaleString("en-US");return[s.length>0?`+${d(s.length)} ${s.length===1?"query":"queries"}`:null,a.length>0?`−${d(a.length)} ${a.length===1?"query":"queries"}`:null,`+${d(r)} / −${d(l)} answers per sweep`,`next sweep asks ${d(i)}`].filter(c=>c!==null).join(" · ")}function vl({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`:zf(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(Vf,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function Vf({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(c=>c.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",d=a.contexts.map(c=>Xi(Ji(c))).join("; ");return e.jsx("li",{children:[l,i,d].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function zf(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=ld(a.assignments.flatMap(i=>i.contexts).map(Ji)),l=r.length===1?Xi(r[0]):r.length>1?`${r.length} contexts`:null;return[od(a,n),l].filter(i=>i!==null).join(" · ")}function Qf({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,publishGuard:d}){const c=bs(),[h,u]=o.useState(null),m=$e({...Oi({client:ne,path:{name:t}})}),f=$e({...gc({client:ne,path:{name:t}}),staleTime:6e4}),g=Kt({...Xu(),onSuccess:p=>u(p),onError:async p=>{u(null),await c.invalidateQueries({queryKey:Ju({client:ne,path:{name:t}})}),De({title:"Could not review tracking changes",detail:p instanceof Error?p.message:"Update the draft and review it again.",tone:"negative"})}}),y=Kt({...Zu(),onSuccess:async p=>{u(null),r?.(void 0),await yo(c,t),De({title:p.committed?"Tracked queries updated":"No tracked-query change",detail:p.committed&&p.mode==="advanced"?"New numbers after the next sweep.":void 0,tone:p.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async p=>{u(null),await yo(c,t),De({title:"Could not confirm tracking changes",detail:p instanceof Error?p.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return m.isLoading?e.jsx(je,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):m.isError||!m.data?e.jsxs(je,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{m.refetch()},children:"Try again"})]}):e.jsx(Rf,{workspace:m.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,publishGuard:d,templates:f.data?.templates??[],preview:h,isPreviewing:g.isPending,isCommitting:y.isPending,onPreview:p=>{u(null),g.mutate({client:ne,path:{name:t},body:{...p,expectedWorkspaceVersion:m.data.workspaceVersion}})},onCommit:p=>y.mutate({client:ne,path:{name:t},body:p})})}function Hf({projectName:t,onReviewDiscoveryProbe:s}){const n=bs(),[a,r]=o.useState(null),[l,i]=o.useState(""),[d,c]=o.useState("100"),h=$e({...em({client:ne,path:{name:t},query:{limit:"10"}}),refetchInterval:v=>v.state.data?.some(R=>ki.has(R.status))?3e3:!1}),u=h.data??[];o.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const m=u.find(v=>v.id===a)??null,f=$e({...tm({client:ne,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:m&&ki.has(m.status)?3e3:!1}),g=f.data??null,y=Kt({mutationFn:()=>{const v={},$=l.trim();$&&(v.icpDescription=$);const R=Number.parseInt(d,10);return Number.isFinite(R)&&R>0&&(v.maxProbes=R),sm(t,v)},onSuccess:async v=>{r(v.sessionId),i(""),await Xf(n,t,v.sessionId),De({title:"Discovery started",detail:`Run ${Wr(v.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${v.sessionId}`,dedupeMode:"replace"})},onError:v=>{De({title:"Discovery failed to start",detail:v instanceof Error?v.message:"Could not start discovery.",tone:"negative"})}}),p=g??m,b=o.useMemo(()=>(g?.probes??[]).slice(0,30),[g?.probes]);async function C(){try{const v=await h.refetch();if(v.error)throw v.error;const $=v.data?.length??0;De({title:"Discovery sessions refreshed",detail:`${$} recent session${$===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(v){De({title:"Discovery refresh failed",detail:v instanceof Error?v.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:ie()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{C()},children:[e.jsx(wa,{className:`size-3.5 ${h.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(je,{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(ge,{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:v=>i(v.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:d,onChange:v=>c(v.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."})]}),!ie()&&e.jsxs(He,{type:"button",size:"sm",disabled:y.isPending,onClick:()=>y.mutate(),children:[e.jsx(hr,{size:14}),y.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(je,{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"})]}),h.isFetching&&e.jsx(ge,{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(v=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===v.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(v.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:Wr(v.id)}),e.jsx(ge,{tone:jl(v.status),children:v.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",v.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",v.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",v.wastedCount??0]})]})]},v.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(je,{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:p?Wr(p.id):"No run selected"})]}),p&&e.jsx(ge,{tone:jl(p.status),children:p.status})]}),p?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Wa,{label:"Questions tested",value:p.probeCount??0}),e.jsx(Wa,{label:"Cited queries",value:p.citedCount??0,tone:"positive"}),e.jsx(Wa,{label:"Worth tracking",value:p.aspirationalCount??0,tone:"caution"}),e.jsx(Wa,{label:"Skip",value:p.wastedCount??0,tone:"negative"})]}),p.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:p.error}),p.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:p.warning}),p.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:p.icpDescription})]}),p.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:p.competitorMap.slice(0,8).map(v=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[v.domain," ",e.jsx("span",{className:"text-muted",children:v.hits})]},v.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),p?.status==="completed"&&e.jsxs(je,{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(je,{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(ge,{tone:"neutral",children:"Loading"})]}),b.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:b.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:v.query}),e.jsx("td",{children:e.jsx(ge,{tone:Wf(v.bucket),children:Jf(v.bucket)})}),e.jsx("td",{className:"text-secondary",children:v.citedDomains.length>0?v.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!ie()&&s&&(v.bucket==="cited"||v.bucket==="aspirational")&&e.jsx(He,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(v.id),children:"Review for tracking"})})]},v.id))})]})})]})]})]})]})}function Wa({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 jl(t){return t==="completed"?"positive":t==="failed"?"negative":ki.has(t)?"caution":"neutral"}function Wf(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Yf={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Jf(t){return t?Yf[t]:"Not classified"}function Wr(t){return t.length>8?t.slice(0,8):t}async function Xf(t,s,n){await Promise.all([Dt(t,"discovery"),t.invalidateQueries({queryKey:nm({client:ne})})])}function Zf({projectName:t}){const[s,n]=o.useState("changes"),[a,r]=o.useState(null),[l,i]=o.useState(null),d=$e({...am({client:ne,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=$e({...oc({client:ne,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(c.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),u=l??h[0]?.id??"",m=a??h.find(b=>b.id!==u)?.id??"",f=!!(m&&u&&m!==u),g=$e({...rm({client:ne,path:{name:t},query:{run1:m,run2:u}}),enabled:s==="compare"&&f}),y=d.data??[],p=g.data?.diff.filter(b=>b.changed||b.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(([b,C])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:C},b))}),s==="changes"?e.jsx(yx,{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."})]}),d.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!d.isLoading&&y.length===0?e.jsxs(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Jt()?Wn:"Complete an answer visibility sweep to create the first snapshot."})]}):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:"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:y.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(b.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.mentionedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Je(b.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.citedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Je(b.overallCitedRate)})]},b.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:m,onChange:b=>r(b.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:h.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:u,onChange:b=>i(b.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:h.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]})]}),c.isLoading||g.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&h.length<2?e.jsxs(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Jt()?Wn:"Run another answer visibility sweep before comparing historical evidence."})]}):null,g.data&&p.length===0?e.jsxs(je,{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,p.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:p.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ge,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ge,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const Nl={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},ey={contract:null,assessment:null,googleAds:Nl,gtm:Nl,snapshots:[]};function ty(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":ry(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function sy(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 ny(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 ay(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 cd(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"&&iy(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 ry(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function iy(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function dd(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 oy(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 ly(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 jn(t){return t.length<=12?t:`…${t.slice(-10)}`}function cy(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 dy(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 Yr={"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 wl(t){return t.outcome==="pass"?{label:Yr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Yr[t.code],tone:"negative",outcome:"Fail"}:{label:Yr[t.code],tone:"caution",outcome:"Unknown"}}function uy(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function my(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 hy(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function Sl({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=dd(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(ge,{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(He,{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 xy="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.",py="Available once Google Ads and Tag Manager are connected.",gy="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 fy({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:l}){const i=t.googleAds.state==="connected",d=t.gtm.state==="connected",c=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",u=c||h||t.gtm.state==="unavailable",m={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},f=!i&&!d,g=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:c?m:ny(t)},{title:"Tag Manager",state:t.gtm.state,ready:d,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?m:ay(t)}],y=i&&d&&!u?cd(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(Fe,{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:gy}):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(Fe,{text:xy})]}),y&&s?e.jsx(He,{type:"button",disabled:r,onClick:()=>s(y.id),children:r?"Working…":y.label}):e.jsx("p",{className:"text-sm text-secondary",children:py})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:g.map(p=>{const b=p.ready?{label:"Ready",tone:"positive"}:dd(p.state),C=p.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:p.title}),e.jsx(ge,{tone:b.tone,children:b.label}),p.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:p.summary}):null,C&&s?C.id==="retry-connection-status"?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):e.jsx(He,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):null,p.summary&&p.onChange?e.jsx(He,{type:"button",variant:"ghost",size:"sm","aria-label":p.changeLabel,disabled:r,onClick:p.onChange,children:"Change"}):null]},p.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function yy({workspace:t=ey,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:d=null,onRetryContracts:c,onRetryEvidence:h,onChangeGoogleAdsSelection:u,onChangeGtmSelection:m,onAddContract:f}){const g=ty(t),y=sy(g),p=cd(t),b=t.assessment?.findings??[],C=b.filter(x=>x.outcome!=="pass"),v=b.filter(x=>x.outcome==="pass"),$=C.some(x=>x.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&d===null?e.jsx(fy,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:m,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(ge,{tone:y.tone,children:y.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:y.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(x=>e.jsxs("li",{className:"break-words",children:[hy(x)," ",x.kind,", captured ",Xt(x.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",x.id,")"]})]},x.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?p.id==="review-findings"||p.id==="review-runtime-verification"||p.id==="retry-connection-status"||p.id==="select-contract"||p.id==="retry-integrity"||p.id==="waiting-for-integrity"?e.jsx(A,{type:"button",disabled:n||p.id==="waiting-for-integrity",onClick:()=>s(p.id),children:n?"Working…":p.label}):e.jsx(He,{type:"button",disabled:n,onClick:()=>s(p.id),children:n?"Working…":p.label}):p.id==="review-findings"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):g==="runtime-unverified"?e.jsx(A,{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:p.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(He,{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:x=>i?.(x.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(x=>e.jsx("option",{value:x.id,children:x.name},x.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:cy(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:dy(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:jn(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:jn(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:jn(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:jn(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."}),d?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:d}),c?e.jsx(A,{type:"button",variant:"outline",onClick:c,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(ge,{tone:$,children:[C.length," ",C.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:C.map(x=>{const N=wl(x);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:N.label}),e.jsx(ge,{tone:N.tone,children:N.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",x.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",x.code]}),x.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",x.evidenceIds.join(", ")]}):null]},`${x.code}:${x.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(Fe,{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(x=>{const N=oy(x.key,g);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 ${N==="positive"?"bg-positive-fill":N==="caution"?"bg-caution-fill":N==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:x.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:x.detail}),e.jsx(ge,{tone:N,children:ly(x.key,g)})]},x.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:[Sl({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),Sl({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:m}:{},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)&&h?e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:h,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(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:x.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:x.kind}),e.jsx("td",{className:"text-secondary",children:Xt(x.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:jn(x.id)})]},x.id))})]})})]}):null,v.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[v.length," ",v.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:v.map(x=>{const N=wl(x);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:N.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",x.code]}),x.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",x.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(ge,{tone:N.tone,children:N.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:x.subject})]},`${x.code}:${x.subject}`)})})]})})]}):null,g==="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 ",uy(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:jn(t.contract.gtm.tagId)})," fires with ",my(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:jn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Nn=3e4,Cl={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",ps="text-sm font-medium text-secondary";function kl(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:Ct(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Ya(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function by(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 vy(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function jy(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:vy(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 Ny(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:Ya(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Ya(t.triggerIds),variableIds:Ya(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Ya(t.productionHosts)}}}function Al(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 Ja(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 Xa(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Za({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:ps,children:[s,e.jsx("select",{id:t,className:Ut,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function Fn({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 Rl({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[d,c]=o.useState(null),h=o.useRef(null),u=o.useRef(null),m=o.useRef(!1);o.useEffect(()=>{const p=m.current;m.current=a,a?u.current?.focus():p&&h.current?.querySelector("button")?.focus()},[a]);function f(){c(null),r(!0)}function g(){c(null),r(!1)}async function y(){i(!0),c(null);try{await n()}catch(p){c(Ct(p)),i(!1)}}return e.jsx("div",{ref:h,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(A,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:g,children:"Keep connected"}),e.jsx(He,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{y()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),d?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:d}):null]}):e.jsxs(He,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:f,children:["Disconnect ",t]})})}function Pl({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:d,value:c,onChange:h}){const u=n.some(p=>p.id===c),[m,f]=o.useState(!1),g=m||c!==""&&!u&&n.length>0,y=e.jsx("label",{htmlFor:t,className:ps,children:s});return r?e.jsxs("div",{children:[y,e.jsx("select",{id:t,className:Ut,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Ut,value:c,onChange:p=>h(p.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:[y,e.jsx("input",{id:t,required:!0,className:Ut,value:c,onChange:p=>h(p.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":d})]}):e.jsxs("div",{children:[y,g?e.jsx("input",{id:t,required:!0,className:Ut,value:c,onChange:p=>h(p.target.value)}):e.jsxs("select",{id:t,required:!0,className:Ut,value:c,onChange:p=>h(p.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(p=>e.jsxs("option",{value:p.id,children:[p.name,p.detail?` (${p.detail})`:"",p.active?"":" — inactive"]},p.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{f(!g),h("")},children:g?"Choose from synced list":"Enter an ID manually"})]})}function wy({projectId:t,projectName:s}){const n=Ys(),[a,r]=o.useState(null),[l,i]=o.useState(null),[d,c]=o.useState(!1),[h,u]=o.useState(""),[m,f]=o.useState(null),[g,y]=o.useState(!1),[p,b]=o.useState(!1),[C,v]=o.useState(""),[$,R]=o.useState(""),[x,N]=o.useState(""),[w,P]=o.useState(""),[q,S]=o.useState(""),[G,X]=o.useState(!1),[T,F]=o.useState(Cl),[ae,Q]=o.useState(null),B=o.useRef(null),D=$e({...im({client:ne,path:{name:s}}),staleTime:Nn}),Y=$e({...om({client:ne,path:{name:s}}),staleTime:Nn}),E=$e({...lm({client:ne,path:{name:s}}),staleTime:Nn}),W=$e({...cm({client:ne,path:{name:s}}),staleTime:Nn}),L=W.data,ee=$e({...dm({client:ne,path:{name:s},query:{limit:5}}),staleTime:Nn}),K=$e({...um({client:ne,path:{name:s},query:{limit:5}}),staleTime:Nn}),se=E.data??[],Se=(ae?se.find(M=>M.id===ae)??null:null)??(se.length===1?se[0]??null:null),Z=se.length>1&&!Se,me=$e({...mm({client:ne,path:{name:s,contractId:Se?.id??""}}),enabled:!!Se,staleTime:Nn}),Ce=$e({...hm({client:ne,path:{name:s}}),enabled:m==="google-ads"&&D.data?.connected===!0,staleTime:0}),J=$e({...xm({client:ne,path:{name:s}}),enabled:m==="gtm"&&Y.data?.connected===!0,staleTime:0}),he=$e({...pm({client:ne,path:{name:s,accountId:x}}),enabled:m==="gtm"&&!!x,staleTime:0}),_=$e({...gm({client:ne,path:{name:s,accountId:x,containerId:w}}),enabled:m==="gtm"&&!!x&&!!w,staleTime:0}),pe=Kt(fm({client:ne})),Me=Kt(ym({client:ne})),Pe=Kt(bm({client:ne})),re=Kt(vm({client:ne})),be=Kt(jm({client:ne})),Ne=Kt(Nm({client:ne})),_e=Kt(wm({client:ne})),Oe=Kt(Sm({client:ne})),O=Kt(Cm({client:ne}));o.useEffect(()=>{if(m!=="google-ads"||g||!D.isSuccess)return;const M=D.data.connection?.selection;v(M?.customerId??""),R(M?.loginCustomerId??""),y(!0)},[g,D.data,D.isSuccess,m]),o.useEffect(()=>{if(m!=="gtm"||p||!Y.isSuccess)return;const M=Y.data.selection;N(M?.accountId??""),P(M?.containerId??""),S(M?.workspaceId??""),b(!0)},[p,Y.data,Y.isSuccess,m]),o.useEffect(()=>{!ae||!E.data||E.data.some(M=>M.id===ae)||Q(null)},[E.data,ae]);const U=o.useMemo(()=>{const M=ee.data?.snapshots??[],ve=K.data?.snapshots??[],et=[...M.map(gt=>({id:gt.id,provider:"google-ads",kind:gt.kind,capturedAt:gt.capturedAt})),...ve.map(gt=>({id:gt.id,provider:"gtm",kind:gt.kind,capturedAt:gt.capturedAt}))].sort((gt,Ks)=>Ks.capturedAt.localeCompare(gt.capturedAt)).slice(0,5),Rt=[],qt=me.data?.googleAdsSnapshot,Ve=me.data?.gtmSnapshot;return qt&&Rt.push({id:qt.id,provider:"google-ads",kind:qt.kind,capturedAt:qt.capturedAt}),Ve&&Rt.push({id:Ve.id,provider:"gtm",kind:Ve.kind,capturedAt:Ve.capturedAt}),{contract:me.data?.assessment.contract??Se,assessment:me.data?.assessment??null,contractSelectionRequired:Z,assessmentState:Se?me.isError?"unavailable":me.isLoading?"loading":void 0:void 0,assessmentError:me.isError?Ct(me.error):null,googleAds:by(D.data,kl(ee.data?.total??0,ee.isLoading,ee.isError,ee.error),D.isError),gtm:jy(Y.data,kl(K.data?.total??0,K.isLoading,K.isError,K.error),Y.isError),snapshots:et,assessmentEvidenceSnapshots:Rt}},[Se,Z,ee.data,ee.error,ee.isError,ee.isLoading,D.data,D.isError,K.data,K.error,K.isError,K.isLoading,Y.data,Y.isError,me.data,me.error,me.isError,me.isLoading]),V=o.useSyncExternalStore(cc,ur,ur),Le=Object.values(V.runs).some(M=>M.projectId===t&&(M.kind===Ds["google-ads-sync"]||M.kind===Ds["gtm-sync"])),ze=pe.isPending||Me.isPending||Pe.isPending||re.isPending||be.isPending||Ne.isPending||_e.isPending||Oe.isPending||O.isPending||Le;async function Ue(){await Promise.all([D.refetch(),Y.refetch(),E.refetch(),ee.refetch(),K.refetch(),W.refetch(),Se?me.refetch():Promise.resolve()])}async function dt(M){await Ue();for(let ve=0;ve<10&&!M();ve+=1)await new Promise(et=>setTimeout(et,1500)),await Ue()}function de(){const M=document.activeElement;B.current=M instanceof HTMLElement?M:null}function Tt(M){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(M);return}globalThis.setTimeout(M,0)}function vt(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function We(M){if(!M)return;!M.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!M.hasAttribute("tabindex")&&(M.tabIndex=-1),M.focus({preventScroll:!0})}function Xe(M,ve=M){const et=document.getElementById(M);et instanceof HTMLDetailsElement&&(et.open=!0);const Rt=et?.scrollIntoView;typeof Rt=="function"&&Rt.call(et,{behavior:vt()?"auto":"smooth",block:"start"}),We(document.getElementById(ve)??et)}function mt(M,ve){de(),Tt(()=>Xe(M,ve))}function Ze(){const M=B.current;B.current=null,M&&Tt(()=>{M.isConnected&&M.focus({preventScroll:!0})})}function jt(){r(null),c(!1),Ze()}function at(){r(null),f(null),Ze()}function Ft(){r(null),X(!1),Ze()}function Pt(){r(null),f(null),c(!0),mt("google-ads-connect-panel","google-ads-connect-title")}function k(){r(null),v(""),R(""),y(!1),f("google-ads"),c(!1),mt("google-ads-selection-panel","google-ads-selection-title")}function xe(){r(null),N(""),P(""),S(""),b(!1),f("gtm"),c(!1),mt("gtm-selection-panel","gtm-selection-title")}function Ke(){r(null),X(!0),mt("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Ie(M,ve){lc({id:M.id,projectId:M.projectId,kind:M.kind,projectLabel:s,sourceAction:ve}),De({title:ve==="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:${M.id}`,dedupeMode:"replace"})}async function At(){Ps(n),r(null);try{const M=await pe.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});u(""),c(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Al(M.authorizationUrl,()=>{Ue(),i(null),Ze()})}catch(M){r(Ct(M))}}async function ht(){Ps(n),r(null);try{const M=await Me.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."),Al(M.authorizationUrl,()=>{Ue(),i(null),Ze()})}catch(M){r(Ct(M))}}async function Ge(){if(Ps(n),!C){r("Select a Google Ads customer before saving.");return}r(null);try{await Pe.mutateAsync({path:{name:s},body:{customerId:C,...$.trim()?{loginCustomerId:$.trim()}:{}}}),f(null),Ze(),await dt(()=>D.data?.selectedCustomer!=null)}catch(M){r(Ct(M))}}async function te(){if(Ps(n),!x||!w){r("Select a Tag Manager account and container before saving.");return}r(null);try{await re.mutateAsync({path:{name:s},body:{accountId:x,containerId:w,...q?{workspaceId:q}:{}}}),f(null),Ze(),await dt(()=>Y.data?.status==="connected")}catch(M){r(Ct(M))}}async function Be(){Ps(n),r(null),await _e.mutateAsync({path:{name:s}}),f(null),c(!1),v(""),R(""),y(!1),i(null),await Ue(),De({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),B.current=null,Tt(()=>We(document.getElementById("conversion-integrity-title")))}async function Ee(){Ps(n),r(null),await Oe.mutateAsync({path:{name:s}}),f(null),N(""),P(""),S(""),b(!1),i(null),await Ue(),De({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),B.current=null,Tt(()=>We(document.getElementById("conversion-integrity-title")))}async function Ae(){Ps(n),r(null);try{const M=await be.mutateAsync({path:{name:s}});Ie(M,"google-ads-sync")}catch(M){r(Ct(M))}}async function rt(){Ps(n),r(null);try{const M=await Ne.mutateAsync({path:{name:s}});Ie(M,"gtm-sync")}catch(M){r(Ct(M))}}async function Zt(){Ps(n),r(null);try{const M=await Promise.allSettled([be.mutateAsync({path:{name:s}}),Ne.mutateAsync({path:{name:s}})]),[ve,et]=M;ve.status==="fulfilled"&&Ie(ve.value,"google-ads-sync"),et.status==="fulfilled"&&Ie(et.value,"gtm-sync");const Rt=M.find(qt=>qt.status==="rejected");if(Rt?.status==="rejected")throw Rt.reason}catch(M){r(Ct(M))}}async function es(){Ps(n);const M=D.data?.connection?.selection.customerId,ve=Y.data?.selection;if(!M||!ve?.accountId||!ve.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const et=await O.mutateAsync({path:{name:s},body:Ny(T,M,{accountId:ve.accountId,containerId:ve.containerId})});F(Cl),X(!1),Ze(),(await E.refetch()).data?.some(qt=>qt.id===et.id)&&Q(et.id)}catch(et){r(Ct(et))}}function Qt(M){switch(M){case"connect-google-ads":Pt();return;case"connect-gtm":de(),ht();return;case"select-google-ads":k();return;case"select-gtm":xe();return;case"sync-google-ads":Ae();return;case"sync-gtm":rt();return;case"sync-static-evidence":Zt();return;case"declare-contract":Ke();return;case"review-findings":mt("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":mt("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Ue();return;case"select-contract":mt("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":me.refetch();return;case"waiting-for-integrity":return}}const St=Ce.data?.customers??[],ft=J.data?.accounts??[],ls=he.data?.containers??[],it=_.data?.workspaces??[],vs=!!C&&!St.some(M=>M.customerId===C),Fs=!!x&&!ft.some(M=>M.id===x),Nt=!!w&&!ls.some(M=>M.id===w),Gs=!!q&&!it.some(M=>M.id===q),Lt=vs&&Ce.isSuccess&&Ce.data.truncated===!1,As=Fs&&J.isSuccess&&J.data.truncated===!1,ts=Nt&&he.isSuccess&&he.data.truncated===!1,ss=Gs&&_.isSuccess&&_.data.truncated===!1,xt=As||ts||ss,Ht=As?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":ts?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":ss?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,ns=Xa(Lt,Ce.data,Ce.isError),as=Xa(As,J.data,J.isError),$t=Xa(ts,he.data,he.isError),js=Xa(ss,_.data,_.isError),pt=Ce.isError?Ct(Ce.error):null,yt=J.isError?Ct(J.error):he.isError?Ct(he.error):_.isError?Ct(_.error):null,Ns=m==="google-ads"?pt:m==="gtm"?yt:null,_s=Ja("customer",Ce.data,St.length),z=Ja("account",J.data,ft.length),oe=Ja("container",he.data,ls.length),ke=Ja("draft workspace",_.data,it.length),le=J.isError||he.isError||_.isError&&!!q,Re=d||m!==null||G;function qe(){Ce.refetch()}function cs(){if(J.isError){J.refetch();return}if(he.isError){he.refetch();return}_.isError&&_.refetch()}return D.isLoading||Y.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(M=>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"})]},M))}),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(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{E.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(yy,{workspace:U,onPrimaryAction:Qt,actionPending:ze,actionError:Re?null:a,contracts:se,selectedContractId:Se?.id??null,onSelectContract:M=>Q(M||null),contractError:E.isError?Ct(E.error):null,onRetryContracts:()=>{E.refetch()},onRetryEvidence:()=>{Promise.all([ee.refetch(),K.refetch()])},onChangeGoogleAdsSelection:k,onChangeGtmSelection:xe,onAddContract:()=>Qt("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,d?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:Ye(async M=>{M.preventDefault(),await At()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ps,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:M=>u(M.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(He,{type:"submit",disabled:pe.isPending,children:pe.isPending?"Starting…":"Continue to Google"}),e.jsx(A,{type:"button",variant:"outline",onClick:jt,children:"Cancel"})]})]})]}):null,m==="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"})]})}),Ns?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Ns}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:qe,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(Za,{id:"google-ads-customer",label:"Customer account",value:C,onChange:M=>{y(!0),v(M);const ve=St.find(et=>et.customerId===M);R(ve?.parentCustomerId??"")},disabled:Ce.isLoading,children:[e.jsx("option",{value:"",children:Ce.isLoading?"Loading accessible customers…":"Select a customer"}),vs?e.jsxs("option",{value:C,disabled:Lt,children:["Saved customer ",C," (",ns,")"]}):null,St.map(M=>e.jsx("option",{value:M.customerId,children:M.descriptiveName??`Customer ${M.customerId}`},M.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ps,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Ut,value:$,onChange:M=>{y(!0),R(M.target.value)},placeholder:"Use only when a manager context is required"})]})]}),_s?e.jsx("p",{role:"status",className:`mt-3 text-sm ${Ce.data?.truncated?"text-caution":"text-secondary"}`,children:_s}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(He,{type:"button",disabled:Pe.isPending||Ce.isLoading||Ce.isError||Lt||!C,onClick:Ye(Ge),children:Pe.isPending?"Saving…":"Save customer selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:at,children:"Cancel"})]}),D.data?.connected?e.jsx(Rl,{providerLabel:"Google Ads",disabled:ze,onDisconnect:Be}):null]}):null,m==="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"})]})}),Ns?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Ns}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:cs,children:J.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(Za,{id:"gtm-account",label:"Account",value:x,onChange:M=>{b(!0),M!==x&&(P(""),S("")),N(M)},disabled:J.isLoading,children:[e.jsx("option",{value:"",children:J.isLoading?"Loading accounts…":"Select an account"}),Fs?e.jsxs("option",{value:x,disabled:As,children:["Saved account ",x," (",as,")"]}):null,ft.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]}),e.jsxs(Za,{id:"gtm-container",label:"Container",value:w,onChange:M=>{b(!0),M!==w&&S(""),P(M)},disabled:!x||he.isLoading,children:[e.jsx("option",{value:"",children:he.isLoading?"Loading containers…":"Select a container"}),Nt?e.jsxs("option",{value:w,disabled:ts,children:["Saved container ",w," (",$t,")"]}):null,ls.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]}),e.jsxs(Za,{id:"gtm-workspace",label:"Draft workspace (optional)",value:q,onChange:M=>{b(!0),S(M)},disabled:!w||_.isLoading,children:[e.jsx("option",{value:"",children:_.isLoading?"Loading workspaces…":"No draft workspace"}),Gs?e.jsxs("option",{value:q,disabled:ss,children:["Saved draft workspace ",q," (",js,")"]}):null,it.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[z?e.jsx("p",{role:"status",className:J.data?.truncated?"text-caution":"text-secondary",children:z}):null,oe?e.jsx("p",{role:"status",className:he.data?.truncated?"text-caution":"text-secondary",children:oe}):null,ke?e.jsx("p",{role:"status",className:_.data?.truncated?"text-caution":"text-secondary",children:ke}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(He,{type:"button",disabled:re.isPending||J.isLoading||he.isLoading||_.isLoading&&!!q||le||xt||!x||!w,onClick:Ye(te),children:re.isPending?"Saving…":"Save container selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:at,children:"Cancel"})]}),Y.data?.connected?e.jsx(Rl,{providerLabel:"Tag Manager",disabled:ze,onDisconnect:Ee}):null]}):null,G?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:Ye(async M=>{M.preventDefault(),await es()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ps,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Ut,value:T.name,onChange:M=>F(ve=>({...ve,name:M.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ps,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Ut,value:T.eventName,onChange:M=>F(ve=>({...ve,eventName:M.target.value})),placeholder:"booking_complete"})]}),e.jsx(Pl,{id:"contract-conversion-action",label:"Google Ads conversion action",options:L?.googleAds.conversionActions??[],synced:L?.googleAds.syncedAt!=null,loading:W.isLoading,failed:W.isError,onRetry:()=>{W.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:T.conversionActionId,onChange:M=>F(ve=>({...ve,conversionActionId:M}))}),e.jsx(Pl,{id:"contract-gtm-tag",label:"Tag Manager tag",options:L?.gtm.tags??[],synced:L?.gtm.syncedAt!=null,loading:W.isLoading,failed:W.isError,onRetry:()=>{W.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:T.tagId,onChange:M=>F(ve=>({...ve,tagId:M}))})]}),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:ps,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Ut,value:T.conversionId,onChange:M=>F(ve=>({...ve,conversionId:M.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ps,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Ut,value:T.conversionLabel,onChange:M=>F(ve=>({...ve,conversionLabel:M.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ps,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Ut,value:T.triggerIds,onChange:M=>F(ve=>({...ve,triggerIds:M.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ps,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Ut,value:T.variableIds,onChange:M=>F(ve=>({...ve,variableIds:M.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ps,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Ut,value:T.campaignIds,onChange:M=>F(ve=>({...ve,campaignIds:M.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ps,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Ut,value:T.productionHosts,onChange:M=>F(ve=>({...ve,productionHosts:M.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(Fn,{id:"contract-primary-action",checked:T.requirePrimaryAction,onChange:M=>F(ve=>({...ve,requirePrimaryAction:M})),children:"Google Ads action is primary"}),e.jsx(Fn,{id:"contract-biddable-goal",checked:T.requireBiddableGoal,onChange:M=>F(ve=>({...ve,requireBiddableGoal:M})),children:"Google Ads goal is biddable"}),e.jsx(Fn,{id:"contract-runtime-verification",checked:T.verificationRequired,onChange:M=>F(ve=>({...ve,verificationRequired:M})),children:"Runtime proof is required"}),e.jsx(Fn,{id:"contract-transaction-id",checked:T.requireTransactionId,onChange:M=>F(ve=>({...ve,requireTransactionId:M})),children:"Transaction ID is required"}),e.jsx(Fn,{id:"contract-value",checked:T.requireValue,onChange:M=>F(ve=>({...ve,requireValue:M})),children:"Conversion value is required"}),e.jsx(Fn,{id:"contract-currency",checked:T.requireCurrency,onChange:M=>F(ve=>({...ve,requireCurrency:M})),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(He,{type:"submit",disabled:O.isPending,children:O.isPending?"Saving…":"Save conversion contract"}),e.jsx(A,{type:"button",variant:"outline",onClick:Ft,children:"Cancel"})]})]})]}):null]})}const Sy=6e4,Cy=["7d","14d","30d"],Zi="not available",ky='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%.',Ay="No Google Ads snapshot stored yet",Ry="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.",Py="No closed days yet",Iy="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.",Ty={"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}),Jr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Ly=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Gn(t,s){return t===null||!Number.isFinite(t)?Zi:s===null?Ly.format(t/1e6):vx(t,s)}function Xr(t){return t===null||!Number.isFinite(t)?Zi:Je(t)}function $y(t,s){return t===null||!Number.isFinite(t)?`${Zi} vs prior ${s}d`:t===0?`no change vs prior ${s}d`:`${t>0?"↑":"↓"} ${Je(Math.abs(t))} vs prior ${s}d`}function qy(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function My(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Ey(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 Dy({projectName:t}){const[s,n]=o.useState("14d"),[a,r]=o.useState(()=>new Set(["costMicros","conversions"])),l=$e({...km({client:ne,path:{name:t},query:{window:s}}),staleTime:Sy}),i=l.data,d=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(Fe,{text:ky})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[It(i.startDate)," to ",It(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(qa,{windows:Cy,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:[d,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(x=>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"})]},x))}),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:[d,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",Ct(l.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:c,daily:h,campaigns:u,comparison:m,comparisonUnavailableReason:f,source:g}=i;if(!g){const x=f==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,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:x?Py:Ay}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:x?Iy:Ry})]})]})}const y=g.currencyCode,p=g.campaignsInInventory>0&&g.campaignsQueried<g.campaignsInInventory?{queried:g.campaignsQueried,inInventory:g.campaignsInInventory}:null,b=c.costMicros>0&&c.conversions===0,C=[{key:"spend",comparable:!0,label:"Spend",value:Gn(c.costMicros,y),change:m?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Jr.format(c.conversions),change:m?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:b?"no conversions":Gn(c.costPerConversionMicros,y),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Xr(c.conversionRate),change:m?.change.conversionRate??null,direction:"up-good",seriesKey:null}],v=[{key:"clicks",label:"Clicks",value:en.format(c.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:en.format(c.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Xr(c.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:Gn(c.cpcMicros,y),seriesKey:null}],$={costMicros:{label:"Spend",color:ct[1],axisId:"spend",formatValue:x=>Gn(x,y)},conversions:{label:"Conversions",color:ct[0],axisId:"conversions",formatValue:x=>Jr.format(x)},clicks:{label:"Clicks",color:ct[2],axisId:"clicks",formatValue:x=>en.format(x)},impressions:{label:"Impressions",color:ct[3],axisId:"impressions",formatValue:x=>en.format(x)}},R=[...a].map(x=>({dataKey:x,...$[x]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,p!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",en.format(p.queried)," of"," ",en.format(p.inInventory)," campaigns, so they are a subset of the account."]}):null,g.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,!m&&f==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:Ty["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:C.map(x=>{const N=x.seriesKey!==null&&a.has(x.seriesKey),w=N&&a.size===1,P=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[x.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:N?$[x.seriesKey].color:"var(--color-mono-600)"}}):null,x.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:x.value}),m&&x.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Ey(x.change,x.direction)}`,children:$y(x.change,m.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:x.comparable?`no prior ${s} period stored`:" "})]});return x.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:P},x.key):e.jsx("button",{type:"button","aria-pressed":N,disabled:w,onClick:()=>r(q=>{const S=new Set(q);return S.has(x.seriesKey)?S.delete(x.seriesKey):S.add(x.seriesKey),S.size===0?q:S}),className:`rounded-md border px-3 py-2 text-left transition-colors ${N?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${w?"cursor-default":""}`,children:P},x.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:v.map(x=>{const N=x.seriesKey!==null&&a.has(x.seriesKey),w=N&&a.size===1,P=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[x.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:N?$[x.seriesKey].color:"var(--color-mono-600)"}}):null,x.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:x.value})]});return x.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:P},x.key):e.jsx("button",{type:"button","aria-pressed":N,disabled:w,onClick:()=>r(q=>{const S=new Set(q);return S.has(x.seriesKey)?S.delete(x.seriesKey):S.add(x.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},x.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(kc,{data:h,xKey:"date",series:R,xTickFormatter:An,labelFormatter:It}),e.jsx("ul",{className:"sr-only",children:h.map(x=>e.jsxs("li",{children:[It(x.date),":"," ",R.map(N=>`${N.label} ${$[N.dataKey].formatValue(x[N.dataKey])}`).join(", "),x.origin==="filled"?", no delivery reported":""]},x.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(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:x.name??x.campaignId,children:x.name??e.jsx("span",{className:"font-mono text-secondary",children:x.campaignId})}),e.jsx("td",{children:e.jsx(ge,{tone:qy(x.status),children:My(x.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:en.format(x.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:en.format(x.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Gn(x.totals.costMicros,y)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Jr.format(x.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Xr(x.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:x.totals.costMicros>0&&x.totals.conversions===0?e.jsx(ge,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:Gn(x.totals.costPerConversionMicros,y)})})]},x.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Pa(Ot(g.capturedAt))," · ","customer ",g.customerId," · ","latest closed day ",It(g.asOfDate),g.openDate?e.jsxs(e.Fragment,{children:[" · ",It(g.openDate)," still open, excluded"]}):null,g.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",g.timeZone]}):null]})]})]})}const Zr=20,zs=50,Oy=50,Fy=50;function eo(t){return t==="viewer"}function to(t){return t?.status==="unavailable"}function ud(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function md(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 er(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 Gy(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 ei(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 Il(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Tl(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 tr(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 Ri(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function ti(t){return Ri(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Pi({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=o.useState(""),[d,c]=o.useState(!1),h=l.trim().toLocaleLowerCase(),u=h?t.filter(y=>y.label.toLocaleLowerCase().includes(h)):t,m=d?u:u.slice(0,Oy),f=m.length<u.length;function g(){const y=new Set([...s,...m.map(p=>p.id)]);n(t.filter(p=>y.has(p.id)).map(p=>p.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:y=>i(y.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(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:m.length===0,onClick:g,children:"Select all shown"}),e.jsx(A,{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 ",m.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:m.map(y=>{const p=s.includes(y.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 ${y.label}`,checked:p,type:"checkbox",onChange:b=>n(ud(s,y.id,b.currentTarget.checked))}),e.jsx("span",{children:y.label})]}),y.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[y.urlCount," URLs"]})]},y.id)})}),f?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function so(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ge,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function no({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(ge,{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),d=t.preview,c=d?.counts.needsAttention??0,h=d?.rows.filter(w=>w.status==="matched")??[],u=d?.rows??[],m=u.filter(w=>w.status!=="matched"),f=Math.max(1,Math.ceil(u.length/zs)),g=Math.min(s,f-1),y=u.slice(g*zs,(g+1)*zs),p=Math.max(1,Math.ceil(m.length/zs)),b=Math.min(a,p-1),C=m.slice(b*zs,(b+1)*zs),v=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,$=h.length>0&&!t.isApplying,R=d!==null&&l===d.previewChecksum,x=m.length>0&&b===p-1;o.useEffect(()=>{n(0),r(0),i(null)},[d?.previewChecksum]);async function N(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=>{N(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
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(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!v,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]}),d?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:[d.counts.matchedRows," matched · ",d.counts.groupsReady," group",d.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),d.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:d.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,d.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 (",d.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:y.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(ge,{tone:Il(w.status),children:Tl(w.status)}),tr(w)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:tr(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 ",g+1," of ",f," · ",d.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:g===0,onClick:()=>n(w=>Math.max(0,w-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:g===f-1,onClick:()=>n(w=>Math.min(f-1,w+1)),children:"Next 50 rows"})]})]}):null,c>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 ",c," row",c===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(ge,{tone:Il(w.status),children:Tl(w.status)}),tr(w)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:tr(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 ",b+1," of ",p]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>r(w=>Math.max(0,w-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===p-1,onClick:()=>r(w=>Math.min(p-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:R,disabled:t.isApplying||!x,onChange:w=>i(w.currentTarget.checked?d.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!$||!R,onClick:()=>{t.onApply(h.map(w=>w.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!$,onClick:()=>{t.onApply(h.map(w=>w.dataRow))},children:t.isApplying?"Creating groups…":`Create ${d.counts.groupsReady} group${d.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const Ky="—";function Uy({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:l=!1,isBusy:i=!1,canContinue:d=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:h,onClearQueryAssignments:u,onRemoveQuery:m,onCreateQueries:f,onCreateAndPairQuestions:g,isCreatingQueries:y=!1,createQueriesError:p=null,onManageProjectQueries:b,groups:C,audience:v,onAudienceChange:$,assignmentImpact:R=null,isPreviewingAssignmentImpact:x=!1,assignmentImpactError:N=null,onRetryAssignmentImpact:w,assignmentNotice:P=null,onReplaceAssignments:q,isReplacingAssignments:S=!1,onBack:G,onContinue:X}){const[T,F]=o.useState(""),[ae,Q]=o.useState(!1),[B,D]=o.useState(!1),[Y,E]=o.useState(""),[W,L]=o.useState(""),[ee,K]=o.useState(null);if(to(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(no,{message:s.message})});const se=eo(t),ce=v,Se=$,Z=er(ce,n,C),me=Z.length,Ce=me>0&&r.length>0&&!l&&!i&&!x&&R!==null&&N===null,J=u??m,he=T.trim().toLocaleLowerCase(),_=he?a.filter(V=>ti(V).toLocaleLowerCase().includes(he)):a,pe=_.filter(V=>(V.propertyIds?.length??0)===0),Me=B?pe:_,Pe=ae?Me:Me.slice(0,Fy),re=Pe.filter(V=>!Ri(V)),be=[...new Set(Y.split(`
|
|
4
4
|
`).map(V=>V.trim()).filter(Boolean))],Ne=[...W.matchAll(/\{([a-z][\w-]*)\}/gi)].map(V=>V[1]),_e=n.filter(V=>Z.includes(V.id)),Oe=Ne.length===0||W.trim()===""?[]:_e.map(V=>({propertyId:V.id,text:Ne.reduce((Le,ze)=>Le.replaceAll(`{${ze}}`,V.label),W.trim())})),O=[...new Set(Oe.map(V=>V.text))];function U(){const V=new Set([...r,...re.map(Le=>Le.id)]);c(a.filter(Le=>V.has(Le.id)).map(Le=>Le.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."})]})}),se?e.jsx(so,{}):null,se?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:ce.kind==="none"?"":ce.kind==="all"?"all":ce.kind==="specific"?"specific":`group:${ce.groupIds[0]??""}`,onChange:V=>{const Le=V.currentTarget.value;Le==="all"?Se({kind:"all"}):Le==="specific"?Se({kind:"specific",propertyIds:[]}):Le.startsWith("group:")&&Se({kind:"groups",groupIds:[Le.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(V=>{const Le=er({kind:"groups",groupIds:[V.id]},n,C).length;return e.jsx("option",{value:`group:${V.id}`,disabled:Le===0,children:ei(V,n)},V.id)})}):null,e.jsx("option",{value:"specific",children:"Specific locations…"})]})]})}),ce.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:ce.groupIds.map(V=>{const Le=C.find(ze=>ze.id===V);return Le?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:[ei(Le,n),e.jsx("button",{type:"button","aria-label":`Remove ${Le.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 ze=ce.groupIds.filter(Ue=>Ue!==Le.id);Se(ze.length>0?{kind:"groups",groupIds:ze}:{kind:"none"})},children:"×"})]},Le.id):null})}),C.some(V=>!ce.groupIds.includes(V.id)&&er({kind:"groups",groupIds:[V.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:V=>{V.currentTarget.value&&Se({kind:"groups",groupIds:[...ce.groupIds,V.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(V=>!ce.groupIds.includes(V.id)).map(V=>{const Le=er({kind:"groups",groupIds:[V.id]},n,C).length;return e.jsx("option",{value:V.id,disabled:Le===0,children:ei(V,n)},V.id)})]})]}):null,me===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,ce.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(Pi,{legend:"Specific locations",properties:n,selectedPropertyIds:ce.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:V=>{Se({kind:"specific",propertyIds:V})}})}):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."})]}),se||!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:Y,onChange:V=>E(V.currentTarget.value),placeholder:`best apartments in dallas
|